Spaces:
Sleeping
Sleeping
Download app.py from QnoM/Gradio_Browser_State: direct link, hf CLI and curl.
- Browser
- Download file 9.81 kB
-
https://huggingface.co/spaces/QnoM/Gradio_Browser_State/resolve/main/app.py
- Command line
-
hf download hf://spaces/QnoM/Gradio_Browser_State/app.py
-
curl -L -o app.py https://huggingface.co/spaces/QnoM/Gradio_Browser_State/resolve/main/app.py
9.81 kB
| # app.py | |
| import gradio as gr | |
| from gradio_htmlinjector import HTMLInjector | |
| import json | |
| FIRST_MESSAGE = ( | |
| '👋 Bonjour ! Nous allons créer ta demande "Onboarding" ensemble.\n' | |
| "Quel titre souhaites tu donner à ta demande ? Onboarding de ... par exemple" | |
| ) | |
| QUESTIONS = [ | |
| "Quel titre souhaites tu donner à ta demande ?", | |
| "Quel est le prénom de la personne concernée ?", | |
| "Quel est son nom ?", | |
| "Quelle est la date de démarrage jj/mm/aaaa ?", | |
| ] | |
| SUMMARY_MESSAGE = "Nous allons créer la demande : {title} pour {first} {last}, démarrage le {date}." | |
| END_MESSAGE = "✅ La demande est créée !" | |
| CANCEL_MESSAGE = "❎ La demande a été annulée." | |
| DEFAULT_STATE = {"step": 0, "answers": []} | |
| # -------- Helpers -------- | |
| def clamp_step(s: int) -> int: | |
| return max(0, min(s, len(QUESTIONS))) | |
| def build_summary(answers: list[str]) -> str: | |
| title = (answers[0].strip() if len(answers) > 0 else "") or "(vide)" | |
| first = (answers[1].strip() if len(answers) > 1 else "") or "(vide)" | |
| last = (answers[2].strip() if len(answers) > 2 else "") or "(vide)" | |
| date = (answers[3].strip() if len(answers) > 3 else "") or "(vide)" | |
| return SUMMARY_MESSAGE.format(title=title, first=first, last=last, date=date) | |
| def build_chat_messages(state: dict) -> list[dict]: | |
| """ | |
| - Garde TOUJOURS FIRST_MESSAGE en premier. | |
| - Après la DERNIÈRE réponse, affiche le SUMMARY (mais pas END_MESSAGE : il vient de la popup). | |
| """ | |
| msgs: list[dict] = [] | |
| msgs.append({"role": "assistant", "content": FIRST_MESSAGE}) | |
| step = clamp_step(state.get("step", 0)) | |
| answers = state.get("answers", []) | |
| if step == 0 and not answers: | |
| return msgs | |
| n = min(step, len(QUESTIONS)) | |
| for i in range(n): | |
| user_msg = answers[i] if i < len(answers) else "(vide)" | |
| msgs.append({"role": "user", "content": user_msg}) | |
| if i + 1 < len(QUESTIONS): | |
| msgs.append({"role": "assistant", "content": QUESTIONS[i + 1]}) | |
| else: | |
| # dernière réponse -> récapitulatif | |
| summary = build_summary(answers) | |
| msgs.append({"role": "assistant", "content": summary}) | |
| return msgs | |
| # -------- Handlers (server) -------- | |
| def on_load(saved: dict): | |
| state = saved or DEFAULT_STATE.copy() | |
| state.setdefault("step", 0) | |
| state.setdefault("answers", []) | |
| state["step"] = clamp_step(int(state["step"])) | |
| state["answers"] = list(state["answers"])[:len(QUESTIONS)] | |
| chat = build_chat_messages(state) | |
| return chat, state, json.loads(json.dumps(state)), "" # "" = flag popup (fermé) | |
| def on_submit(user_text: str, saved: dict): | |
| state = saved or DEFAULT_STATE.copy() | |
| state.setdefault("answers", []) | |
| state.setdefault("step", 0) | |
| step = clamp_step(int(state["step"])) | |
| text = (user_text or "").strip() or "(vide)" | |
| if step < len(QUESTIONS): | |
| if len(state["answers"]) <= step: | |
| state["answers"].extend([""] * (step - len(state["answers"]) + 1)) | |
| state["answers"][step] = text | |
| step += 1 | |
| state["step"] = clamp_step(step) | |
| chat = build_chat_messages(state) | |
| # Ouvrir la popup SEULEMENT si on vient de terminer les questions | |
| open_flag = "open" if state["step"] >= len(QUESTIONS) else "" | |
| return chat, state, "", json.loads(json.dumps(state)), open_flag | |
| # ^ vide textbox ^ flag popup | |
| def on_reset(): | |
| state = DEFAULT_STATE.copy() | |
| chat = build_chat_messages(state) | |
| return chat, state, "", json.loads(json.dumps(state)), "" # pas de popup | |
| def handle_choice(choice: str, saved: dict, current_chat: list[dict]): | |
| """ | |
| choice ∈ {"create","edit","cancel"} | |
| - create: ajoute END_MESSAGE (ne réinitialise pas le state) | |
| - edit: reset le state et repart de zéro | |
| - cancel: reset le state et affiche CANCEL_MESSAGE | |
| """ | |
| c = (choice or "").strip().lower() | |
| state = saved or DEFAULT_STATE.copy() | |
| if c == "create": | |
| # repart de l'historique existant puis ajoute la confirmation | |
| chat = current_chat + [{"role": "assistant", "content": END_MESSAGE}] | |
| return chat, state, "", json.loads(json.dumps(state)), "" # clear bridge, fermer popup | |
| elif c == "edit": | |
| state = DEFAULT_STATE.copy() | |
| chat = build_chat_messages(state) # revient à la 1ère question | |
| return chat, state, "", json.loads(json.dumps(state)), "" # clear bridge, fermer popup | |
| elif c == "cancel": | |
| state = DEFAULT_STATE.copy() | |
| # message d'annulation (sans relancer flux) | |
| chat = [{"role": "assistant", "content": CANCEL_MESSAGE}] | |
| return chat, state, "", json.loads(json.dumps(state)), "" # clear bridge, fermer popup | |
| # valeur inattendue -> ne rien changer | |
| return current_chat, state, "", json.loads(json.dumps(state)), "" | |
| # -------- Assets (client) -------- | |
| def inject_assets(): | |
| js = r""" | |
| function setGradioValue(elemId, value){ | |
| const root = (window.gradioApp && window.gradioApp()) || document; | |
| const host = root.querySelector(`#${elemId}`); | |
| if (!host) return; | |
| const input = host.querySelector('input, textarea'); | |
| if (!input) return; | |
| input.value = value; | |
| input.dispatchEvent(new Event('input', {bubbles:true})); | |
| input.dispatchEvent(new Event('change', {bubbles:true})); | |
| } | |
| """ | |
| css = r""" | |
| #confirm-modal{ | |
| display:none; position:fixed; inset:0; z-index:9999; | |
| background: rgba(0,0,0,.45); align-items:center; justify-content:center; | |
| } | |
| #confirm-card{ | |
| background: var(--panel-background-fill, #fff); color: var(--body-text-color, #111); | |
| border: 1px solid var(--border-color-primary, #ccc); border-radius: 10px; | |
| padding: 20px; min-width: 340px; max-width: 92vw; box-shadow: 0 10px 30px rgba(0,0,0,.2); | |
| } | |
| #confirm-actions{ display:flex; gap:8px; justify-content:flex-end; margin-top:14px; flex-wrap:wrap; } | |
| #confirm-actions button{ cursor:pointer; padding:8px 14px; border-radius:8px; border:1px solid #bbb; background:#f4f4f5; } | |
| #confirm-actions button.primary{ background:#2563eb; color:#fff; border-color:transparent; } | |
| #bridge-choice{ display:none; } /* pont caché mais monté */ | |
| #modal-flag{ display:none; } /* flag d'ouverture caché */ | |
| """ | |
| html = r""" | |
| <div id="confirm-modal" role="dialog" aria-modal="true" aria-labelledby="confirm-title"> | |
| <div id="confirm-card"> | |
| <h3 id="confirm-title">Valider la demande ?</h3> | |
| <p>Veuillez confirmer votre choix :</p> | |
| <div id="confirm-actions"> | |
| <button type="button" | |
| onclick="setGradioValue('bridge-choice','cancel'); document.getElementById('confirm-modal').style.display='none'; document.body.style.overflow=''">Annuler</button> | |
| <button type="button" | |
| onclick="setGradioValue('bridge-choice','edit'); document.getElementById('confirm-modal').style.display='none'; document.body.style.overflow=''">Modifier la saisie</button> | |
| <button type="button" class="primary" | |
| onclick="setGradioValue('bridge-choice','create'); document.getElementById('confirm-modal').style.display='none'; document.body.style.overflow=''">Créer la demande</button> | |
| </div> | |
| </div> | |
| </div> | |
| """ | |
| return {"css": css, "js": js, "body_html": html} | |
| # -------- UI -------- | |
| with gr.Blocks(title="Chatbot Workflow (BrowserState) + Validation", fill_height=True) as demo: | |
| # Injection HTML/CSS/JS du modal | |
| html_injector = HTMLInjector() | |
| gr.Markdown("### Onboarding — questions une à une, récap & validation\n" | |
| "- Le récapitulatif s’affiche après la dernière question.\n" | |
| "- Une popup propose **Créer la demande / Modifier la saisie / Annuler**.") | |
| # Chatbot (messages) | |
| chat = gr.Chatbot(type="messages", height=380, label="Chatbot") | |
| # Textbox de réponse | |
| txt = gr.Textbox(label="Ta réponse", placeholder="Tape ta réponse puis Enter…", lines=2) | |
| # Bouton Réinitialiser | |
| reset = gr.Button("🔁 Réinitialiser") | |
| # State persistant côté navigateur | |
| local = gr.BrowserState(DEFAULT_STATE) | |
| # Ponts cachés | |
| bridge_choice = gr.Textbox(visible=True, elem_id="bridge-choice") # "create" | "edit" | "cancel" | |
| modal_flag = gr.Textbox(visible=False, elem_id="modal-flag") # "" | "open" | |
| # Zone d'affichage du state (en bas) | |
| with gr.Accordion("State (BrowserState)", open=False): | |
| state_json = gr.JSON(label="State", value=DEFAULT_STATE) | |
| # --- Wiring --- | |
| # 0) injection des assets | |
| demo.load(fn=inject_assets, inputs=None, outputs=[html_injector]) | |
| # 1) au chargement | |
| demo.load(on_load, inputs=[local], outputs=[chat, local, state_json, modal_flag]) | |
| # 2) submit: MAJ chat/state + drapeau d'ouverture de modal | |
| evt = txt.submit(on_submit, inputs=[txt, local], outputs=[chat, local, txt, state_json, modal_flag]) | |
| # 3) si flag == "open" -> ouvrir la popup côté client | |
| evt.then( | |
| fn=None, inputs=[modal_flag], outputs=None, | |
| js=""" | |
| (flag) => { | |
| if (flag !== "open") return; | |
| const start = Date.now(); | |
| (function tick(){ | |
| const modal = document.getElementById('confirm-modal'); | |
| if (modal) { | |
| modal.style.display = 'flex'; | |
| document.body.style.overflow = 'hidden'; | |
| return; | |
| } | |
| if (Date.now() - start < 3000) setTimeout(tick, 60); | |
| })(); | |
| } | |
| """, | |
| ) | |
| # 4) clic sur un bouton du modal -> action serveur | |
| bridge_choice.change( | |
| fn=handle_choice, | |
| inputs=[bridge_choice, local, chat], | |
| outputs=[chat, local, bridge_choice, state_json, modal_flag], | |
| ) | |
| # 5) reset manuel | |
| reset.click(on_reset, outputs=[chat, local, txt, state_json, modal_flag]) | |
| if __name__ == "__main__": | |
| demo.launch() |