Spaces:
Runtime error
Runtime error
Update app.py
Browse files1234567891011121314151617181920212223242526272829303 unmodified lines3435363738394041424344454616 unmodified lines63646566676869707172737475767778798081828384853 unmodified lines89909192939495969798991001011021031041051061071081091103 unmodified lines11411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515612 unmodified lines1691701711721731741751761771781791801811821831841851861871881891901911921931948 unmodified lines2032042052062072082092102112122132142152162172182192202212222237 unmodified lines2312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612621 unmodified line264265266267268269270# file: app.py"""Gradio French tutor using Hugging Face Inference Providers router (OpenAI-style /v1/chat/completions).Requirements:- huggingface_hub>=0.28 (you reported 1.1.7, which is fine)- gradio>=4.44.0- httpx (gradio usually brings it; kept explicit import)Key points:- Uses InferenceClient.chat.completions.create(stream=True)- Works with ChatInterface(type="messages") via correct callback signature- Automatically selects a provider-available model from /v1/models if needed"""from __future__ import annotationsimport osfrom typing import Dict, Iterable, List, Optional, Sequence, Tuple, Unionimport httpximport gradio as grfrom huggingface_hub import InferenceClientROUTER_BASE = "https://router.huggingface.co"# ---------- CSS (unchanged from your original) ----------css = """body {background-image: url('https://cdn-uploads.huggingface.co/production/uploads/67351c643fe51cb1aa28f2e5/YcsJnPk8HJvXiB5WkVmf1.jpeg');3 unmodified lines}.gradio-container { display: flex; flex-direction: column; justify-content: center; min-height: 100vh; padding-top: 2rem; padding-bottom: 2rem; }#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; }#title-container h1 { color: #222 !important; font-size: 4rem; font-family: 'Noto Sans JP', sans-serif; margin: 0; }#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; }#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; }.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%; }"""# ---------- Prompt role ----------def level_to_prompt(level: str) -> str:return {"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.",16 unmodified linesfor item in history:if isinstance(item, tuple) and len(item) == 2:u, a = itemif u:msgs.append({"role": "user", "content": u})if a:msgs.append({"role": "assistant", "content": a})elif isinstance(item, dict) and "role" in item and "content" in item:if item["role"] != "system":msgs.append({"role": item["role"], "content": item["content"]})return msgsdef coerce_to_messages(message: Union[str, List[GradioMessage]],history: History,system_text: str,) -> List[GradioMessage]:if isinstance(message, list) and all(isinstance(m, dict) and "role" in m for m in message):user_msgs = [m for m in message if m.get("role") != "system"]return [{"role": "system", "content": system_text}, *user_msgs]msgs = [{"role": "system", "content": system_text}, *_history_to_messages(history)]if isinstance(message, str) and message:msgs.append({"role": "user", "content": message})3 unmodified linesdef get_token(user_token: Optional[str]) -> str:tok = user_token or os.getenv("HUGGINGFACEHUB_API_TOKEN") or os.getenv("HF_TOKEN")if not tok:raise RuntimeError("Missing Hugging Face token (enable 'Make calls to Inference Providers').")return tokdef list_models(token: str) -> List[str]:r = httpx.get(f"{ROUTER_BASE}/v1/models",headers={"Authorization": f"Bearer {token}"},timeout=30,)r.raise_for_status()data = r.json()return [m["id"] for m in data.get("data", []) if isinstance(m, dict) and "id" in m]def choose_model(token: str, requested: Optional[str]) -> tuple[str, Optional[str]]:# preference order for common, instruction-tuned modelspreferred = ["meta-llama/Llama-3.1-8B-Instruct","mistralai/Mixtral-8x7B-Instruct-v0.1","Qwen/Qwen2.5-7B-Instruct",3 unmodified linestry:available = list_models(token)except Exception:fallback = requested or "meta-llama/Llama-3.1-8B-Instruct"return fallback, Noneif requested and requested in available:return requested, None# pick first preferred that existsfor mid in preferred:if mid in available:if requested and requested not in available:note = f"Requested model '{requested}' not available on your provider/token. Using '{mid}'."elif not requested:note = f"No model specified. Using '{mid}'."return mid, note# final fallback: first availableif available:chosen = available[0]if requested:note = f"Requested model '{requested}' not available. Using '{chosen}'."else:note = f"No model specified. Using '{chosen}'."return chosen, note# no models visible; return requested or default and let call error with a clear messagereturn (requested or "meta-llama/Llama-3.1-8B-Instruct"), "No models visible to your token on Inference Providers."# ---------- Streaming ----------def stream_chat(client: InferenceClient,*,model_id: str,messages: List[GradioMessage],max_tokens: int,temperature: float,top_p: float,) -> Iterable[str]:buf = ""try:events = client.chat.completions.create(12 unmodified linesyield bufexcept Exception as e:msg = str(e)if "api-inference.huggingface.co" in msg or "410" in msg or "404" in msg:yield "Endpoint deprecated; ensure huggingface_hub>=0.28 and use the router with a provider-backed model."elif "model_not_found" in msg or "does not exist" in msg:yield f"Model not found/available: '{model_id}'. Use the List models button to pick a valid one."elif "401" in msg or "403" in msg or "Unauthorized" in msg or "permission" in msg:yield "Auth error. Provide an HF token with 'Make calls to Inference Providers' permission."else:yield f"Désolé ! {msg}"# ---------- Gradio callback (matches ChatInterface: message, history, *inputs) ----------def respond(message: Union[str, List[GradioMessage]],history: History,user_level: str,max_tokens: int,temperature: float,top_p: float,model_id: str,hf_token: Optional[str],):system_message = level_to_prompt(user_level)msgs = coerce_to_messages(message, history, system_message)8 unmodified linesreturnchosen_model, note = choose_model(token, (model_id or "").strip() or None)if note:yield f"ℹ️ {note}"client = InferenceClient(api_key=token)yield from stream_chat(client,model_id=chosen_model,messages=msgs,max_tokens=max_tokens,temperature=temperature,top_p=top_p,)# ---------- Extra UI: list models ----------def list_models_ui(hf_token: Optional[str]) -> str:try:token = get_token(hf_token)7 unmodified lines# ---------- UI ----------with gr.Blocks(css=css) as demo:gr.HTML("""<div id="title-container"><h1>LE PROFESSEUR</h1><p class="subtitle">French Tutor</p></div>""")with gr.Column(elem_id="chat-panel"):with gr.Accordion("Advanced Settings", open=False):user_level = gr.Dropdown(choices=["A1", "A2", "B1", "B2", "C1", "C2"],value="A1",label="Your French Level (CEFR)",)max_tokens = gr.Slider(1, 4096, value=400, step=1, label="Response Length")temperature = gr.Slider(0.0, 4.0, value=0.5, step=0.1, label="Creativity")top_p = gr.Slider(0.0, 1.0, value=0.85, step=0.05, label="Dynamic Text Sampling")model_id = gr.Textbox(label="Model (HF Inference Providers)",value="meta-llama/Llama-3.1-8B-Instruct",placeholder="Leave blank to auto-pick; or e.g. mistralai/Mixtral-8x7B-Instruct-v0.1",)hf_token = gr.Textbox(label="Hugging Face Token",type="password",placeholder="hf_xxx — must allow 'Make calls to Inference Providers'",)with gr.Row():list_btn = gr.Button("List models (visible to my token)")models_box = gr.Textbox(label="Available models", lines=10)1 unmodified linelist_btn.click(list_models_ui, inputs=[hf_token], outputs=[models_box])gr.ChatInterface(fn=respond,additional_inputs=[user_level, max_tokens, temperature, top_p, model_id, hf_token],type="messages",)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051523 unmodified lines5657585960616263646566676816 unmodified lines8586878889909192939495969798991001013 unmodified lines1051061071081091101111121131141151161171181191201213 unmodified lines12512612712812913013113213313413513613713813914014114214314414514614714814915015115215315412 unmodified lines1671681691701711721731741751761771781791801811821831841851861871881891908 unmodified lines1992002012022032042052062072082092102112127 unmodified lines2202212222232242252262272282292302312322332342352362372382392402412421 unmodified line244245246247248249250# file: app.py"""Gradio French Tutor — HF Inference Providers (router) with Gradio<5 + huggingface_hub>=1.0 compatibility shim.- Fixes Gradio ImportError by injecting HfFolder/whoami shims before importing gradio.- Uses huggingface_hub>=0.28+ InferenceClient.chat.completions.create(stream=True) against router.- Auto-picks an available provider-backed model if none/invalid is given."""from __future__ import annotationsimport osimport sysfrom typing import Dict, Iterable, List, Optional, Sequence, Tuple, Union# ---------- Compatibility shim: add HfFolder / whoami if missing (Gradio<5 expects them) ----------try:import huggingface_hub as _hub # noqa: F401if not hasattr(_hub, "HfFolder"):class _HfFolder: # WHY: provide minimal token accessor to satisfy old gradio import@staticmethoddef get_token() -> Optional[str]:return (os.getenv("HUGGINGFACEHUB_API_TOKEN")or os.getenv("HF_TOKEN")or os.getenv("HF_HOME_TOKEN"))_hub.HfFolder = _HfFolder # type: ignore[attr-defined]if not hasattr(_hub, "whoami"):def _whoami(token: Optional[str] = None) -> Dict[str, str]:return {}_hub.whoami = _whoami # type: ignore[attr-defined]except Exception:pass # If hub not installed yet, gradio import will fail earlier anyway.# Now it is safe to import gradio even if it is <5 and hub>=1.0import httpximport gradio as grfrom huggingface_hub import InferenceClient, __version__ as _hub_ver# Optional: print versions once for easier debuggingtry:import importlib.metadata as _md_gr_ver = _md.version("gradio")print(f"[startup] gradio={_gr_ver} huggingface_hub={_hub_ver}", file=sys.stderr)except Exception:passROUTER_BASE = "https://router.huggingface.co"# ---------- CSS (your original) ----------css = """body {background-image: url('https://cdn-uploads.huggingface.co/production/uploads/67351c643fe51cb1aa28f2e5/YcsJnPk8HJvXiB5WkVmf1.jpeg');3 unmodified lines}.gradio-container { display: flex; flex-direction: column; justify-content: center; min-height: 100vh; padding-top: 2rem; padding-bottom: 2rem; }#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; }#title-container h1 { color:#222 !important; font-size:4rem; font-family:'Noto Sans JP',sans-serif; margin:0; }#title-container .subtitle { font-size:1.1rem; font-family:'Noto Sans',sans-serif; color:#222 !important; margin-top:.5rem; margin-bottom:0; width:100%; display:block; }#chat-panel { background-color:rgba(255,255,255,.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,.3); overflow-y:auto; }.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%; }"""# ---------- Prompting ----------def level_to_prompt(level: str) -> str:return {"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.",16 unmodified linesfor item in history:if isinstance(item, tuple) and len(item) == 2:u, a = itemif u: msgs.append({"role": "user", "content": u})if a: msgs.append({"role": "assistant", "content": a})elif isinstance(item, dict) and "role" in item and "content" in item:if item["role"] != "system":msgs.append({"role": item["role"], "content": item["content"]})return msgsdef coerce_to_messages(message: Union[str, List[GradioMessage]], history: History, system_text: str) -> List[GradioMessage]:if isinstance(message, list) and all(isinstance(m, dict) and "role" in m for m in message):cleaned = [m for m in message if m.get("role") != "system"]return [{"role": "system", "content": system_text}, *cleaned]msgs = [{"role": "system", "content": system_text}, *_history_to_messages(history)]if isinstance(message, str) and message:msgs.append({"role": "user", "content": message})3 unmodified linesdef get_token(user_token: Optional[str]) -> str:tok = user_token or os.getenv("HUGGINGFACEHUB_API_TOKEN") or os.getenv("HF_TOKEN")if not tok:raise RuntimeError("Missing Hugging Face token (needs 'Make calls to Inference Providers').")return tokdef list_models(token: str) -> List[str]:r = httpx.get(f"{ROUTER_BASE}/v1/models", headers={"Authorization": f"Bearer {token}"}, timeout=30)r.raise_for_status()data = r.json()return [m["id"] for m in data.get("data", []) if isinstance(m, dict) and "id" in m]def choose_model(token: str, requested: Optional[str]) -> tuple[str, Optional[str]]:prefs = ["meta-llama/Llama-3.1-8B-Instruct","mistralai/Mixtral-8x7B-Instruct-v0.1","Qwen/Qwen2.5-7B-Instruct",3 unmodified linestry:available = list_models(token)except Exception:return (requested or "meta-llama/Llama-3.1-8B-Instruct"), Noneif requested and requested in available:return requested, Nonefor mid in prefs:if mid in available:if requested and requested not in available:note = f"Requested model '{requested}' not available. Using '{mid}'."elif not requested:note = f"No model specified. Using '{mid}'."return mid, noteif available:chosen = available[0]note = (f"Requested '{requested}' not available. Using '{chosen}'."if requested else f"No model specified. Using '{chosen}'.")return chosen, notereturn (requested or "meta-llama/Llama-3.1-8B-Instruct"), "No models visible to your token on Inference Providers."# ---------- Streaming via HF Router (OpenAI-style chat.completions) ----------def stream_chat(client: InferenceClient, *, model_id: str, messages: List[GradioMessage],max_tokens: int, temperature: float, top_p: float) -> Iterable[str]:buf = ""try:events = client.chat.completions.create(12 unmodified linesyield bufexcept Exception as e:msg = str(e)if any(x in msg for x in ("api-inference.huggingface.co", "410", "404")):yield "Endpoint deprecated; ensure huggingface_hub>=0.28 and use router with a provider-backed model."elif "model_not_found" in msg or "does not exist" in msg:yield f"Model not found/available: '{model_id}'. Use the List models button to pick a valid one."elif any(x in msg for x in ("401", "403", "Unauthorized", "permission")):yield "Auth error. Provide an HF token with 'Make calls to Inference Providers' permission."else:yield f"Désolé ! {msg}"# ---------- Gradio callback ----------def respond(message: Union[str, List[GradioMessage]],history: History,user_level: str,max_tokens: int,temperature: float,top_p: float,model_id: str,hf_token: Optional[str]):system_message = level_to_prompt(user_level)msgs = coerce_to_messages(message, history, system_message)8 unmodified linesreturnchosen_model, note = choose_model(token, (model_id or "").strip() or None)if note:yield f"ℹ️ {note}"client = InferenceClient(api_key=token)yield from stream_chat(client, model_id=chosen_model, messages=msgs,max_tokens=max_tokens, temperature=temperature, top_p=top_p)# ---------- Extra UI action ----------def list_models_ui(hf_token: Optional[str]) -> str:try:token = get_token(hf_token)7 unmodified lines# ---------- UI ----------with gr.Blocks(css=css) as demo:gr.HTML("""<div id="title-container"><h1>LE PROFESSEUR</h1><p class="subtitle">French Tutor</p></div>""")with gr.Column(elem_id="chat-panel"):with gr.Accordion("Advanced Settings", open=False):user_level = gr.Dropdown(choices=["A1","A2","B1","B2","C1","C2"], value="A1", label="Your French Level (CEFR)")max_tokens = gr.Slider(1, 4096, value=400, step=1, label="Response Length")temperature = gr.Slider(0.0, 4.0, value=0.5, step=0.1, label="Creativity")top_p = gr.Slider(0.0, 1.0, value=0.85, step=0.05, label="Dynamic Text Sampling")model_id = gr.Textbox(label="Model (HF Inference Providers)",value="meta-llama/Llama-3.1-8B-Instruct",placeholder="Leave blank to auto-pick; e.g. mistralai/Mixtral-8x7B-Instruct-v0.1")hf_token = gr.Textbox(label="Hugging Face Token", type="password",placeholder="hf_xxx — must allow 'Make calls to Inference Providers'")with gr.Row():list_btn = gr.Button("List models (visible to my token)")models_box = gr.Textbox(label="Available models", lines=10)1 unmodified linelist_btn.click(list_models_ui, inputs=[hf_token], outputs=[models_box])gr.ChatInterface(fn=respond, # called as (message, history, *additional_inputs)additional_inputs=[user_level, max_tokens, temperature, top_p, model_id, hf_token],type="messages",)
app.py+81-101