QnoM commited on
Commit
f81a19e
·
verified ·
1 Parent(s): e11d07e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +58 -58
app.py CHANGED
@@ -1,39 +1,40 @@
1
  import gradio as gr
2
  from gradio_htmlinjector import HTMLInjector
3
 
4
- # --- Handler du choix depuis la popup ---
5
- def handle_choice(choice: str, chat_history: list[tuple[str, str]]):
6
- if not choice: # ignore le 2e "change" éventuel (quand on vide le pont)
7
- return chat_history, ""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
 
9
- c = choice.strip().lower()
10
  if c in {"oui", "o", "yes", "y"}:
11
- user_msg = "Oui"
12
- bot_reply = "✅ Vous avez choisi **OUI**. Action validée."
13
  elif c in {"non", "n", "no"}:
14
- user_msg = "Non"
15
- bot_reply = "❌ Vous avez choisi **NON**. Action annulée."
16
  else:
17
- # Dans cette démo, la popup ne devrait envoyer que oui/non.
18
- # On ignore toute autre valeur pour éviter des messages parasites.
19
- return chat_history, ""
20
 
21
- chat_history = chat_history + [(user_msg, bot_reply)]
22
- return chat_history, "" # on vide le pont (déclenche un 2e change, mais ignoré ci-dessus)
23
 
24
- # --- Soumission utilisateur : réponse fixe + demande d'ouverture de la popup ---
25
- def on_submit(user_msg: str, chat_history: list[tuple[str, str]]):
26
- if not user_msg:
27
- return chat_history, "" # rien
28
-
29
- assistant_reply = "Ceci est une réponse de démonstration.\n\nConfirmez-vous l’action ?"
30
- chat_history = chat_history + [(user_msg, assistant_reply)]
31
- return chat_history, "" # l'ouverture de la popup se fait côté JS (param js)
32
-
33
- # --- Injection (HTML/CSS/JS) de la popup ---
34
  def inject_assets():
35
  js = r"""
36
- // Pousser une valeur dans un composant Gradio (shadow DOM v4)
37
  function setGradioValue(elemId, value){
38
  const root = (window.gradioApp && window.gradioApp()) || document;
39
  const host = root.querySelector(`#${elemId}`);
@@ -52,30 +53,17 @@ def inject_assets():
52
  align-items:center; justify-content:center;
53
  }
54
  #confirm-card{
55
- background: var(--panel-background-fill, #fff);
56
- color: var(--body-text-color, #111);
57
- border: 1px solid var(--border-color-primary, #ccc);
58
- border-radius: var(--radius-lg, 10px);
59
- padding: 20px; min-width: 320px; max-width: 90vw;
60
- box-shadow: var(--shadow-drop-lg, 0 10px 30px rgba(0,0,0,.2));
61
- }
62
- #confirm-actions{ display:flex; gap:8px; justify-content:flex-end; margin-top: 14px; }
63
- #confirm-actions button{
64
- cursor: pointer; padding: 8px 14px; border-radius: 8px; border: 1px solid var(--border-color-primary, #bbb);
65
- background: var(--button-secondary-background-fill, #f4f4f5);
66
  }
67
- #confirm-actions button.primary{
68
- background: var(--button-primary-background-fill, #2563eb);
69
- color: white; border-color: transparent;
70
- }
71
- /* Pont caché mais monté dans le DOM */
72
- #bridge-choice { display: none; }
73
  """
74
  html = r"""
75
  <div id="confirm-modal" role="dialog" aria-modal="true" aria-labelledby="confirm-title">
76
  <div id="confirm-card">
77
  <h3 id="confirm-title">Confirmer ?</h3>
78
- <p>Souhaitez-vous continuer ?</p>
79
  <div id="confirm-actions">
80
  <button type="button"
81
  onclick="setGradioValue('bridge-choice','non'); document.getElementById('confirm-modal').style.display='none'; document.body.style.overflow=''">
@@ -91,23 +79,34 @@ def inject_assets():
91
  """
92
  return {"css": css, "js": js, "body_html": html}
93
 
94
- # --- UI ---
95
- with gr.Blocks(title="Démo Chat + Popup", fill_height=True) as demo:
96
  html_injector = HTMLInjector()
97
 
98
- chat = gr.Chatbot(label="Chatbot", height=420)
99
  user_in = gr.Textbox(placeholder="Tapez un message…", lines=2)
 
 
 
100
 
101
- # Pont: textbox cachée qui recevra "oui"/"non"
102
- bridge_choice = gr.Textbox(visible=True, elem_id="bridge-choice")
103
-
104
- # A) Soumission -> réponse + ouverture popup (client JS, après rendu du message)
105
- user_in.submit(
106
  fn=on_submit,
107
- inputs=[user_in, chat],
108
- outputs=[chat, user_in],
 
 
 
 
 
 
 
 
 
 
109
  js="""
110
- () => {
 
111
  const start = Date.now();
112
  (function tick(){
113
  const modal = document.getElementById('confirm-modal');
@@ -122,14 +121,15 @@ with gr.Blocks(title="Démo Chat + Popup", fill_height=True) as demo:
122
  """,
123
  )
124
 
125
- # B) Choix -> ajoute un nouveau tour (user: Oui/Non, bot: confirmation)
126
  bridge_choice.change(
127
  fn=handle_choice,
128
- inputs=[bridge_choice, chat],
129
- outputs=[chat, bridge_choice],
 
 
130
  )
131
 
132
- # Injection initiale de la popup
133
  demo.load(fn=inject_assets, inputs=None, outputs=[html_injector])
134
 
135
  demo.launch()
 
1
  import gradio as gr
2
  from gradio_htmlinjector import HTMLInjector
3
 
4
+ # ---------- logique serveur ----------
5
+ def on_submit(user_msg: str, conv: list[tuple[str, str]]):
6
+ # 1) ajoute (user_msg, question) et indique qu'il faut ouvrir la popup
7
+ if conv is None:
8
+ conv = []
9
+ user_msg = (user_msg or "").strip()
10
+ if not user_msg:
11
+ return conv, False, "" # pas de popup
12
+
13
+ bot_question = "Ceci est une réponse de démo.\n\n**Confirmez-vous l’action ?**"
14
+ new_conv = conv + [(user_msg, bot_question)]
15
+ confirm_needed = True
16
+ return new_conv, confirm_needed, "" # (maj chatbot via state_conv, flag popup, clear textbox)
17
+
18
+ def handle_choice(choice: str, conv: list[tuple[str, str]]):
19
+ # 3) ajoute (Oui/Non, confirmation) ; ignore les resets vides
20
+ if conv is None:
21
+ conv = []
22
+ c = (choice or "").strip().lower()
23
+ if not c:
24
+ return conv, "" # ignore le "change" déclenché par le reset
25
 
 
26
  if c in {"oui", "o", "yes", "y"}:
27
+ user_choice, bot_reply = "Oui", "✅ Vous avez choisi **OUI**. Action validée."
 
28
  elif c in {"non", "n", "no"}:
29
+ user_choice, bot_reply = "Non", "❌ Vous avez choisi **NON**. Action annulée."
 
30
  else:
31
+ return conv, ""
 
 
32
 
33
+ return conv + [(user_choice, bot_reply)], "" # reset du pont via ""
 
34
 
35
+ # ---------- assets popup ----------
 
 
 
 
 
 
 
 
 
36
  def inject_assets():
37
  js = r"""
 
38
  function setGradioValue(elemId, value){
39
  const root = (window.gradioApp && window.gradioApp()) || document;
40
  const host = root.querySelector(`#${elemId}`);
 
53
  align-items:center; justify-content:center;
54
  }
55
  #confirm-card{
56
+ background:#fff; border:1px solid #ccc; border-radius:10px;
57
+ padding:20px; min-width:320px; max-width:90vw; box-shadow:0 10px 30px rgba(0,0,0,.2);
 
 
 
 
 
 
 
 
 
58
  }
59
+ #confirm-actions{ display:flex; gap:8px; justify-content:flex-end; margin-top:14px; }
60
+ #bridge-choice{ display:none; } /* pont caché mais monté */
 
 
 
 
61
  """
62
  html = r"""
63
  <div id="confirm-modal" role="dialog" aria-modal="true" aria-labelledby="confirm-title">
64
  <div id="confirm-card">
65
  <h3 id="confirm-title">Confirmer ?</h3>
66
+ <p>Souhaitez-vous poursuivre ?</p>
67
  <div id="confirm-actions">
68
  <button type="button"
69
  onclick="setGradioValue('bridge-choice','non'); document.getElementById('confirm-modal').style.display='none'; document.body.style.overflow=''">
 
79
  """
80
  return {"css": css, "js": js, "body_html": html}
81
 
82
+ # ---------- UI ----------
83
+ with gr.Blocks(title="Chat + Popup (avec .then)") as demo:
84
  html_injector = HTMLInjector()
85
 
86
+ chat = gr.Chatbot(height=420)
87
  user_in = gr.Textbox(placeholder="Tapez un message…", lines=2)
88
+ state_conv = gr.State([]) # vérité de la conversation
89
+ confirm_flag = gr.State(False) # flag “ouvrir popup ?”
90
+ bridge_choice = gr.Textbox(visible=True, elem_id="bridge-choice") # pont oui/non
91
 
92
+ # (A) submit -> met à jour état & textbox
93
+ evt = user_in.submit(
 
 
 
94
  fn=on_submit,
95
+ inputs=[user_in, state_conv],
96
+ outputs=[state_conv, confirm_flag, user_in], # maj state_conv, flag, clear input
97
+ )
98
+
99
+ # (B) refléter l'état dans le Chatbot (immédiatement après)
100
+ evt = evt.then(
101
+ fn=lambda s: s, inputs=state_conv, outputs=chat
102
+ )
103
+
104
+ # (C) puis ouvrir la popup côté client *si* confirm_flag = True
105
+ evt.then(
106
+ fn=None, inputs=[confirm_flag], outputs=None,
107
  js="""
108
+ (flag) => {
109
+ if(!flag) return;
110
  const start = Date.now();
111
  (function tick(){
112
  const modal = document.getElementById('confirm-modal');
 
121
  """,
122
  )
123
 
124
+ # (D) choix utilisateur -> ajoute (Oui/Non, confirmation) à la conversation + reflète dans Chatbot
125
  bridge_choice.change(
126
  fn=handle_choice,
127
+ inputs=[bridge_choice, state_conv],
128
+ outputs=[state_conv, bridge_choice],
129
+ ).then(
130
+ fn=lambda s: s, inputs=state_conv, outputs=chat
131
  )
132
 
 
133
  demo.load(fn=inject_assets, inputs=None, outputs=[html_injector])
134
 
135
  demo.launch()