datacipen commited on
Commit
5e9d705
·
verified ·
1 Parent(s): b24750a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +273 -17
app.py CHANGED
@@ -1,9 +1,11 @@
1
  import os
2
  import datetime
3
  import requests
 
4
  from offres_emploi import Api
5
  from offres_emploi.utils import dt_to_str_iso
6
  from dash import Dash, html, dcc, callback, Output, Input, dash_table, State, _dash_renderer
 
7
  import plotly.express as px
8
  import dash_mantine_components as dmc
9
  from dash_iconify import DashIconify
@@ -11,16 +13,19 @@ import pandas as pd
11
  from dotenv import load_dotenv
12
  _dash_renderer._set_react_version("18.2.0")
13
  import plotly.io as pio
 
 
 
 
14
  from flask import Flask
15
 
 
 
16
  # external JavaScript files
17
  external_scripts = [
18
  'https://datacipen-eventia.hf.space/copilot/index.js'
19
  ]
20
-
21
- server = Flask(__name__)
22
-
23
- # Create a customized version of the plotly_dark theme with a modified background color.
24
  custom_plotly_dark_theme = {
25
  "layout": {
26
  "paper_bgcolor": "#1E1E1E", # Update the paper background color
@@ -195,14 +200,36 @@ theme_toggle = dmc.Tooltip(
195
  )
196
 
197
  styleTitle = {
198
- "textAlign": "center",
199
- "color": dmc.DEFAULT_THEME["colors"]["orange"][4]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
200
  }
201
 
202
  styleToggle = {
203
  "marginTop":"25px",
204
  "textAlign": "right",
205
  }
 
 
 
 
 
 
206
  datadefault = [
207
  {"value": "K2105", "label": "K2105"},
208
  {"value": "L1101", "label": "L1101"},
@@ -211,12 +238,106 @@ datadefault = [
211
  {"value": "L1508", "label": "L1508"},
212
  {"value": "L1509", "label": "L1509"},
213
  ]
 
214
  def custom_error_handler(err):
215
  # This function defines what we want to happen when an exception occurs
216
  # For now, we just print the exception to the terminal with additional text
217
  print(f"The app raised the following exception: {err}")
 
 
 
 
 
 
 
 
 
 
218
 
219
- app = Dash(__name__, external_scripts=external_scripts, server=server, external_stylesheets=dmc.styles.ALL, on_error=custom_error_handler)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
220
 
221
  app.layout = dmc.MantineProvider(
222
  [
@@ -227,22 +348,42 @@ app.layout = dmc.MantineProvider(
227
  dmc.Grid(
228
  children=[
229
  dmc.GridCol(html.Div(
 
230
  dmc.MultiSelect(
231
- label="Selectionnez vos Codes ROME",
232
- placeholder="Select vos Codes ROME parmi la liste",
233
  id="framework-multi-select",
234
  value=['K2105', 'L1101', 'L1202', 'L1507', 'L1508', 'L1509'],
235
  data=datadefault,
236
  w=600,
237
- mb=10,
238
  styles={
239
- "input": {"borderColor": dmc.DEFAULT_THEME["colors"]["orange"][2]},
240
  "label": {"color": dmc.DEFAULT_THEME["colors"]["orange"][4]},
241
  },
242
- )
243
- ), span=6),
244
- dmc.GridCol(html.Div(dmc.Title(f"Le marché et les statistiques de l'emploi", order=1, size="30", my="20", style=styleTitle)), span=5),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
245
  dmc.GridCol(html.Div(theme_toggle, style=styleToggle), span=1),
 
246
  dmc.GridCol(html.Div(
247
  dcc.Loading(
248
  id="loadingRepartition",
@@ -341,14 +482,23 @@ app.layout = dmc.MantineProvider(
341
  def switch_theme(_, theme):
342
  return "dark" if theme == "light" else "light"
343
 
 
 
 
 
 
 
 
 
344
  @callback(
345
  Output(component_id='figRepartition', component_property='figure'),
346
  Output(component_id='figCompetences', component_property='figure'),
347
  Output(component_id='figTransversales', component_property='figure'),
348
  Input(component_id='framework-multi-select', component_property='value'),
 
349
  Input("mantine-provider", "forceColorScheme"),
350
  )
351
- def create_repartition(array_value, theme):
352
  if theme == "dark":
353
  template = "plotly_dark"
354
  paper_bgcolor = 'rgba(36, 36, 36, 1)'
@@ -368,6 +518,18 @@ def create_repartition(array_value, theme):
368
  df.drop(df[df['lieuTravail'] == 'Bou'].index, inplace = True)
369
  df.drop(df[df['lieuTravail'] == '976'].index, inplace = True)
370
 
 
 
 
 
 
 
 
 
 
 
 
 
371
  ######## localisation ########
372
  ListCentroids = localisation()
373
  df_localisation = df.groupby('lieuTravail').size().reset_index(name='obs')
@@ -378,6 +540,8 @@ def create_repartition(array_value, theme):
378
  df_localisation["longitude"] = pd.to_numeric(df_localisation["longitude"], downcast="float")
379
  df_localisation["latitude"] = df_localisation['latitude'].apply(lambda x:[loc['Latitude'] for loc in ListCentroids if loc['ID'] == x]).apply(lambda x:''.join(map(str, x)))
380
  df_localisation["latitude"] = pd.to_numeric(df_localisation["latitude"], downcast="float")
 
 
381
  res = requests.get(
382
  "https://raw.githubusercontent.com/codeforgermany/click_that_hood/main/public/data/france-regions.geojson"
383
  )
@@ -408,7 +572,7 @@ def create_repartition(array_value, theme):
408
  df_comp = df_comp.groupby('competences').size().reset_index(name='obs')
409
  df_comp = df_comp.sort_values(by=['obs'])
410
  df_comp = df_comp.iloc[-20:]
411
- fig_competences = px.bar(df_comp, x='obs', y='competences', orientation='h', color='obs', height=600, template=template, title="Les principales compétences professionnelles", labels={'obs':'nombre'}, color_continuous_scale="Teal", text_auto=True).update_layout(font=dict(size=10),paper_bgcolor=paper_bgcolor,plot_bgcolor=plot_bgcolor,autosize=True).update_traces(hovertemplate=df_comp["competences"] + ' <br>Nombre : %{x}', y=[y[:100] + "..." for y in df_comp['competences']], showlegend=False)
412
 
413
  ######## Compétences transversales ########
414
  df_transversales = df_FT
@@ -434,7 +598,7 @@ def create_emploi(df, theme):
434
  df_intitule = df.groupby('intitule').size().reset_index(name='obs')
435
  df_intitule = df_intitule.sort_values(by=['obs'])
436
  df_intitule = df_intitule.iloc[-25:]
437
- fig_intitule = px.bar(df_intitule, x='obs', y='intitule', height=600, orientation='h', color='obs', template=template, title="Les principaux emplois", labels={'obs':'nombre'}, color_continuous_scale="Teal", text_auto=True).update_layout(font=dict(size=10),paper_bgcolor=paper_bgcolor,plot_bgcolor=plot_bgcolor, autosize=True).update_traces(hovertemplate=df_intitule["intitule"] + ' <br>Nombre : %{x}', y=[y[:100] + "..." for y in df_intitule["intitule"]], showlegend=False)
438
 
439
  return fig_intitule
440
 
@@ -553,6 +717,98 @@ def update_experience(selectedData, array_value, theme):
553
  df = df[df['lieuTravail'].isin(options)]
554
 
555
  return create_experience(df, theme)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
556
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
557
  if __name__ == '__main__':
558
  app.run_server(debug=True)
 
1
  import os
2
  import datetime
3
  import requests
4
+ import textwrap
5
  from offres_emploi import Api
6
  from offres_emploi.utils import dt_to_str_iso
7
  from dash import Dash, html, dcc, callback, Output, Input, dash_table, State, _dash_renderer
8
+ import dash_bootstrap_components as dbc
9
  import plotly.express as px
10
  import dash_mantine_components as dmc
11
  from dash_iconify import DashIconify
 
13
  from dotenv import load_dotenv
14
  _dash_renderer._set_react_version("18.2.0")
15
  import plotly.io as pio
16
+ from langchain_community.llms import HuggingFaceEndpoint
17
+ from langchain_core.prompts import ChatPromptTemplate, PromptTemplate
18
+ from langchain.schema.output_parser import StrOutputParser
19
+
20
  from flask import Flask
21
 
22
+ server = Flask(__name__)
23
+
24
  # external JavaScript files
25
  external_scripts = [
26
  'https://datacipen-eventia.hf.space/copilot/index.js'
27
  ]
28
+ # Create a customized version of the plotly_dark theme with a modified background color
 
 
 
29
  custom_plotly_dark_theme = {
30
  "layout": {
31
  "paper_bgcolor": "#1E1E1E", # Update the paper background color
 
200
  )
201
 
202
  styleTitle = {
203
+ "textAlign": "center"
204
+ }
205
+ styleUSERIA = {
206
+ "textAlign": "right",
207
+ "marginBottom" : "5px"
208
+ }
209
+ styleSUBMITIA = {
210
+ "marginLeft":"auto",
211
+ "marginRight":"auto",
212
+ "marginTop": "5px",
213
+ "marginBottom" : "5px"
214
+ }
215
+ styleSYSIA = {
216
+ "marginTop":"10px",
217
+ "marginBottom":"120px",
218
+ }
219
+ styleTopvar = {
220
+ "display": "none"
221
  }
222
 
223
  styleToggle = {
224
  "marginTop":"25px",
225
  "textAlign": "right",
226
  }
227
+ styleSubmitBox = {
228
+ "position":"fixed",
229
+ "width": "100%",
230
+ "top": "calc(100vh - 100px)",
231
+ "right": "0"
232
+ }
233
  datadefault = [
234
  {"value": "K2105", "label": "K2105"},
235
  {"value": "L1101", "label": "L1101"},
 
238
  {"value": "L1508", "label": "L1508"},
239
  {"value": "L1509", "label": "L1509"},
240
  ]
241
+
242
  def custom_error_handler(err):
243
  # This function defines what we want to happen when an exception occurs
244
  # For now, we just print the exception to the terminal with additional text
245
  print(f"The app raised the following exception: {err}")
246
+ def textbox(text, box="AI", name="Philippe"):
247
+ text = text.replace(f"{name}:", "").replace("You:", "")
248
+ #text = textile.textile(text)
249
+ style = {
250
+ "max-width": "60%",
251
+ "width": "max-content",
252
+ "padding": "5px 10px",
253
+ "border-radius": 25,
254
+ "margin-bottom": 20,
255
+ }
256
 
257
+ if box == "user":
258
+ style["margin-left"] = "auto"
259
+ style["margin-right"] = 0
260
+
261
+ #return dbc.Card(text, style=style, body=True, color="primary", inverse=True)
262
+ return html.Div(dmc.Button(text, variant="gradient", gradient={"from": "grape", "to": "pink", "deg": 35}), style=styleUSERIA)
263
+
264
+ elif box == "AI":
265
+ style["margin-left"] = 0
266
+ style["margin-right"] = "auto"
267
+
268
+ thumbnail = html.Img(
269
+ src=app.get_asset_url("sparkles.gif"),
270
+ style={
271
+ "border-radius": 50,
272
+ "height": 36,
273
+ "margin-right": 5,
274
+ "float": "left",
275
+ },
276
+ )
277
+ #textbox = dbc.Card(text, style=style, body=True, color="light", inverse=False)
278
+ #textbox = dmc.Blockquote(text, style=styleSYSIA)
279
+ textbox = dmc.Card(children=[dmc.Text(text,size="sm",c="dimmed")],withBorder=False,w="100%", style=styleSYSIA)
280
+ return html.Div([thumbnail, textbox])
281
+
282
+ else:
283
+ raise ValueError("Incorrect option for `box`.")
284
+
285
+
286
+ #description = """
287
+ #Philippe is the principal architect at a condo-development firm in Paris. He lives with his girlfriend of five years in a 2-bedroom condo, with a small dog named Coco. Since the pandemic, his firm has seen a significant drop in condo requests. As such, he’s been spending less time designing and more time on cooking, his favorite hobby. He loves to cook international foods, venturing beyond French cuisine. But, he is eager to get back to architecture and combine his hobby with his occupation. That’s why he’s looking to create a new design for the kitchens in the company’s current inventory. Can you give him advice on how to do that?
288
+ #"""
289
+
290
+ # Authentication
291
+ #openai.api_key = os.getenv("OPENAI_KEY")
292
+
293
+
294
+ # Define Layout
295
+ conversation = html.Div(
296
+ html.Div(id="display-conversation"),
297
+ style={
298
+ "overflow-y": "auto",
299
+ "display": "flex",
300
+ "height": "calc(100vh - 100px)",
301
+ "flex-direction": "column-reverse",
302
+ },
303
+ )
304
+
305
+ controls = dbc.InputGroup(
306
+ children=[
307
+ dmc.TextInput(id="user-input", placeholder="Ecrire votre requête...", w="400", style=styleSUBMITIA),
308
+ dbc.InputGroupAddon(dmc.Button(leftSection=DashIconify("Envoyer", icon="tabler:send", width=20), id="submit"), addon_type="append", style=styleTitle),
309
+
310
+ #dbc.Input(id="user-input", placeholder="Ecrire votre requête...", type="text"),
311
+ #dbc.InputGroupAddon(dbc.Button("Submit", id="submit"), addon_type="append"),
312
+ ],style=styleSubmitBox
313
+ )
314
+ class CustomDash(Dash):
315
+ def interpolate_index(self, **kwargs):
316
+ # Inspect the arguments by printing them
317
+ return '''
318
+ <!DOCTYPE html>
319
+ <html>
320
+ <head>
321
+ <title>Dashboard des compétences</title>
322
+ </head>
323
+ <body>
324
+
325
+ <div id="custom-topbar"></div>
326
+ {app_entry}
327
+ {config}
328
+ {scripts}
329
+ {renderer}
330
+ <div id="custom-footer">My custom footer</div>
331
+ </body>
332
+ </html>
333
+ '''.format(
334
+ app_entry=kwargs['app_entry'],
335
+ config=kwargs['config'],
336
+ scripts=kwargs['scripts'],
337
+ renderer=kwargs['renderer'])
338
+
339
+ #app = Dash(__name__, external_scripts=external_scripts, external_stylesheets=dmc.styles.ALL, on_error=custom_error_handler)
340
+ app = CustomDash(__name__, server=server, external_scripts=external_scripts, external_stylesheets=dmc.styles.ALL, on_error=custom_error_handler)
341
 
342
  app.layout = dmc.MantineProvider(
343
  [
 
348
  dmc.Grid(
349
  children=[
350
  dmc.GridCol(html.Div(
351
+ children=[
352
  dmc.MultiSelect(
353
+ placeholder="Selectionnez vos Codes ROME",
 
354
  id="framework-multi-select",
355
  value=['K2105', 'L1101', 'L1202', 'L1507', 'L1508', 'L1509'],
356
  data=datadefault,
357
  w=600,
358
+ mt=10,
359
  styles={
360
+ "input": {"borderColor": "grey"},
361
  "label": {"color": dmc.DEFAULT_THEME["colors"]["orange"][4]},
362
  },
363
+ ),
364
+ dmc.Drawer(
365
+ title="Mistral répond à vos questions sur les datas de l'emploi et des compétences.",
366
+ children=[dbc.Container(
367
+ fluid=False,
368
+ children=[
369
+ dcc.Store(id="store-conversation", data=""),
370
+ html.Div(dmc.Button("Bonjour, Mistral est à votre écoute!", variant="gradient", gradient={"from": "grape", "to": "pink", "deg": 35}), style=styleUSERIA),
371
+ conversation,
372
+ dcc.Loading(html.Div(id="loading-component"),type="default"),
373
+ controls,
374
+ #dbc.Spinner(html.Div(id="loading-component")),
375
+ ],
376
+ )
377
+ ],
378
+ id="drawer-simple",
379
+ padding="md",
380
+ size="50%",
381
+ position="right"
382
+ ),]
383
+ ), span=5),
384
+ dmc.GridCol(html.Div(dmc.Title(f"Le marché et les statistiques de l'emploi", order=1, size="30", my="20", id="chainlit-call-fn", style=styleTitle)), span=5),
385
  dmc.GridCol(html.Div(theme_toggle, style=styleToggle), span=1),
386
+ dmc.GridCol(html.Div(dmc.Tooltip(dmc.Button(leftSection=DashIconify(icon="tabler:sparkles", width=30), id="drawer-demo-button"), label="IA générative sur les données",position="left",withArrow=True,arrowSize=6,), style=styleToggle), span=1),
387
  dmc.GridCol(html.Div(
388
  dcc.Loading(
389
  id="loadingRepartition",
 
482
  def switch_theme(_, theme):
483
  return "dark" if theme == "light" else "light"
484
 
485
+ @callback(
486
+ Output("drawer-simple", "opened"),
487
+ Input("drawer-demo-button", "n_clicks"),
488
+ prevent_initial_call=True,
489
+ )
490
+ def drawer_demo(n_clicks):
491
+ return True
492
+
493
  @callback(
494
  Output(component_id='figRepartition', component_property='figure'),
495
  Output(component_id='figCompetences', component_property='figure'),
496
  Output(component_id='figTransversales', component_property='figure'),
497
  Input(component_id='framework-multi-select', component_property='value'),
498
+ Input('figEmplois', 'selectedData'),
499
  Input("mantine-provider", "forceColorScheme"),
500
  )
501
+ def create_repartition(array_value, selectedData, theme):
502
  if theme == "dark":
503
  template = "plotly_dark"
504
  paper_bgcolor = 'rgba(36, 36, 36, 1)'
 
518
  df.drop(df[df['lieuTravail'] == 'Bou'].index, inplace = True)
519
  df.drop(df[df['lieuTravail'] == '976'].index, inplace = True)
520
 
521
+ ######## Filtre Emplois ########
522
+ options = []
523
+ if selectedData != None:
524
+ if type(selectedData['points'][0]['y']) == str:
525
+ options.append(selectedData['points'][0]['y'][:-3])
526
+ else:
527
+ options = selectedData['points'][0]['y'][:-3]
528
+ else:
529
+ options = df['intitule'].values.tolist()
530
+ df = df[df['intitule'].isin(options)]
531
+
532
+
533
  ######## localisation ########
534
  ListCentroids = localisation()
535
  df_localisation = df.groupby('lieuTravail').size().reset_index(name='obs')
 
540
  df_localisation["longitude"] = pd.to_numeric(df_localisation["longitude"], downcast="float")
541
  df_localisation["latitude"] = df_localisation['latitude'].apply(lambda x:[loc['Latitude'] for loc in ListCentroids if loc['ID'] == x]).apply(lambda x:''.join(map(str, x)))
542
  df_localisation["latitude"] = pd.to_numeric(df_localisation["latitude"], downcast="float")
543
+
544
+
545
  res = requests.get(
546
  "https://raw.githubusercontent.com/codeforgermany/click_that_hood/main/public/data/france-regions.geojson"
547
  )
 
572
  df_comp = df_comp.groupby('competences').size().reset_index(name='obs')
573
  df_comp = df_comp.sort_values(by=['obs'])
574
  df_comp = df_comp.iloc[-20:]
575
+ fig_competences = px.bar(df_comp, x='obs', y='competences', orientation='h', color='obs', height=600, template=template, title="Les principales compétences professionnelles", labels={'obs':'nombre'}, color_continuous_scale="Teal", text_auto=True).update_layout(font=dict(size=10),paper_bgcolor=paper_bgcolor,plot_bgcolor=plot_bgcolor,clickmode='event+select',autosize=True).update_traces(hovertemplate=df_comp["competences"] + ' <br>Nombre : %{x}', y=[y[:100] + "..." for y in df_comp['competences']], showlegend=False)
576
 
577
  ######## Compétences transversales ########
578
  df_transversales = df_FT
 
598
  df_intitule = df.groupby('intitule').size().reset_index(name='obs')
599
  df_intitule = df_intitule.sort_values(by=['obs'])
600
  df_intitule = df_intitule.iloc[-25:]
601
+ fig_intitule = px.bar(df_intitule, x='obs', y='intitule', height=600, orientation='h', color='obs', template=template, title="Les principaux emplois", labels={'obs':'nombre'}, color_continuous_scale="Teal", text_auto=True).update_layout(font=dict(size=10),paper_bgcolor=paper_bgcolor,plot_bgcolor=plot_bgcolor,clickmode='event+select',autosize=True).update_traces(hovertemplate=df_intitule["intitule"] + ' <br>Nombre : %{x}', y=[y[:100] + "..." for y in df_intitule["intitule"]], showlegend=False)
602
 
603
  return fig_intitule
604
 
 
717
  df = df[df['lieuTravail'].isin(options)]
718
 
719
  return create_experience(df, theme)
720
+
721
+ ########### IA Chatbot ###########
722
+ @app.callback(
723
+ Output("display-conversation", "children"), [Input("store-conversation", "data")]
724
+ )
725
+ def update_display(chat_history):
726
+ return [
727
+ textbox(x, box="user") if i % 2 == 0 else textbox(x, box="AI")
728
+ for i, x in enumerate(chat_history.split("<split>")[:-1])
729
+ ]
730
+
731
+
732
+ @app.callback(
733
+ Output("user-input", "value"),
734
+ [Input("submit", "n_clicks"), Input("user-input", "n_submit")],
735
+ )
736
+ def clear_input(n_clicks, n_submit):
737
+ return ""
738
+
739
+ @app.callback(
740
+ [Output("store-conversation", "data"), Output("loading-component", "children")],
741
+ [Input("submit", "n_clicks"), Input("user-input", "n_submit")],
742
+ [State("user-input", "value"), State("store-conversation", "data")],
743
+ Input(component_id='framework-multi-select', component_property='value'),
744
+ )
745
+ def run_chatbot(n_clicks, n_submit, user_input, chat_history, array_value):
746
+ if n_clicks == 0 and n_submit is None:
747
+ return "", None
748
+
749
+ if user_input is None or user_input == "":
750
+ return chat_history, None
751
+
752
+ df_FT = API_France_Travail(array_value)
753
+
754
+ df_FT_Select = df_FT[['intitule','typeContratLibelle','experienceLibelle','competences','description','qualitesProfessionnelles','salaire','lieuTravail','formations']].copy()
755
+ list_FT = df_FT_Select.values.tolist()
756
+ context = ''
757
+ for i in range(0,len(list_FT)):
758
+ context += "\n✔️ Emploi : " + str(list_FT[i][0]) + ";\n◉ Contrat : " + str(list_FT[i][1]) + ";\n◉ Compétences professionnelles : " + str(list_FT[i][3]) + ";\n" + "◉ Salaire : " + str(list_FT[i][6]) + ";\n◉ Qualification : " + str(list_FT[i][5]).replace("'libelle'","\n• 'libelle") + ";\n◉ Localisation : " + str(list_FT[i][7]) + ";\n◉ Expérience : " + str(list_FT[i][2]) + ";\n◉ Niveau de qualification : " + str(list_FT[i][8]) + ";\n◉ Description de l'emploi : " + str(list_FT[i][4]) + "\n"
759
+ #context = df_FT.to_string(index=False)
760
+ template = """<s>[INST] Vous êtes un ingénieur pédagogique de l'enseignement supérieur et vous êtes doué pour faire des analyses des formations de l'enseignement supérieur et de faire le rapprochement entre les compétences académiques et les compétences professionnelles attendues par le marché de l'emploi et les les recruteurs, en fonction des critères définis ci-avant. En fonction des informations suivantes et du contexte suivant seulement et strictement, répondez en langue française strictement à la question ci-dessous, en 5000 mots au moins. Lorsque cela est possible, cite les sources du contexte. Si vous ne pouvez pas répondre à la question sur la base des informations, dites que vous ne trouvez pas de réponse ou que vous ne parvenez pas à trouver de réponse. Essayez donc de comprendre en profondeur le contexte et répondez uniquement en vous basant sur les informations fournies. Ne générez pas de réponses non pertinentes.
761
+ Répondez à la question ci-dessous à partir du contexte ci-dessous :
762
+ {context}
763
+ {question} [/INST] </s>
764
+ """
765
+ context_p = context[:28500]
766
+ name = "Mistral"
767
+ chat_history += f"Vous: {user_input}<split>{name}:"
768
+
769
+ model_input = template + chat_history.replace("<split>", "\n")
770
+ #model_input = template
771
+
772
+ prompt = PromptTemplate(template=model_input, input_variables=["question","context"])
773
 
774
+ #prompt = dedent(
775
+ # f"""
776
+ #{description}
777
+
778
+ #Vous: Bonjour {name}!
779
+ #{name}: Bonjour! Ravi de parler avec vous aujourd'hui.
780
+ #"""
781
+ #)
782
+
783
+ # First add the user input to the chat history
784
+
785
+ os.environ['HUGGINGFACEHUB_API_TOKEN'] = os.environ['HUGGINGFACEHUB_API_TOKEN']
786
+ #repo_id = "mistralai/Mistral-7B-Instruct-v0.3"
787
+ repo_id = "mistralai/Mixtral-8x7B-Instruct-v0.1"
788
+ #repo_id = "microsoft/Phi-3.5-mini-instruct"
789
+ #mistral_url = "https://api-inference.huggingface.co/models/mistralai/Mixtral-8x22B-Instruct-v0.1"
790
+ llm = HuggingFaceEndpoint(
791
+ repo_id=repo_id, task="text2text-generation", max_new_tokens=8000, temperature=0.001, streaming=True
792
+ )
793
+ model_output = ""
794
+ chain = prompt | llm
795
+ for s in chain.stream({"question":user_input,"context":context_p}):
796
+ model_output = model_output + s
797
+ print(s, end="", flush=True)
798
+
799
+
800
+ #response = openai.Completion.create(
801
+ # engine="davinci",
802
+ # prompt=model_input,
803
+ # max_tokens=250,
804
+ # stop=["You:"],
805
+ # temperature=0.9,
806
+ #)
807
+ #model_output = response.choices[0].text.strip()
808
+
809
+ chat_history += f"{model_output}<split>"
810
+
811
+ return chat_history, None
812
+
813
  if __name__ == '__main__':
814
  app.run_server(debug=True)