CCockrum commited on
Commit
cd9d03f
·
verified ·
1 Parent(s): 63ecd90

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +104 -50
app.py CHANGED
@@ -1,7 +1,12 @@
 
 
 
 
 
1
  import gradio as gr
2
- from huggingface_hub import InferenceClient
3
 
4
- # Background CSS
5
  css = """
6
  body {
7
  background-image: url('https://cdn-uploads.huggingface.co/production/uploads/67351c643fe51cb1aa28f2e5/YcsJnPk8HJvXiB5WkVmf1.jpeg');
@@ -18,7 +23,7 @@ body {
18
  padding-bottom: 2rem;
19
  }
20
  #title-container {
21
- background-color: rgba(255, 255, 255, 0.85); /* match chat panel */
22
  border-radius: 16px;
23
  padding: 1.5rem 2rem;
24
  margin: 2rem 0;
@@ -26,7 +31,7 @@ body {
26
  max-width: 500px;
27
  text-align: left;
28
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
29
- margin-left: 0rem; /* Aligns left edge */
30
  }
31
  #title-container h1 {
32
  color: #222 !important;
@@ -65,79 +70,128 @@ body {
65
  }
66
  """
67
 
68
- # Model client (consider switching to a public model like mistralai if 401 persists)
69
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
70
 
71
- # Level prompt selector
72
- def level_to_prompt(level):
73
  return {
74
  "A1": "You are a friendly French tutor. Focus on the user's specific question. Use simple French and explain in English. If helpful, you may include word origins or cultural notes, but avoid unrelated tangents and voice features.",
75
  "A2": "You are a patient French tutor. Respond to the user's question clearly. You may include brief relevant background such as word origin, common mistakes, or cultural usage — but only if directly related to the question. Do not mention or suggest voice interaction.",
76
  "B1": "You are a helpful French tutor. Use mostly French and minimal English. You can add short on-topic insights (like grammar tips or usage context) but avoid unrelated vocabulary or tools.",
77
  "B2": "You are a French tutor. Respond primarily in French and include only concise, relevant elaborations. Avoid suggesting voice interaction or unrelated content.",
78
  "C1": "You are a native French tutor. Use fluent French and address only what was asked, but you may include brief cultural or historical context if directly relevant.",
79
- "C2": "You are a French language professor. Use sophisticated French to answer only the question. You may include historical or linguistic nuance but avoid speculation or tool suggestions."
80
  }.get(level, "You are a helpful French tutor.")
81
 
 
 
 
 
 
82
 
83
- # Chat handler
84
- def respond(message, history, user_level, max_tokens, temperature, top_p):
85
- system_message = level_to_prompt(user_level)
86
- messages = [{"role": "system", "content": system_message}]
87
-
88
- # Handle history
89
- if history and isinstance(history[0], tuple):
90
- for user_msg, assistant_msg in history:
91
- if user_msg:
92
- messages.append({"role": "user", "content": user_msg})
93
- if assistant_msg:
94
- messages.append({"role": "assistant", "content": assistant_msg})
95
- else:
96
- messages.extend(history)
97
 
98
- messages.append({"role": "user", "content": message})
99
-
100
- response = ""
 
 
 
 
 
 
 
101
  try:
102
- for msg in client.chat_completion(
103
- messages,
 
104
  max_tokens=max_tokens,
105
- stream=True,
106
  temperature=temperature,
107
  top_p=top_p,
 
108
  ):
109
- token = msg.choices[0].delta.content
110
- if token:
111
- response += token
112
- yield response
 
113
  except Exception as e:
114
- yield f"Désolé! There was an error: {str(e)}"
 
 
 
 
 
115
 
116
- # Gradio interface
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
117
  with gr.Blocks(css=css) as demo:
118
- gr.HTML("""
119
- <div id="title-container">
120
- <h1>LE PROFESSEUR</h1>
121
- <p class="subtitle">French Tutor</p>
122
- </div>
123
- """)
124
-
 
 
125
  with gr.Column(elem_id="chat-panel"):
126
  with gr.Accordion("Advanced Settings", open=False):
127
  user_level = gr.Dropdown(
128
  choices=["A1", "A2", "B1", "B2", "C1", "C2"],
129
  value="A1",
130
- label="Your French Level (CEFR)"
 
 
 
 
 
 
 
 
131
  )
132
- max_tokens = gr.Slider(1, 2048, value=400, step=1, label="Response Length")
133
- temperature = gr.Slider(0.1, 4.0, value=0.5, step=0.1, label="Creativity")
134
- top_p = gr.Slider(0.1, 1.0, value=0.85, step=0.05, label="Dynamic Text Sampling")
135
 
136
  gr.ChatInterface(
137
- respond,
138
- additional_inputs=[user_level, max_tokens, temperature, top_p],
139
- type="messages"
140
  )
141
 
142
  if __name__ == "__main__":
143
- demo.launch()
 
 
1
+ # app.py
2
+
3
+ import os
4
+ from typing import Any, Dict, Iterable, List
5
+
6
  import gradio as gr
7
+ from huggingface_hub import InferenceClient, hf_api
8
 
9
+ # ---- Background CSS (kept from your snippet) ----
10
  css = """
11
  body {
12
  background-image: url('https://cdn-uploads.huggingface.co/production/uploads/67351c643fe51cb1aa28f2e5/YcsJnPk8HJvXiB5WkVmf1.jpeg');
 
23
  padding-bottom: 2rem;
24
  }
25
  #title-container {
26
+ background-color: rgba(255, 255, 255, 0.85);
27
  border-radius: 16px;
28
  padding: 1.5rem 2rem;
29
  margin: 2rem 0;
 
31
  max-width: 500px;
32
  text-align: left;
33
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
34
+ margin-left: 0rem;
35
  }
36
  #title-container h1 {
37
  color: #222 !important;
 
70
  }
71
  """
72
 
73
+ MODEL_ID = "HuggingFaceH4/zephyr-7b-beta" # switch to a public Inference API-enabled model if this is gated
 
74
 
75
+ # ---- Prompting ----
76
+ def level_to_prompt(level: str) -> str:
77
  return {
78
  "A1": "You are a friendly French tutor. Focus on the user's specific question. Use simple French and explain in English. If helpful, you may include word origins or cultural notes, but avoid unrelated tangents and voice features.",
79
  "A2": "You are a patient French tutor. Respond to the user's question clearly. You may include brief relevant background such as word origin, common mistakes, or cultural usage — but only if directly related to the question. Do not mention or suggest voice interaction.",
80
  "B1": "You are a helpful French tutor. Use mostly French and minimal English. You can add short on-topic insights (like grammar tips or usage context) but avoid unrelated vocabulary or tools.",
81
  "B2": "You are a French tutor. Respond primarily in French and include only concise, relevant elaborations. Avoid suggesting voice interaction or unrelated content.",
82
  "C1": "You are a native French tutor. Use fluent French and address only what was asked, but you may include brief cultural or historical context if directly relevant.",
83
+ "C2": "You are a French language professor. Use sophisticated French to answer only the question. You may include historical or linguistic nuance but avoid speculation or tool suggestions.",
84
  }.get(level, "You are a helpful French tutor.")
85
 
86
+ # ---- HF Client ----
87
+ def create_client(token: str | None) -> InferenceClient:
88
+ # WHY: re-create per call so users can supply token at runtime (avoids global state & 401s).
89
+ tok = token or os.getenv("HUGGINGFACEHUB_API_TOKEN") or os.getenv("HF_TOKEN")
90
+ return InferenceClient(model=MODEL_ID, token=tok)
91
 
92
+ # ---- Message shaping ----
93
+ def normalize_messages(
94
+ gradio_messages: List[Dict[str, str]], system_text: str
95
+ ) -> List[Dict[str, str]]:
96
+ # Gradio (type="messages") sends full chat as list of {role, content}.
97
+ msgs: List[Dict[str, str]] = []
98
+ # Drop any incoming system prompts; we control the single system message.
99
+ for m in gradio_messages:
100
+ if m.get("role") != "system":
101
+ msgs.append({"role": m.get("role", "user"), "content": m.get("content", "")})
102
+ return [{"role": "system", "content": system_text}, *msgs]
 
 
 
103
 
104
+ # ---- Streaming call wrapper ----
105
+ def stream_chat(
106
+ client: InferenceClient,
107
+ messages: List[Dict[str, str]],
108
+ *,
109
+ max_tokens: int,
110
+ temperature: float,
111
+ top_p: float,
112
+ ) -> Iterable[str]:
113
+ buf = ""
114
  try:
115
+ # Some servers return events where delta.content can be None (role/tool changes) → guard it.
116
+ for ev in client.chat_completion(
117
+ messages=messages,
118
  max_tokens=max_tokens,
 
119
  temperature=temperature,
120
  top_p=top_p,
121
+ stream=True,
122
  ):
123
+ delta = getattr(ev.choices[0], "delta", None)
124
+ piece = getattr(delta, "content", None) if delta is not None else None
125
+ if piece:
126
+ buf += piece
127
+ yield buf
128
  except Exception as e:
129
+ # WHY: Surface common auth hint for 401 to reduce confusion.
130
+ msg = str(e)
131
+ if "401" in msg or "Unauthorized" in msg:
132
+ yield "Désolé ! Auth error (401). Provide a valid Hugging Face token in Advanced Settings or set HUGGINGFACEHUB_API_TOKEN."
133
+ else:
134
+ yield f"Désolé ! An error occurred: {msg}"
135
 
136
+ # ---- Gradio callback (matches `type="messages"` signature) ----
137
+ def respond(
138
+ messages: List[Dict[str, str]],
139
+ user_level: str,
140
+ max_tokens: int,
141
+ temperature: float,
142
+ top_p: float,
143
+ hf_token: str | None,
144
+ ):
145
+ system_message = level_to_prompt(user_level)
146
+ msgs = normalize_messages(messages, system_message)
147
+ client = create_client(hf_token)
148
+
149
+ # Enforce bounds defensively
150
+ max_tokens = int(max(1, min(int(max_tokens), 4096)))
151
+ temperature = float(max(0.0, min(float(temperature), 4.0)))
152
+ top_p = float(max(0.0, min(float(top_p), 1.0)))
153
+
154
+ yield from stream_chat(
155
+ client,
156
+ msgs,
157
+ max_tokens=max_tokens,
158
+ temperature=temperature,
159
+ top_p=top_p,
160
+ )
161
+
162
+ # ---- UI ----
163
  with gr.Blocks(css=css) as demo:
164
+ gr.HTML(
165
+ """
166
+ <div id="title-container">
167
+ <h1>LE PROFESSEUR</h1>
168
+ <p class="subtitle">French Tutor</p>
169
+ </div>
170
+ """
171
+ )
172
+
173
  with gr.Column(elem_id="chat-panel"):
174
  with gr.Accordion("Advanced Settings", open=False):
175
  user_level = gr.Dropdown(
176
  choices=["A1", "A2", "B1", "B2", "C1", "C2"],
177
  value="A1",
178
+ label="Your French Level (CEFR)",
179
+ )
180
+ max_tokens = gr.Slider(1, 4096, value=400, step=1, label="Response Length")
181
+ temperature = gr.Slider(0.0, 4.0, value=0.5, step=0.1, label="Creativity")
182
+ top_p = gr.Slider(0.0, 1.0, value=0.85, step=0.05, label="Dynamic Text Sampling")
183
+ hf_token = gr.Textbox(
184
+ label="Hugging Face Token (optional)",
185
+ type="password",
186
+ placeholder="hf_xxx — leave empty if set via env",
187
  )
 
 
 
188
 
189
  gr.ChatInterface(
190
+ fn=respond,
191
+ additional_inputs=[user_level, max_tokens, temperature, top_p, hf_token],
192
+ type="messages", # IMPORTANT: pairs with respond(messages, ...)
193
  )
194
 
195
  if __name__ == "__main__":
196
+ # WHY: show URL in logs; enable queues for streaming concurrency.
197
+ demo.launch(server_name="0.0.0.0", server_port=7860, share=False)