Clément Simon commited on
Commit
f4b52a8
1 Parent(s): 4b66965

hello world

Browse files
Files changed (1) hide show
  1. app.py +209 -206
app.py CHANGED
@@ -9,7 +9,7 @@ import uvicorn
9
  from dotenv import load_dotenv
10
  from fastapi import FastAPI
11
  from fastapi.staticfiles import StaticFiles
12
- from mistralai.client import ChatMessage, MistralClient
13
  from pydantic import BaseModel
14
  from fastapi import Depends
15
  import json
@@ -19,7 +19,7 @@ from fastapi.responses import HTMLResponse
19
  # Load environment variables
20
  load_dotenv()
21
  api_key = os.getenv('API_KEY')
22
- client = MistralClient(api_key=api_key)
23
  model = 'mistral-small'
24
 
25
  title = "Gaia Mistral Chat Demo"
@@ -32,207 +32,210 @@ examples = ["Comment fait on pour produire du maïs ?",
32
  # create a FastAPI app
33
  app = FastAPI()
34
 
35
- # create a static directory to store the static files
36
- static_dir = Path('./static')
37
- static_dir.mkdir(parents=True, exist_ok=True)
38
-
39
- # mount FastAPI StaticFiles server
40
- app.mount("/static", StaticFiles(directory=static_dir), name="static")
41
-
42
-
43
- # Gradio stuff
44
-
45
- def predict(text_input):
46
- file_name = f"{datetime.utcnow().strftime('%s')}.html"
47
- file_path = static_dir / file_name
48
- print(file_path)
49
- with open(file_path, "w") as f:
50
- f.write(f"""
51
- <script src="https://cdn.tailwindcss.com"></script>
52
- <body class="bg-gray-200 dark:text-white dark:bg-gray-900">
53
- <h1 class="text-3xl font-bold">
54
- Hello <i>{text_input}</i> From Gradio Iframe
55
- </h1>
56
- <h3>Filename: {file_name}</h3>
57
- """)
58
- iframe = f"""<iframe src="/static/{file_name}" width="100%" height="500px"></iframe>"""
59
- link = f'<a href="/static/{file_name}" target="_blank">{file_name}</a>'
60
- return link, iframe
61
-
62
-
63
- with gr.Blocks() as block:
64
- gr.Markdown("""
65
- ## Gradio + FastAPI + Static Server
66
- This is a demo of how to use Gradio with FastAPI and a static server.
67
- The Gradio app generates dynamic HTML files and stores them in a static directory. FastAPI serves the static files.
68
- """)
69
- with gr.Row():
70
- with gr.Column():
71
- text_input = gr.Textbox(label="Name")
72
- markdown = gr.Markdown(label="Output Box")
73
- new_btn = gr.Button("New")
74
- with gr.Column():
75
- html = gr.HTML(label="HTML preview", show_label=True)
76
-
77
- new_btn.click(fn=predict, inputs=[text_input], outputs=[markdown, html])
78
-
79
-
80
- def create_world_map(lat, lon):
81
-
82
- fig = go.Figure(go.Scattermapbox(
83
- lat=[lat],
84
- lon=[lon],
85
- mode='markers',
86
- marker=go.scattermapbox.Marker(size=14),
87
- text=['Location'],
88
- ))
89
-
90
- fig.update_layout(
91
- mapbox_style="open-street-map",
92
- hovermode='closest',
93
- mapbox=dict(
94
- bearing=0,
95
- center=go.layout.mapbox.Center(
96
- lat=lat,
97
- lon=lon,
98
- ),
99
- pitch=0,
100
- zoom=5
101
- ),
102
- )
103
-
104
- return fig
105
-
106
-
107
- # # Fake JSON data for the user profile
108
- # user_profile_data = {
109
- # "name": "John Doe",
110
- # "age": 30,
111
- # "location": "Montreal",
112
- # "lat": 45.5017,
113
- # "lon": -73.5673
114
- # }
115
-
116
- # #as a JSON:
117
- # with open('user_profile.json', 'w') as f:
118
- # json.dump(user_profile_data, f)
119
-
120
- # Mistral AI Chat
121
-
122
- def chat_with_mistral(user_input):
123
- messages = [ChatMessage(role="user", content=user_input)]
124
-
125
- chat_response = client.chat(model=model, messages=messages)
126
- return chat_response.choices[0].message.content
127
-
128
-
129
- ### FRONTEND ###
130
- def create_gradio_dashboard():
131
- with gr.Blocks() as demo:
132
- # Mistral AI Chat
133
- with gr.Column():
134
- with gr.Row():
135
- user_input = gr.Textbox (lines=2, placeholder=placeholder)
136
- send_chat_btn = gr.Button(value="Send")
137
- update_map_btn = gr.Button(value="Update Map")
138
- chat_output = gr.Textbox(lines=2, placeholder="Réponse")
139
-
140
- # Profile
141
- with gr.Row():
142
- name = gr.Textbox(label="Name")
143
- age = gr.Number(label="Age")
144
- location = gr.Textbox(label="Location")
145
- lat = gr.Number(value=45.5017, label="Latitude")
146
- lon = gr.Number(value=-73.5673, label="Longitude")
147
- load_user_profile_btn = gr.Button(value="Load User Profile")
148
- save_user_profile_btn = gr.Button(value="Save User Profile")
149
-
150
- # Map
151
- with gr.Row():
152
- map = gr.Plot()
153
-
154
- # Mistral AI Chat
155
- demo.load(chat_with_mistral, user_input, chat_output)
156
- send_chat_btn.click(chat_with_mistral, user_input, chat_output)
157
-
158
- return demo
159
-
160
-
161
- # Profile stuff
162
- class UserProfile(BaseModel):
163
- name: str
164
- age: int
165
- location: str
166
- lat: float
167
- lon: float
168
-
169
- @app.post("/user_profile")
170
- def save_user_profile(user_profile: UserProfile):
171
- with open('user_profile.json', 'w') as f:
172
- json.dump(user_profile.dict(), f)
173
- return user_profile.dict()
174
-
175
- @app.get("/user_profile")
176
- def load_user_profile():
177
- with open('user_profile.json', 'r') as f:
178
- user_profile = json.load(f)
179
- return UserProfile(**user_profile)
180
-
181
- @app.put("/user_profile")
182
- def update_user_profile(user_profile: UserProfile):
183
- with open('user_profile.json', 'w') as f:
184
- json.dump(user_profile.dict(), f)
185
- return user_profile
186
-
187
- # load user profile on startup
188
- user_profile = load_user_profile()
189
-
190
-
191
- ### BACKEND ###
192
- @app.get("/meteo")
193
- async def read_meteo(location: str, date: str):
194
- # API call to get the weather
195
- pass
196
-
197
- # Home page : using the user profile, display the weather and chat with Mistral AI
198
- @app.get("/", response_class=HTMLResponse)
199
- async def home(user_profile: UserProfile = Depends(load_user_profile)):
200
-
201
- #1st : display as background the map of the user location:
202
- # get the user location
203
- lat = user_profile.lat
204
- lon = user_profile.lon
205
- # create the map
206
- fig = create_world_map(lat, lon)
207
- # save the map as a file
208
- map_file = static_dir / "map.html"
209
- fig.write_html(str(map_file))
210
- # display the map
211
- map_html = f'<iframe src="/static/map.html" width="100%" height="500px"></iframe>'
212
-
213
- #2nd : gradio dashboard on top of the map to toggle the user profile and display chat with Mistral AI
214
- # create the gradio dashboard
215
- # gradio_dashboard = create_gradio_dashboard()
216
- # save the dashboard as a file
217
- # dashboard_file = static_dir / "dashboard.html"
218
- # gradio_dashboard.save(dashboard_file)
219
- # # display the dashboard
220
- # dashboard_html = f'<iframe src="/static/dashboard.html" width="100%" height="500px"></iframe>'
221
-
222
- return f"""
223
- <h1>Welcome to the home page</h1>
224
- <h2>User Profile</h2>
225
- <p>Name: {user_profile.name}</p>
226
- <p>Age: {user_profile.age}</p>
227
- <p>Location: {user_profile.location}</p>
228
- <p>Latitude: {user_profile.lat}</p>
229
- <p>Longitude: {user_profile.lon}</p>
230
- <h2>Map</h2>
231
- {map_html}
232
- """
233
- # <h2>Gradio Dashboard</h2>
234
- # {dashboard_html}
235
-
236
- # # serve the app for local use with uvicorn
237
- # if __name__ == "__main__":
238
- # uvicorn.run(app, host="0.0.0.0", port=7860)
 
 
 
 
9
  from dotenv import load_dotenv
10
  from fastapi import FastAPI
11
  from fastapi.staticfiles import StaticFiles
12
+ # from mistralai.client import ChatMessage, MistralClient
13
  from pydantic import BaseModel
14
  from fastapi import Depends
15
  import json
 
19
  # Load environment variables
20
  load_dotenv()
21
  api_key = os.getenv('API_KEY')
22
+ # client = MistralClient(api_key=api_key)
23
  model = 'mistral-small'
24
 
25
  title = "Gaia Mistral Chat Demo"
 
32
  # create a FastAPI app
33
  app = FastAPI()
34
 
35
+ @app.get("/")
36
+ async def read_root():
37
+ return {"Hello": "World"}
38
+ # # create a static directory to store the static files
39
+ # static_dir = Path('./static')
40
+ # static_dir.mkdir(parents=True, exist_ok=True)
41
+
42
+ # # mount FastAPI StaticFiles server
43
+ # app.mount("/static", StaticFiles(directory=static_dir), name="static")
44
+
45
+
46
+ # # Gradio stuff
47
+
48
+ # def predict(text_input):
49
+ # file_name = f"{datetime.utcnow().strftime('%s')}.html"
50
+ # file_path = static_dir / file_name
51
+ # print(file_path)
52
+ # with open(file_path, "w") as f:
53
+ # f.write(f"""
54
+ # <script src="https://cdn.tailwindcss.com"></script>
55
+ # <body class="bg-gray-200 dark:text-white dark:bg-gray-900">
56
+ # <h1 class="text-3xl font-bold">
57
+ # Hello <i>{text_input}</i> From Gradio Iframe
58
+ # </h1>
59
+ # <h3>Filename: {file_name}</h3>
60
+ # """)
61
+ # iframe = f"""<iframe src="/static/{file_name}" width="100%" height="500px"></iframe>"""
62
+ # link = f'<a href="/static/{file_name}" target="_blank">{file_name}</a>'
63
+ # return link, iframe
64
+
65
+
66
+ # with gr.Blocks() as block:
67
+ # gr.Markdown("""
68
+ # ## Gradio + FastAPI + Static Server
69
+ # This is a demo of how to use Gradio with FastAPI and a static server.
70
+ # The Gradio app generates dynamic HTML files and stores them in a static directory. FastAPI serves the static files.
71
+ # """)
72
+ # with gr.Row():
73
+ # with gr.Column():
74
+ # text_input = gr.Textbox(label="Name")
75
+ # markdown = gr.Markdown(label="Output Box")
76
+ # new_btn = gr.Button("New")
77
+ # with gr.Column():
78
+ # html = gr.HTML(label="HTML preview", show_label=True)
79
+
80
+ # new_btn.click(fn=predict, inputs=[text_input], outputs=[markdown, html])
81
+
82
+
83
+ # def create_world_map(lat, lon):
84
+
85
+ # fig = go.Figure(go.Scattermapbox(
86
+ # lat=[lat],
87
+ # lon=[lon],
88
+ # mode='markers',
89
+ # marker=go.scattermapbox.Marker(size=14),
90
+ # text=['Location'],
91
+ # ))
92
+
93
+ # fig.update_layout(
94
+ # mapbox_style="open-street-map",
95
+ # hovermode='closest',
96
+ # mapbox=dict(
97
+ # bearing=0,
98
+ # center=go.layout.mapbox.Center(
99
+ # lat=lat,
100
+ # lon=lon,
101
+ # ),
102
+ # pitch=0,
103
+ # zoom=5
104
+ # ),
105
+ # )
106
+
107
+ # return fig
108
+
109
+
110
+ # # # Fake JSON data for the user profile
111
+ # # user_profile_data = {
112
+ # # "name": "John Doe",
113
+ # # "age": 30,
114
+ # # "location": "Montreal",
115
+ # # "lat": 45.5017,
116
+ # # "lon": -73.5673
117
+ # # }
118
+
119
+ # # #as a JSON:
120
+ # # with open('user_profile.json', 'w') as f:
121
+ # # json.dump(user_profile_data, f)
122
+
123
+ # # Mistral AI Chat
124
+
125
+ # def chat_with_mistral(user_input):
126
+ # messages = [ChatMessage(role="user", content=user_input)]
127
+
128
+ # chat_response = client.chat(model=model, messages=messages)
129
+ # return chat_response.choices[0].message.content
130
+
131
+
132
+ # ### FRONTEND ###
133
+ # def create_gradio_dashboard():
134
+ # with gr.Blocks() as demo:
135
+ # # Mistral AI Chat
136
+ # with gr.Column():
137
+ # with gr.Row():
138
+ # user_input = gr.Textbox (lines=2, placeholder=placeholder)
139
+ # send_chat_btn = gr.Button(value="Send")
140
+ # update_map_btn = gr.Button(value="Update Map")
141
+ # chat_output = gr.Textbox(lines=2, placeholder="Réponse")
142
+
143
+ # # Profile
144
+ # with gr.Row():
145
+ # name = gr.Textbox(label="Name")
146
+ # age = gr.Number(label="Age")
147
+ # location = gr.Textbox(label="Location")
148
+ # lat = gr.Number(value=45.5017, label="Latitude")
149
+ # lon = gr.Number(value=-73.5673, label="Longitude")
150
+ # load_user_profile_btn = gr.Button(value="Load User Profile")
151
+ # save_user_profile_btn = gr.Button(value="Save User Profile")
152
+
153
+ # # Map
154
+ # with gr.Row():
155
+ # map = gr.Plot()
156
+
157
+ # # Mistral AI Chat
158
+ # demo.load(chat_with_mistral, user_input, chat_output)
159
+ # send_chat_btn.click(chat_with_mistral, user_input, chat_output)
160
+
161
+ # return demo
162
+
163
+
164
+ # # Profile stuff
165
+ # class UserProfile(BaseModel):
166
+ # name: str
167
+ # age: int
168
+ # location: str
169
+ # lat: float
170
+ # lon: float
171
+
172
+ # @app.post("/user_profile")
173
+ # def save_user_profile(user_profile: UserProfile):
174
+ # with open('user_profile.json', 'w') as f:
175
+ # json.dump(user_profile.dict(), f)
176
+ # return user_profile.dict()
177
+
178
+ # @app.get("/user_profile")
179
+ # def load_user_profile():
180
+ # with open('user_profile.json', 'r') as f:
181
+ # user_profile = json.load(f)
182
+ # return UserProfile(**user_profile)
183
+
184
+ # @app.put("/user_profile")
185
+ # def update_user_profile(user_profile: UserProfile):
186
+ # with open('user_profile.json', 'w') as f:
187
+ # json.dump(user_profile.dict(), f)
188
+ # return user_profile
189
+
190
+ # # load user profile on startup
191
+ # user_profile = load_user_profile()
192
+
193
+
194
+ # ### BACKEND ###
195
+ # @app.get("/meteo")
196
+ # async def read_meteo(location: str, date: str):
197
+ # # API call to get the weather
198
+ # pass
199
+
200
+ # # Home page : using the user profile, display the weather and chat with Mistral AI
201
+ # @app.get("/", response_class=HTMLResponse)
202
+ # async def home(user_profile: UserProfile = Depends(load_user_profile)):
203
+
204
+ # #1st : display as background the map of the user location:
205
+ # # get the user location
206
+ # lat = user_profile.lat
207
+ # lon = user_profile.lon
208
+ # # create the map
209
+ # fig = create_world_map(lat, lon)
210
+ # # save the map as a file
211
+ # map_file = static_dir / "map.html"
212
+ # fig.write_html(str(map_file))
213
+ # # display the map
214
+ # map_html = f'<iframe src="/static/map.html" width="100%" height="500px"></iframe>'
215
+
216
+ # #2nd : gradio dashboard on top of the map to toggle the user profile and display chat with Mistral AI
217
+ # # create the gradio dashboard
218
+ # # gradio_dashboard = create_gradio_dashboard()
219
+ # # save the dashboard as a file
220
+ # # dashboard_file = static_dir / "dashboard.html"
221
+ # # gradio_dashboard.save(dashboard_file)
222
+ # # # display the dashboard
223
+ # # dashboard_html = f'<iframe src="/static/dashboard.html" width="100%" height="500px"></iframe>'
224
+
225
+ # return f"""
226
+ # <h1>Welcome to the home page</h1>
227
+ # <h2>User Profile</h2>
228
+ # <p>Name: {user_profile.name}</p>
229
+ # <p>Age: {user_profile.age}</p>
230
+ # <p>Location: {user_profile.location}</p>
231
+ # <p>Latitude: {user_profile.lat}</p>
232
+ # <p>Longitude: {user_profile.lon}</p>
233
+ # <h2>Map</h2>
234
+ # {map_html}
235
+ # """
236
+ # # <h2>Gradio Dashboard</h2>
237
+ # # {dashboard_html}
238
+
239
+ # # # serve the app for local use with uvicorn
240
+ # # if __name__ == "__main__":
241
+ # # uvicorn.run(app, host="0.0.0.0", port=7860)