CCockrum commited on
Commit
3da162a
·
verified ·
1 Parent(s): 569604f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +117 -46
app.py CHANGED
@@ -1,14 +1,22 @@
1
  # app.py
 
 
 
 
 
 
 
 
2
 
3
  from __future__ import annotations
4
 
5
  import os
6
- from typing import Any, Dict, Iterable, List, Optional, Sequence, Tuple, Union
7
 
8
  import gradio as gr
9
- from huggingface_hub import InferenceClient
10
 
11
- # -------------------- CSS --------------------
12
  css = """
13
  body {
14
  background-image: url('https://cdn-uploads.huggingface.co/production/uploads/67351c643fe51cb1aa28f2e5/YcsJnPk8HJvXiB5WkVmf1.jpeg');
@@ -16,18 +24,63 @@ body {
16
  background-position: center;
17
  background-repeat: no-repeat;
18
  }
19
- .gradio-container { display: flex; flex-direction: column; justify-content: center; min-height: 100vh; padding-top: 2rem; padding-bottom: 2rem; }
20
- #title-container { background-color: rgba(255, 255, 255, 0.85); border-radius: 16px; padding: 1.5rem 2rem; margin: 2rem 0; width: fit-content; max-width: 500px; text-align: left; box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1); margin-left: 0rem; }
21
- #title-container h1 { color: #222 !important; font-size: 4rem; font-family: 'Noto Sans JP', sans-serif; margin: 0; }
22
- #title-container .subtitle { font-size: 1.1rem; font-family: 'Noto Sans', sans-serif; color: #222 !important; margin-top: 0.5rem; margin-bottom: 0; width: 100%; display: block; }
23
- #chat-panel { background-color: rgba(255, 255, 255, 0.85); padding: 2rem; border-radius: 12px; justify-content: center; width: 100%; max-width: 700px; height: 70vh; box-shadow: 0 0 12px rgba(0, 0, 0, 0.3); overflow-y: auto; }
24
- .gradio-container .chatbot h1 { color: var(--custom-title-color) !important; font-family: 'Noto Sans', serif !important; font-size: 5rem !important; font-weight: bold !important; text-align: center !important; margin-bottom: 1.5rem !important; width: 100%; }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
  """
26
 
27
- MODEL_ID = "HuggingFaceH4/zephyr-7b-beta" # ensure your HF token has access if gated
28
-
29
-
30
- # -------------------- Prompting --------------------
31
  def level_to_prompt(level: str) -> str:
32
  return {
33
  "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.",
@@ -38,15 +91,7 @@ def level_to_prompt(level: str) -> str:
38
  "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.",
39
  }.get(level, "You are a helpful French tutor.")
40
 
41
-
42
- # -------------------- HF Client --------------------
43
- def create_client(token: Optional[str]) -> InferenceClient:
44
- # why: allow runtime token; avoids hard-failing with 401 when model is gated
45
- tok = token or os.getenv("HUGGINGFACEHUB_API_TOKEN") or os.getenv("HF_TOKEN")
46
- return InferenceClient(model=MODEL_ID, token=tok)
47
-
48
-
49
- # -------------------- Message shaping --------------------
50
  GradioMessage = Dict[str, str]
51
  HistoryItem = Union[Tuple[str, str], GradioMessage]
52
  History = Optional[Sequence[HistoryItem]]
@@ -55,7 +100,6 @@ def _history_to_messages(history: History) -> List[GradioMessage]:
55
  msgs: List[GradioMessage] = []
56
  if not history:
57
  return msgs
58
- # Accept either tuples (user, assistant) or already-shaped dicts
59
  for item in history:
60
  if isinstance(item, tuple) and len(item) == 2:
61
  u, a = item
@@ -73,49 +117,63 @@ def coerce_to_messages(
73
  history: History,
74
  system_text: str,
75
  ) -> List[GradioMessage]:
76
- # Handle both call modes: (str, history) and (messages_list, None)
77
  if isinstance(message, list) and all(isinstance(m, dict) and "role" in m for m in message):
78
  user_msgs = [m for m in message if m.get("role") != "system"]
79
  return [{"role": "system", "content": system_text}, *user_msgs]
80
- # Default: current user message + legacy history tuples/dicts
81
  msgs = [{"role": "system", "content": system_text}, *_history_to_messages(history)]
82
  if isinstance(message, str) and message:
83
  msgs.append({"role": "user", "content": message})
84
  return msgs
85
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86
 
87
- # -------------------- Streaming wrapper --------------------
88
  def stream_chat(
89
- client: InferenceClient,
90
- messages: List[GradioMessage],
91
  *,
 
 
92
  max_tokens: int,
93
  temperature: float,
94
  top_p: float,
95
  ) -> Iterable[str]:
96
  buf = ""
97
  try:
98
- for ev in client.chat_completion(
 
99
  messages=messages,
100
- max_tokens=max_tokens, # if your server expects max_new_tokens, rename here
101
  temperature=temperature,
102
  top_p=top_p,
103
  stream=True,
104
- ):
105
- delta = getattr(ev.choices[0], "delta", None)
 
106
  piece = getattr(delta, "content", None) if delta is not None else None
107
  if piece:
108
  buf += piece
109
  yield buf
110
  except Exception as e:
111
  msg = str(e)
112
- if "401" in msg or "Unauthorized" in msg:
113
- yield "Désolé ! Auth error (401). Provide a valid Hugging Face token in Advanced Settings or set HUGGINGFACEHUB_API_TOKEN."
 
 
114
  else:
115
  yield f"Désolé ! An error occurred: {msg}"
116
 
117
-
118
- # -------------------- Gradio callback --------------------
119
  def respond(
120
  message: Union[str, List[GradioMessage]],
121
  history: History,
@@ -123,27 +181,34 @@ def respond(
123
  max_tokens: int,
124
  temperature: float,
125
  top_p: float,
 
126
  hf_token: Optional[str],
127
  ):
128
  system_message = level_to_prompt(user_level)
129
  msgs = coerce_to_messages(message, history, system_message)
130
- client = create_client(hf_token)
131
 
132
- # defensive bounds
133
  max_tokens = int(max(1, min(int(max_tokens), 4096)))
134
  temperature = float(max(0.0, min(float(temperature), 4.0)))
135
  top_p = float(max(0.0, min(float(top_p), 1.0)))
 
 
 
 
 
 
 
136
 
137
  yield from stream_chat(
138
  client,
139
- msgs,
 
140
  max_tokens=max_tokens,
141
  temperature=temperature,
142
  top_p=top_p,
143
  )
144
 
145
-
146
- # -------------------- UI --------------------
147
  with gr.Blocks(css=css) as demo:
148
  gr.HTML(
149
  """
@@ -164,17 +229,23 @@ with gr.Blocks(css=css) as demo:
164
  max_tokens = gr.Slider(1, 4096, value=400, step=1, label="Response Length")
165
  temperature = gr.Slider(0.0, 4.0, value=0.5, step=0.1, label="Creativity")
166
  top_p = gr.Slider(0.0, 1.0, value=0.85, step=0.05, label="Dynamic Text Sampling")
 
 
 
 
 
167
  hf_token = gr.Textbox(
168
- label="Hugging Face Token (optional)",
169
  type="password",
170
- placeholder="hf_xxx — leave empty if set via env",
171
  )
172
 
173
  gr.ChatInterface(
174
- fn=respond, # expects (message, history, *inputs)
175
- additional_inputs=[user_level, max_tokens, temperature, top_p, hf_token],
176
- type="messages", # still fine; we normalize both call shapes
177
  )
178
 
179
  if __name__ == "__main__":
 
180
  demo.launch(server_name="0.0.0.0", server_port=7860, share=False)
 
1
  # app.py
2
+ """
3
+ Gradio French tutor that uses Hugging Face Inference Providers (router.huggingface.co/hf-inference)
4
+ via the OpenAI-compatible Chat Completions API. Requires `openai>=1.51.0`.
5
+
6
+ WHY this approach:
7
+ - The old api-inference.huggingface.co endpoint is deprecated (410/404). The router exposes an
8
+ OpenAI-compatible /v1/chat/completions; using the OpenAI SDK keeps the code simple and future-proof.
9
+ """
10
 
11
  from __future__ import annotations
12
 
13
  import os
14
+ from typing import Dict, Iterable, List, Optional, Sequence, Tuple, Union
15
 
16
  import gradio as gr
17
+ from openai import OpenAI # pip install openai>=1.51.0
18
 
19
+ # ---------- Styling ----------
20
  css = """
21
  body {
22
  background-image: url('https://cdn-uploads.huggingface.co/production/uploads/67351c643fe51cb1aa28f2e5/YcsJnPk8HJvXiB5WkVmf1.jpeg');
 
24
  background-position: center;
25
  background-repeat: no-repeat;
26
  }
27
+ .gradio-container {
28
+ display: flex;
29
+ flex-direction: column;
30
+ justify-content: center;
31
+ min-height: 100vh;
32
+ padding-top: 2rem;
33
+ padding-bottom: 2rem;
34
+ }
35
+ #title-container {
36
+ background-color: rgba(255, 255, 255, 0.85);
37
+ border-radius: 16px;
38
+ padding: 1.5rem 2rem;
39
+ margin: 2rem 0;
40
+ width: fit-content;
41
+ max-width: 500px;
42
+ text-align: left;
43
+ box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
44
+ margin-left: 0rem;
45
+ }
46
+ #title-container h1 {
47
+ color: #222 !important;
48
+ font-size: 4rem;
49
+ font-family: 'Noto Sans JP', sans-serif;
50
+ margin: 0;
51
+ }
52
+ #title-container .subtitle {
53
+ font-size: 1.1rem;
54
+ font-family: 'Noto Sans', sans-serif;
55
+ color: #222 !important;
56
+ margin-top: 0.5rem;
57
+ margin-bottom: 0;
58
+ width: 100%;
59
+ display: block;
60
+ }
61
+ #chat-panel {
62
+ background-color: rgba(255, 255, 255, 0.85);
63
+ padding: 2rem;
64
+ border-radius: 12px;
65
+ justify-content: center;
66
+ width: 100%;
67
+ max-width: 700px;
68
+ height: 70vh;
69
+ box-shadow: 0 0 12px rgba(0, 0, 0, 0.3);
70
+ overflow-y: auto;
71
+ }
72
+ .gradio-container .chatbot h1 {
73
+ color: var(--custom-title-color) !important;
74
+ font-family: 'Noto Sans', serif !important;
75
+ font-size: 5rem !important;
76
+ font-weight: bold !important;
77
+ text-align: center !important;
78
+ margin-bottom: 1.5rem !important;
79
+ width: 100%;
80
+ }
81
  """
82
 
83
+ # ---------- Prompting ----------
 
 
 
84
  def level_to_prompt(level: str) -> str:
85
  return {
86
  "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.",
 
91
  "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.",
92
  }.get(level, "You are a helpful French tutor.")
93
 
94
+ # ---------- Message shaping ----------
 
 
 
 
 
 
 
 
95
  GradioMessage = Dict[str, str]
96
  HistoryItem = Union[Tuple[str, str], GradioMessage]
97
  History = Optional[Sequence[HistoryItem]]
 
100
  msgs: List[GradioMessage] = []
101
  if not history:
102
  return msgs
 
103
  for item in history:
104
  if isinstance(item, tuple) and len(item) == 2:
105
  u, a = item
 
117
  history: History,
118
  system_text: str,
119
  ) -> List[GradioMessage]:
 
120
  if isinstance(message, list) and all(isinstance(m, dict) and "role" in m for m in message):
121
  user_msgs = [m for m in message if m.get("role") != "system"]
122
  return [{"role": "system", "content": system_text}, *user_msgs]
 
123
  msgs = [{"role": "system", "content": system_text}, *_history_to_messages(history)]
124
  if isinstance(message, str) and message:
125
  msgs.append({"role": "user", "content": message})
126
  return msgs
127
 
128
+ # ---------- OpenAI-compatible HF router ----------
129
+ def create_hf_openai_client(token: Optional[str]) -> OpenAI:
130
+ """
131
+ WHY: HF Inference Providers exposes OpenAI-compatible /v1 endpoints at router.hf.co/hf-inference.
132
+ Using the OpenAI SDK avoids deprecated api-inference paths.
133
+ """
134
+ api_key = token or os.getenv("HUGGINGFACEHUB_API_TOKEN") or os.getenv("HF_TOKEN")
135
+ if not api_key:
136
+ # WHY: Fail fast with a clear message when router requires auth.
137
+ raise RuntimeError(
138
+ "Missing Hugging Face token. Provide it in Advanced Settings or set HUGGINGFACEHUB_API_TOKEN."
139
+ )
140
+ return OpenAI(base_url="https://router.huggingface.co/hf-inference/v1", api_key=api_key)
141
 
 
142
  def stream_chat(
143
+ client: OpenAI,
 
144
  *,
145
+ model_id: str,
146
+ messages: List[GradioMessage],
147
  max_tokens: int,
148
  temperature: float,
149
  top_p: float,
150
  ) -> Iterable[str]:
151
  buf = ""
152
  try:
153
+ stream = client.chat.completions.create(
154
+ model=model_id,
155
  messages=messages,
156
+ max_tokens=max_tokens,
157
  temperature=temperature,
158
  top_p=top_p,
159
  stream=True,
160
+ )
161
+ for chunk in stream:
162
+ delta = getattr(chunk.choices[0], "delta", None)
163
  piece = getattr(delta, "content", None) if delta is not None else None
164
  if piece:
165
  buf += piece
166
  yield buf
167
  except Exception as e:
168
  msg = str(e)
169
+ if "api-inference.huggingface.co" in msg or "410" in msg or "404" in msg:
170
+ yield "Le point d’accès a changé. Utilisez le routeur: https://router.huggingface.co/hf-inference/v1 et un token HF avec droit Inference Providers."
171
+ elif "401" in msg or "Unauthorized" in msg:
172
+ yield "Désolé ! Auth error (401). Ajoutez un token HF (permission: Inference Providers) dans Advanced Settings ou via HUGGINGFACEHUB_API_TOKEN."
173
  else:
174
  yield f"Désolé ! An error occurred: {msg}"
175
 
176
+ # ---------- Gradio callback (matches ChatInterface calling convention) ----------
 
177
  def respond(
178
  message: Union[str, List[GradioMessage]],
179
  history: History,
 
181
  max_tokens: int,
182
  temperature: float,
183
  top_p: float,
184
+ model_id: str,
185
  hf_token: Optional[str],
186
  ):
187
  system_message = level_to_prompt(user_level)
188
  msgs = coerce_to_messages(message, history, system_message)
 
189
 
190
+ # Defensive bounds (WHY: avoid provider errors on out-of-range values)
191
  max_tokens = int(max(1, min(int(max_tokens), 4096)))
192
  temperature = float(max(0.0, min(float(temperature), 4.0)))
193
  top_p = float(max(0.0, min(float(top_p), 1.0)))
194
+ model = (model_id or "").strip() or "meta-llama/Meta-Llama-3.1-8B-Instruct"
195
+
196
+ try:
197
+ client = create_hf_openai_client(hf_token)
198
+ except Exception as e:
199
+ yield f"Désolé ! {e}"
200
+ return
201
 
202
  yield from stream_chat(
203
  client,
204
+ model_id=model,
205
+ messages=msgs,
206
  max_tokens=max_tokens,
207
  temperature=temperature,
208
  top_p=top_p,
209
  )
210
 
211
+ # ---------- UI ----------
 
212
  with gr.Blocks(css=css) as demo:
213
  gr.HTML(
214
  """
 
229
  max_tokens = gr.Slider(1, 4096, value=400, step=1, label="Response Length")
230
  temperature = gr.Slider(0.0, 4.0, value=0.5, step=0.1, label="Creativity")
231
  top_p = gr.Slider(0.0, 1.0, value=0.85, step=0.05, label="Dynamic Text Sampling")
232
+ model_id = gr.Textbox(
233
+ label="Model (HF Inference Providers, OpenAI-style)",
234
+ value="meta-llama/Meta-Llama-3.1-8B-Instruct",
235
+ placeholder="e.g. mistralai/Mixtral-8x7B-Instruct-v0.1",
236
+ )
237
  hf_token = gr.Textbox(
238
+ label="Hugging Face Token (required for router)",
239
  type="password",
240
+ placeholder="hf_xxx — enable 'Make calls to Inference Providers' in token settings",
241
  )
242
 
243
  gr.ChatInterface(
244
+ fn=respond, # called as (message, history, *additional_inputs)
245
+ additional_inputs=[user_level, max_tokens, temperature, top_p, model_id, hf_token],
246
+ type="messages",
247
  )
248
 
249
  if __name__ == "__main__":
250
+ # WHY: explicit host/port makes local & container runs predictable
251
  demo.launch(server_name="0.0.0.0", server_port=7860, share=False)