Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,11 +1,8 @@
|
|
| 1 |
-
# app.py
|
| 2 |
-
"""
|
| 3 |
-
|
| 4 |
-
|
| 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
|
|
@@ -14,7 +11,7 @@ import os
|
|
| 14 |
from typing import Dict, Iterable, List, Optional, Sequence, Tuple, Union
|
| 15 |
|
| 16 |
import gradio as gr
|
| 17 |
-
from
|
| 18 |
|
| 19 |
# ---------- Styling ----------
|
| 20 |
css = """
|
|
@@ -24,60 +21,12 @@ body {
|
|
| 24 |
background-position: center;
|
| 25 |
background-repeat: no-repeat;
|
| 26 |
}
|
| 27 |
-
.gradio-container {
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 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 ----------
|
|
@@ -125,22 +74,16 @@ def coerce_to_messages(
|
|
| 125 |
msgs.append({"role": "user", "content": message})
|
| 126 |
return msgs
|
| 127 |
|
| 128 |
-
# ----------
|
| 129 |
-
def
|
| 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 |
-
|
| 137 |
-
|
| 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:
|
| 144 |
*,
|
| 145 |
model_id: str,
|
| 146 |
messages: List[GradioMessage],
|
|
@@ -150,7 +93,7 @@ def stream_chat(
|
|
| 150 |
) -> Iterable[str]:
|
| 151 |
buf = ""
|
| 152 |
try:
|
| 153 |
-
|
| 154 |
model=model_id,
|
| 155 |
messages=messages,
|
| 156 |
max_tokens=max_tokens,
|
|
@@ -158,22 +101,23 @@ def stream_chat(
|
|
| 158 |
top_p=top_p,
|
| 159 |
stream=True,
|
| 160 |
)
|
| 161 |
-
for
|
| 162 |
-
delta = getattr(
|
| 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 "
|
| 171 |
-
elif "401" in msg or "Unauthorized" in msg:
|
| 172 |
-
yield "
|
| 173 |
else:
|
| 174 |
-
yield f"Désolé !
|
| 175 |
|
| 176 |
-
# ---------- Gradio callback
|
| 177 |
def respond(
|
| 178 |
message: Union[str, List[GradioMessage]],
|
| 179 |
history: History,
|
|
@@ -187,14 +131,13 @@ def respond(
|
|
| 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 =
|
| 198 |
except Exception as e:
|
| 199 |
yield f"Désolé ! {e}"
|
| 200 |
return
|
|
@@ -230,12 +173,12 @@ with gr.Blocks(css=css) as demo:
|
|
| 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
|
| 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
|
| 239 |
type="password",
|
| 240 |
placeholder="hf_xxx — enable 'Make calls to Inference Providers' in token settings",
|
| 241 |
)
|
|
@@ -247,5 +190,4 @@ with gr.Blocks(css=css) as demo:
|
|
| 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)
|
|
|
|
| 1 |
+
# file: app.py
|
| 2 |
+
"""French tutor (Gradio) using Hugging Face Inference Providers router (OpenAI-style chat.completions).
|
| 3 |
+
- Requires huggingface_hub>=0.28 (provides `InferenceClient.chat.completions.create`).
|
| 4 |
+
- Fixes Gradio ChatInterface: respond(message, history, *additional_inputs).
|
| 5 |
+
- Adds model picker + HF token input; streams via router.huggingface.co/hf-inference.
|
|
|
|
|
|
|
|
|
|
| 6 |
"""
|
| 7 |
|
| 8 |
from __future__ import annotations
|
|
|
|
| 11 |
from typing import Dict, Iterable, List, Optional, Sequence, Tuple, Union
|
| 12 |
|
| 13 |
import gradio as gr
|
| 14 |
+
from huggingface_hub import InferenceClient
|
| 15 |
|
| 16 |
# ---------- Styling ----------
|
| 17 |
css = """
|
|
|
|
| 21 |
background-position: center;
|
| 22 |
background-repeat: no-repeat;
|
| 23 |
}
|
| 24 |
+
.gradio-container { display: flex; flex-direction: column; justify-content: center; min-height: 100vh; padding-top: 2rem; padding-bottom: 2rem; }
|
| 25 |
+
#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; }
|
| 26 |
+
#title-container h1 { color: #222 !important; font-size: 4rem; font-family: 'Noto Sans JP', sans-serif; margin: 0; }
|
| 27 |
+
#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; }
|
| 28 |
+
#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; }
|
| 29 |
+
.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%; }
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
"""
|
| 31 |
|
| 32 |
# ---------- Prompting ----------
|
|
|
|
| 74 |
msgs.append({"role": "user", "content": message})
|
| 75 |
return msgs
|
| 76 |
|
| 77 |
+
# ---------- HF Router client ----------
|
| 78 |
+
def create_client(token: Optional[str]) -> InferenceClient:
|
| 79 |
+
# WHY: use router via huggingface_hub>=0.28 (OpenAI-style chat.completions)
|
|
|
|
|
|
|
|
|
|
| 80 |
api_key = token or os.getenv("HUGGINGFACEHUB_API_TOKEN") or os.getenv("HF_TOKEN")
|
| 81 |
if not api_key:
|
| 82 |
+
raise RuntimeError("Missing Hugging Face token (enable 'Make calls to Inference Providers').")
|
| 83 |
+
return InferenceClient(api_key=api_key) # model is passed per call
|
|
|
|
|
|
|
|
|
|
| 84 |
|
| 85 |
def stream_chat(
|
| 86 |
+
client: InferenceClient,
|
| 87 |
*,
|
| 88 |
model_id: str,
|
| 89 |
messages: List[GradioMessage],
|
|
|
|
| 93 |
) -> Iterable[str]:
|
| 94 |
buf = ""
|
| 95 |
try:
|
| 96 |
+
events = client.chat.completions.create(
|
| 97 |
model=model_id,
|
| 98 |
messages=messages,
|
| 99 |
max_tokens=max_tokens,
|
|
|
|
| 101 |
top_p=top_p,
|
| 102 |
stream=True,
|
| 103 |
)
|
| 104 |
+
for ev in events:
|
| 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 |
+
# WHY: map common router/auth errors to actionable hints.
|
| 112 |
msg = str(e)
|
| 113 |
if "api-inference.huggingface.co" in msg or "410" in msg or "404" in msg:
|
| 114 |
+
yield "Endpoint deprecated; using router requires huggingface_hub>=0.28 and a valid model on Inference Providers."
|
| 115 |
+
elif "401" in msg or "Unauthorized" in msg or "permission" in msg:
|
| 116 |
+
yield "Auth error. Provide an HF token with 'Inference Providers' permission."
|
| 117 |
else:
|
| 118 |
+
yield f"Désolé ! {msg}"
|
| 119 |
|
| 120 |
+
# ---------- Gradio callback ----------
|
| 121 |
def respond(
|
| 122 |
message: Union[str, List[GradioMessage]],
|
| 123 |
history: History,
|
|
|
|
| 131 |
system_message = level_to_prompt(user_level)
|
| 132 |
msgs = coerce_to_messages(message, history, system_message)
|
| 133 |
|
|
|
|
| 134 |
max_tokens = int(max(1, min(int(max_tokens), 4096)))
|
| 135 |
temperature = float(max(0.0, min(float(temperature), 4.0)))
|
| 136 |
top_p = float(max(0.0, min(float(top_p), 1.0)))
|
| 137 |
model = (model_id or "").strip() or "meta-llama/Meta-Llama-3.1-8B-Instruct"
|
| 138 |
|
| 139 |
try:
|
| 140 |
+
client = create_client(hf_token)
|
| 141 |
except Exception as e:
|
| 142 |
yield f"Désolé ! {e}"
|
| 143 |
return
|
|
|
|
| 173 |
temperature = gr.Slider(0.0, 4.0, value=0.5, step=0.1, label="Creativity")
|
| 174 |
top_p = gr.Slider(0.0, 1.0, value=0.85, step=0.05, label="Dynamic Text Sampling")
|
| 175 |
model_id = gr.Textbox(
|
| 176 |
+
label="Model (HF Inference Providers)",
|
| 177 |
value="meta-llama/Meta-Llama-3.1-8B-Instruct",
|
| 178 |
+
placeholder="e.g. mistralai/Mixtral-8x7B-Instruct-v0.1 or deepseek-ai/DeepSeek-R1",
|
| 179 |
)
|
| 180 |
hf_token = gr.Textbox(
|
| 181 |
+
label="Hugging Face Token",
|
| 182 |
type="password",
|
| 183 |
placeholder="hf_xxx — enable 'Make calls to Inference Providers' in token settings",
|
| 184 |
)
|
|
|
|
| 190 |
)
|
| 191 |
|
| 192 |
if __name__ == "__main__":
|
|
|
|
| 193 |
demo.launch(server_name="0.0.0.0", server_port=7860, share=False)
|