Spaces:
Sleeping
Sleeping
File size: 26,332 Bytes
3911020 |
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 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 |
import gradio as gr
import time
import os
import yaml
from qdrant_client import models
from tqdm import tqdm
from collections import defaultdict
import pandas as pd
from spinoza_project.source.backend.llm_utils import (
get_llm_api,
)
from spinoza_project.source.frontend.utils import (
init_env,
parse_output_llm_with_sources,
)
from spinoza_project.source.frontend.gradio_utils import (
get_sources,
set_prompts,
get_config,
get_prompts,
get_assets,
get_theme,
get_init_prompt,
get_synthesis_prompt,
get_qdrants,
start_agents,
end_agents,
next_call,
zip_longest_fill,
reformulate,
answer,
get_text,
update_translation,
)
from assets.utils_javascript import (
accordion_trigger,
accordion_trigger_end,
accordion_trigger_spinoza,
accordion_trigger_spinoza_end,
update_footer
)
init_env()
with open("./spinoza_project/config.yaml") as f:
config = yaml.full_load(f)
## Loading Prompts
print("Loading Prompts")
prompts = get_prompts(config)
chat_qa_prompts, chat_reformulation_prompts = set_prompts(prompts, config)
synthesis_prompt_template = get_synthesis_prompt(config)
## Building LLM
print("Building LLM")
groq_model_name = config.get("groq_model_name", "")
llm = get_llm_api(groq_model_name)
## Loading BDDs
print("Loading Databases")
qdrants, df_qdrants = get_qdrants(config)
dataframes_by_source = {
source: df_qdrants[df_qdrants['Source'] == source].drop(columns=['Source'])
for source in df_qdrants['Source'].unique()
}
for source, df in dataframes_by_source.items():
dataframes_by_source[source]['Filter'] = dataframes_by_source[source]['Filter'].fillna('Unknown')
unknown_percentage = df.apply(lambda x: (x == 'Unknown').mean())
columns_to_drop = unknown_percentage[unknown_percentage == 1.0].index
if len(columns_to_drop) > 0:
print(f"Deleting following columns for {source}: {columns_to_drop.tolist()}")
dataframes_by_source[source] = df.drop(columns=columns_to_drop)
## Loading Assets
print("Loading assets")
css, source_information_fr, source_information_en, about_contact_fr, about_contact_en = get_assets()
theme = get_theme()
init_prompt = get_init_prompt()
## Updating TRANSLATIONS dictionnary
list_tabs = list(config["tabs"])
update_translation(list_tabs, config)
def get_source_df(source_name):
return dataframes_by_source.get(source_name, pd.DataFrame())
LANGUAGE_MAPPING = {
"fr": "french/français",
"en": "english/anglais"
}
def reformulate_questions(
lang_component,
question,
llm=llm,
chat_reformulation_prompts=chat_reformulation_prompts,
config=config,
):
lang = lang_component.value if hasattr(lang_component, 'value') else lang_component
language = LANGUAGE_MAPPING.get(lang, "french/français")
for elt in zip_longest_fill(
*[
reformulate(language, llm, chat_reformulation_prompts, question, tab, config=config)
for tab in config["tabs"]
]
):
time.sleep(0.02)
yield elt
def retrieve_sources(
*questions,
filters_dict,
qdrants=qdrants,
config=config,
):
if filters_dict is None:
filters_dict = {}
formated_sources, text_sources = get_sources(
questions, filters_dict, qdrants, config
)
return (formated_sources, *text_sources)
def retrieve_sources_wrapper(*args):
questions = list(args[:-1])
filters = args[-1]
return retrieve_sources(
questions,
filters_dict=filters
)
def answer_questions(
lang_component,
*questions_sources,
llm=llm,
chat_qa_prompts=chat_qa_prompts,
config=config
):
lang = lang_component.value if hasattr(lang_component, 'value') else lang_component
language = LANGUAGE_MAPPING.get(lang, "french/français")
questions = [elt for elt in questions_sources[: len(questions_sources) // 2]]
sources = [elt for elt in questions_sources[len(questions_sources) // 2 :]]
for elt in zip_longest_fill(
*[
answer(language, llm, chat_qa_prompts, question, source, tab, config)
for question, source, tab in zip(questions, sources, config["tabs"])
]
):
time.sleep(0.02)
yield [
[(question, parse_output_llm_with_sources(ans))]
for question, ans in zip(questions, elt)
]
def get_synthesis(
lang_component,
question,
*answers,
llm=llm,
synthesis_prompt_template=synthesis_prompt_template,
config=config,
):
lang = lang_component.value if hasattr(lang_component, 'value') else lang_component
language = LANGUAGE_MAPPING.get(lang, "french/français")
answer = []
for i, tab in enumerate(config["tabs"]):
if len(str(answers[i])) >= 100:
answer.append(
f"{tab}\n{answers[i]}".replace("<p>", "").replace("</p>\n", "")
)
if len(answer) == 0:
return "Aucune source n'a pu être identifiée pour répondre, veuillez modifier votre question"
else:
for elt in llm.stream(
synthesis_prompt_template,
{
"question": question.replace("<p>", "").replace("</p>\n", ""),
"answers": "\n\n".join(answer),
"language": language
},
):
time.sleep(0.01)
yield [(question, parse_output_llm_with_sources(elt))]
def get_unique_values_filters(df):
filters_values = sorted([
str(x) for x in df['Filter'].unique()
if pd.notna(x) and str(x).strip() != ''
])
return filters_values
def filter_data(filter, source):
if source not in dataframes_by_source:
raise ValueError(f"'{source}' not found withing the sources availible")
df = dataframes_by_source[source]
if filter:
df = df[df['Filter'].fillna('').astype(str).isin(filter)]
return df.values.tolist()
def update_filters(filters_dict, agent, values):
field = "file_filtering_modality"
if filters_dict is None:
filters_dict = {}
new_filters = dict(filters_dict)
if agent not in new_filters:
new_filters[agent] = {}
if not values or isinstance(values, list):
if field in new_filters[agent]:
del new_filters[agent][field]
if not new_filters[agent]:
del new_filters[agent]
else:
new_filters[agent][field] = values
return new_filters, new_filters
with gr.Blocks(
title=f"🔍 Spinoza",
css=css,
js=update_footer(),
theme=theme,
) as demo:
accordions_qa = {}
accordions_filters = {}
current_language = gr.State(value="fr")
chatbots = {}
question = gr.State("")
agt_input_flt = {}
agt_desc = {}
agt_input_dsp = gr.State({})
docs_textbox = gr.State([""])
agent_questions = {elt: gr.State("") for elt in config["tabs"]}
component_sources = {elt: gr.State("") for elt in config["tabs"]}
text_sources = {elt: gr.State("") for elt in config["tabs"]}
tab_states = {elt: gr.State(elt) for elt in config["tabs"]}
filters_state = gr.State({})
filters_display = gr.JSON(
label="Filtres sélectionnés",
value={},
visible=False
)
with gr.Row(elem_classes="header-row"):
button_fr = gr.Button("", elem_id="fr-button", elem_classes="lang-button", icon='./assets/logos/france_round.png')
button_en = gr.Button("", elem_id="en-button", elem_classes="lang-button", icon='./assets/logos/us_round.png')
with gr.Row(elem_classes="main-row"):
with gr.Tab("Q&A", elem_id="main-component"):
with gr.Row(elem_id="chatbot-row"):
with gr.Column(scale=2, elem_id="center-panel"):
with gr.Row(elem_id="input-message"):
ask = gr.Textbox(
placeholder=get_text("ask_placeholder", current_language.value),
show_label=False,
scale=7,
lines=1,
interactive=True,
elem_id="input-textbox",
)
with gr.Group(elem_id="chatbot-group"):
for tab in list(config["tabs"].keys()):
agent_name = get_text(f"agent_{config['source_mapping'][tab]}_qa", current_language.value)
elem_id = f"accordion-{config['source_mapping'][tab]}"
elem_classes = "accordion accordion-agent"
with gr.Accordion(
label=agent_name,
open=False,
elem_id=elem_id,
elem_classes=elem_classes,
) as accordions_qa[config['source_mapping'][tab]]:
# chatbot_key = agent_name.lower().replace(" ", "_")
chatbots[tab] = gr.Chatbot(
value=None,
show_copy_button=True,
show_share_button=False,
show_label=False,
elem_id=f"chatbot-{agent_name.lower().replace(' ', '-')}",
layout="panel",
avatar_images=(
"./assets/logos/help.png",
(
"./assets/logos/spinoza.png"
if agent_name == "Spinoza"
else None
),
)
)
agent_name = "Spinoza"
with gr.Accordion(
label=agent_name,
open=True,
elem_id="accordion-Spinoza",
elem_classes="accordion accordion-agent spinoza-agent",
) as accordion_spinoza:
# chatbot_key = agent_name.lower().replace(" ", "_")
chatbots["Spinoza"] = gr.Chatbot(
value=([(None, get_text("init_prompt", current_language.value))]),
show_copy_button=True,
show_share_button=False,
show_label=False,
elem_id=f"chatbot-{agent_name.lower().replace(' ', '-')}",
layout="panel",
avatar_images=(
"./assets/logos/help.png",
"./assets/logos/spinoza.png",
),
)
with gr.Column(scale=1, variant="panel", elem_id="right-panel"):
with gr.TabItem("Sources", elem_id="tab-sources", id=0):
sources_textbox = gr.HTML(
show_label=False, elem_id="sources-textbox"
)
with gr.Tab(label=get_text("source_filter_label", current_language.value), elem_id="filter-component") as source_filter_tab:
source_filter_title= gr.Markdown(value=get_text("source_filter_title", current_language.value))
source_filter_subtitle = gr.Markdown(value=get_text("source_filter_subtitle", current_language.value))
with gr.Row(elem_id="filter-row"):
with gr.Column(scale=2, elem_id="filter-center-panel"):
with gr.Group(elem_id="filter-group"):
for tab in list(config["tabs"].keys()):
agent_name = get_text(f"agent_{config['source_mapping'][tab]}_flt", current_language.value)
elem_id = f"accordion-filter-{config['source_mapping'][tab]}"
elem_classes = "accordion accordion-source"
with gr.Accordion(
label=agent_name,
open=False,
elem_id=elem_id,
elem_classes=elem_classes,
) as accordions_filters[config['source_mapping'][tab]]:
question_filter = gr.Markdown(value=get_text("question_filter", current_language.value))
with gr.Tabs():
df = get_source_df(config['source_mapping'][tab])
if not df.empty and 'Filter' in df.columns:
filters = get_unique_values_filters(df)
with gr.Row():
var_name = f"{config['source_mapping'][tab]}_input_flt"
agt_input_flt[var_name] = gr.CheckboxGroup(
[filter for filter in filters],
label="Filter(s):"
)
agt_input_flt[var_name].change(
fn=update_filters,
inputs=[filters_state, gr.State(config['source_mapping'][tab]), agt_input_flt[var_name]],
outputs=[filters_state, filters_display]
)
else:
gr.Markdown("**Error:** No data / 'Filter' column doesn't exist...")
with gr.Tab(label=get_text("source_informatation_label", current_language.value), elem_id="source-component") as source_information_tab:
with gr.Row():
with gr.Column(scale=1):
display_info_desc = gr.Markdown(value=get_text("display_info_desc", current_language.value))
accordions_inf = {}
with gr.Tabs(elem_id="main-tab-disp"):
for tab in list(config["tabs"].keys()):
agent_name = get_text(f"agent_{config['source_mapping'][tab]}_tab", current_language.value)
elem_id = f"accordion-{config['source_mapping'][tab]}-tab"
elem_classes = "disp-tabs"
with gr.Tab(
label=agent_name,
elem_id=elem_id,
elem_classes=elem_classes
) as accordions_inf[config['source_mapping'][tab]]:
var_name = f"{config['source_mapping'][tab]}_desc"
agt_desc[var_name] = gr.Markdown(value=get_text(f"{config['source_mapping'][tab]}_desc", current_language.value))
df = get_source_df(config['source_mapping'][tab])
if not df.empty and 'Filter' in df.columns:
filters = get_unique_values_filters(df)
with gr.Row():
var_name = f"{config['source_mapping'][tab]}_input_dsp"
agt_input_dsp.value[var_name] = gr.CheckboxGroup(
[filter for filter in filters],
label="Filter(s):"
)
output_df = gr.Dataframe(
headers=['Title', 'Pages', 'Filter Category', 'Publishing Date'],
datatype=['str', 'number', 'str', 'number'],
value=df.values.tolist(),
column_widths=[300, 100, 100, 150],
wrap=True
)
agt_input_dsp.value[var_name].change(
filter_data,
inputs=[agt_input_dsp.value[var_name]]+[gr.State(config['source_mapping'][tab])],
outputs=[output_df]
)
else:
gr.Markdown("**Error:** No data / 'Filter' column doesn't exist...")
with gr.Tab(label=get_text("contact_label", current_language.value), elem_id="contact-component") as contact_label:
with gr.Row():
with gr.Column(scale=1):
contact_info = gr.Markdown(value=about_contact_fr)
ask.submit(
start_agents, inputs=[current_language], outputs=[chatbots["Spinoza"]] + [source_filter_tab], js=accordion_trigger()
).then(
fn=reformulate_questions,
inputs=[current_language]+
[ask],
outputs=[agent_questions[tab] for tab in config["tabs"]],
).then(
fn=retrieve_sources_wrapper,
inputs=[agent_questions[tab] for tab in config["tabs"]] + [filters_state],
outputs=[sources_textbox] + [text_sources[tab] for tab in config["tabs"]],
).then(
fn=answer_questions,
inputs=[current_language]
+ [agent_questions[tab] for tab in config["tabs"]]
+ [text_sources[tab] for tab in config["tabs"]],
outputs=[chatbots[tab] for tab in config["tabs"]],
).then(
fn=next_call, inputs=[], outputs=[], js=accordion_trigger_end()
).then(
fn=next_call, inputs=[], outputs=[], js=accordion_trigger_spinoza()
).then(
fn=get_synthesis,
inputs=[current_language]
+ [ask]
+ [chatbots[tab] for tab in config["tabs"]],
outputs=[chatbots["Spinoza"]],
).then(
fn=next_call, inputs=[], outputs=[], js=accordion_trigger_spinoza_end()
).then(
fn=end_agents, inputs=[current_language], outputs=[source_filter_tab]
)
def reset_app(language):
chatbot_updates = {}
for tab in config["tabs"]:
chatbot_updates[tab] = gr.update(value=None)
chatbot_updates["Spinoza"] = gr.update(value=[(None, get_text("init_prompt", language))])
empty_checkbox = gr.update(value=None)
checkbox_components = list(agt_input_flt.keys()) + list(agt_input_dsp.value.keys())
checkbox_updates = {component: empty_checkbox for component in checkbox_components}
return {
"chatbots": chatbot_updates,
"filters_state": gr.update(value={}),
"filters_display": gr.update(value={}),
"ask": gr.update(value="", placeholder=get_text("ask_placeholder", language)),
"sources_textbox": gr.update(value=""),
"checkbox_updates": checkbox_updates
}
def toggle_language_fr():
reset_state = reset_app("fr")
return [
"fr",
reset_state["ask"],
reset_state["chatbots"]["Spinoza"],
*[reset_state["chatbots"][tab] for tab in config["tabs"]],
*[
gr.update(
label=get_text(f"agent_{config['source_mapping'][tab]}_qa", "fr"),
open=False,
elem_id=f"accordion-{config['source_mapping'][tab]}",
elem_classes="accordion accordion-agent"
)
for tab in list(config["tabs"].keys())
],
gr.update(label=get_text("source_filter_label", "fr"), elem_id="filter-component"),
*[
gr.update(
label=get_text(f"agent_{config['source_mapping'][tab]}_flt", "fr"),
elem_id=f"accordion-filter-{config['source_mapping'][tab]}",
elem_classes="accordion accordion-source"
)
for tab in list(config["tabs"].keys())
],
gr.update(value=get_text("source_filter_title", 'fr')),
gr.update(value=get_text("source_filter_subtitle", 'fr')),
gr.update(value=get_text("question_filter", 'fr')),
gr.update(label=get_text("source_informatation_label", "fr"), elem_id="source-component"),
gr.update(value=get_text("display_info_desc", "fr")),
*[
gr.update(value=get_text(f"{config['source_mapping'][tab]}_desc", "fr"))
for tab in list(config["tabs"].keys())
],
*[
gr.update(
label=get_text(f"agent_{config['source_mapping'][tab]}_tab", "fr"),
elem_id=f"accordion-{config['source_mapping'][tab]}-tab",
elem_classes="disp-tabs"
)
for tab in list(config["tabs"].keys())
],
gr.update(label=get_text("contact_label", "fr")),
gr.update(value=about_contact_fr),
gr.update(value=""),
gr.update(value={}),
gr.update(value={}),
*[
gr.update(value=None) for _ in range(len(agt_input_flt))
]
]
def toggle_language_en():
reset_state = reset_app("en")
return [
"en",
reset_state["ask"],
reset_state["chatbots"]["Spinoza"],
*[reset_state["chatbots"][tab] for tab in config["tabs"]],
*[
gr.update(
label=get_text(f"agent_{config['source_mapping'][tab]}_qa", "en"),
open=False,
elem_id=f"accordion-{config['source_mapping'][tab]}",
elem_classes="accordion accordion-agent"
)
for tab in list(config["tabs"].keys())
],
gr.update(label=get_text("source_filter_label", "en"), elem_id="filter-component"),
*[
gr.update(
label=get_text(f"agent_{config['source_mapping'][tab]}_flt", "en"),
elem_id=f"accordion-filter-{config['source_mapping'][tab]}",
elem_classes="accordion accordion-source"
)
for tab in list(config["tabs"].keys())
],
gr.update(value=get_text("source_filter_title", 'en')),
gr.update(value=get_text("source_filter_subtitle", 'en')),
gr.update(value=get_text("question_filter", 'en')),
gr.update(label=get_text("source_informatation_label", "en"), elem_id="source-component"),
gr.update(value=get_text("display_info_desc", "en")),
*[
gr.update(value=get_text(f"{config['source_mapping'][tab]}_desc", "en"))
for tab in list(config["tabs"].keys())
],
*[
gr.update(
label=get_text(f"agent_{config['source_mapping'][tab]}_tab", "en"),
elem_id=f"accordion-{config['source_mapping'][tab]}-tab",
elem_classes="disp-tabs"
)
for tab in list(config["tabs"].keys())
],
gr.update(label=get_text("contact_label", "en")),
gr.update(value=about_contact_en),
gr.update(value=""),
gr.update(value={}),
gr.update(value={}),
*[
gr.update(value=None) for _ in range(len(agt_input_flt))
]
]
button_fr.click(
fn=toggle_language_fr,
inputs=[],
outputs=[
current_language,
ask,
chatbots["Spinoza"],
*[chatbots[tab] for tab in config["tabs"]],
*[accordions_qa[key] for key in accordions_qa.keys()],
source_filter_tab,
*[accordions_filters[key] for key in accordions_filters.keys()],
source_filter_title,
source_filter_subtitle,
question_filter,
source_information_tab,
display_info_desc,
*[agt_desc[key] for key in agt_desc.keys()],
*[accordions_inf[key] for key in accordions_inf.keys()],
contact_label,
contact_info,
sources_textbox,
filters_state,
filters_display,
*[agt_input_flt[key] for key in agt_input_flt.keys()]
]
)
button_en.click(
fn=toggle_language_en,
inputs=[],
outputs=[
current_language,
ask,
chatbots["Spinoza"],
*[chatbots[tab] for tab in config["tabs"]],
*[accordions_qa[key] for key in accordions_qa.keys()],
source_filter_tab,
*[accordions_filters[key] for key in accordions_filters.keys()],
source_filter_title,
source_filter_subtitle,
question_filter,
source_information_tab,
display_info_desc,
*[agt_desc[key] for key in agt_desc.keys()],
*[accordions_inf[key] for key in accordions_inf.keys()],
contact_label,
contact_info,
sources_textbox,
filters_state,
filters_display,
*[agt_input_flt[key] for key in agt_input_flt.keys()]
]
)
if __name__ == "__main__":
demo.queue().launch(debug=True, share=True)
|