File size: 5,539 Bytes
46cb2c1
89a989f
 
 
03605b7
89a989f
 
 
 
 
5d5012e
f995bfa
89a989f
 
6c1b1ab
03605b7
11f3d81
89a989f
11f3d81
 
 
02bf179
3a5876b
 
05dc014
d97bc09
3a5876b
 
 
 
ac5a5f0
9007b86
bae1ef6
 
 
deb4c46
bae1ef6
05dc014
bae1ef6
 
 
0adf31a
 
 
a8dbfbb
 
 
3a5876b
0adf31a
 
deb4c46
 
d97bc09
0adf31a
e30c98b
 
 
 
 
d97bc09
93e16a9
e30c98b
0162874
f396048
 
0162874
f210abf
85a39de
4124d44
 
 
 
f210abf
 
 
4124d44
 
 
 
f210abf
 
5d5012e
4535f52
f210abf
 
4124d44
85a39de
 
0adf31a
 
f210abf
 
 
ac5a5f0
c5acf4e
11f3d81
 
4d16357
 
 
 
 
 
 
 
 
 
329c810
89a989f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4c8fb8e
89a989f
 
 
 
 
 
 
4c8fb8e
89a989f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4d16357
c5acf4e
 
 
4d16357
 
 
 
c5acf4e
411b5ed
 
 
 
 
3c4f927
c8a3a1d
4d16357
89a989f
 
 
 
 
 
 
e189cc3
c5acf4e
89a989f
 
 
 
eb922b4
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
from fasthtml.common import *
from openai import OpenAI # openai==1.2.0
from dotenv import load_dotenv, find_dotenv
_ = load_dotenv(find_dotenv())

upstage_token  = os.getenv('UPSTAGE_TOKEN')

# Set up the app, including daisyui and tailwind for the chat component
hdrs = (picolink, Script(src="https://cdn.tailwindcss.com"),
    Link(rel="stylesheet", href="https://cdn.jsdelivr.net/npm/[email protected]/dist/full.min.css"))
#app = FastHTML(hdrs=hdrs, cls="p-4 max-w-lg mx-auto")
app = FastHTML(hdrs=hdrs)

#app = FastHTML()
rt = app.route

style="""
#mapid { height: 480px; }
"""

js = """
let map = null;
function load()
{
	//map = L.map('mapid').setView([37.5158, 127.0991], 13);
	map = L.map('mapid').setView([33.4311, 126.5499], 10);
	L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {
	    maxZoom: 19,
	    attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>'
	}).addTo(map);
	//alert('loading...');



	$( "#chat_form" ).on( "submit", function( event ) {
  		//alert( "Handler for `submit` called." );
  		//event.preventDefault();
		setTimeout(handle_post, 15000);
	});


	//messages_input = $("#chat_form :input[name='messages']");
	//alert(messages_input);
	//console.log(messages_input);
	//messages_input.change(function(){
	  //alert("The text has been changed.");
	//});
}

function handle_post() {
//messages_input = $("#chat_form :input[name='messages']").value;
messages_input = $( "input" ).last().val()
//alert(messages_input);
console.log(messages_input);
res = JSON.parse(messages_input);
//var marker = L.marker([51.5, -0.09]).addTo(map);

var rec_list = res['recommendations']

//alert(rec_list);
console.log(rec_list);

marker_count = 0;
lat_sum = 0;
lng_sum = 0;

rec_list.forEach((elem) => addElem(elem));

avg_lat = lat_sum / marker_count;
avg_lng = lng_sum / marker_count;

map.setView([avg_lat, avg_lng], 10);

}

let marker_count = 0;
let lat_sum = 0;
let lng_sum = 0;

function addElem(elem)
{
	//var marker = L.marker([elem['latitude'], elem['longitude']]).addTo(map);
	var marker = L.marker([elem['latitude'], elem['longitude']]).addTo(map);
	marker.bindPopup(elem['name'])

	marker_count++;
	lat_sum += elem['latitude'];
	lng_sum += elem['longitude'];
}




setTimeout(load, 1000);

"""

# @rt('/')
# def get():
# 	return Titled("MinorityMap",
# 		Link(rel="stylesheet", href="https://unpkg.com/[email protected]/dist/leaflet.css"),
# 		Style(style),
# 		Script(src="https://unpkg.com/[email protected]/dist/leaflet.js"),
# 		#Body(onload='load()'),
# 		Div(id='mapid'),
# 		Script(js)
# 		)





client = OpenAI(
    api_key=upstage_token,
    base_url="https://api.upstage.ai/v1/solar"
)

sp = "You are a helpful and concise assistant."

def get_completion(prompt, model="solar-1-mini-chat"):
    messages = [{"role": "user", "content": prompt}]
    response = client.chat.completions.create(
        model=model,
        messages=messages,
        temperature=0, # this is the degree of randomness of the model's output
    )
    return response.choices[-1].message.content

def get_completion_from_messages(messages, model="solar-1-mini-chat", temperature=0):
    response = client.chat.completions.create(
        model=model,
        messages=messages,
        temperature=temperature, # this is the degree of randomness of the model's output
    )
    return response.choices[-1].message.content

# Chat message component (renders a chat bubble)
def ChatMessage(msg, user):
    bubble_class = "chat-bubble-primary" if user else 'chat-bubble-secondary'
    chat_class = "chat-end" if user else 'chat-start'
    return Div(cls=f"chat {chat_class}")(
               Div('user' if user else 'assistant', cls="chat-header"),
               Div(msg, cls=f"chat-bubble {bubble_class}"),
               Hidden(msg, name="messages")
           )

# The input field for the user message. Also used to clear the
# input field after sending a message via an OOB swap
def ChatInput():
    return Input(name='msg', id='msg-input', placeholder="Type a message",
                 cls="input input-bordered w-full", hx_swap_oob='true')

# The main screen
@app.get
def index():
    return Titled("MinorityMap",
		Link(rel="stylesheet", href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.9.2/themes/ui-darkness/jquery-ui.css"),
		Script(src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"),
		Script(src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.9.2/jquery-ui.min.js"),
		Link(rel="stylesheet", href="https://unpkg.com/[email protected]/dist/leaflet.css"),
		Style(style),
		Script(src="https://unpkg.com/[email protected]/dist/leaflet.js"),
		#Body(onload='load()'),
		Form(id="chat_form", hx_post=send, hx_target="#chatlist", hx_swap="beforeend")(
			   Div(id='mapid'),
	               Div(cls="flex space-x-2 mt-2")(
	                   Group(ChatInput(), Button("Send", cls="btn btn-primary"))
	               )
	           ),
			   Div(id="chatlist", cls="chat-box h-[73vh] overflow-y-auto"),
		Script(js)
		)

# Handle the form submission
@app.post
def send(msg:str, messages:list[str]=None):
    if not messages: messages = []
    messages.append(msg.rstrip())
    print(messages[0])
    post_append_str = ' Return as a JSON response with GeoLocation'
    r = get_completion(messages[0] + post_append_str) # get response from chat model
    return (ChatMessage(msg, True),    # The user's message
            ChatMessage(r.rstrip(), False), # The chatbot's response
            ChatInput()) # And clear the input field via an OOB swap

serve()