Spaces:
Runtime error
Runtime error
Update app.py
Browse files123456710 unmodified lines181920212223241 unmodified line2627282930313232 unmodified lines6566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143import gradio as grfrom huggingface_hub import InferenceClient# Background CSScss = """body {background-image: url('https://cdn-uploads.huggingface.co/production/uploads/67351c643fe51cb1aa28f2e5/YcsJnPk8HJvXiB5WkVmf1.jpeg');10 unmodified linespadding-bottom: 2rem;}#title-container {background-color: rgba(255, 255, 255, 0.85); /* match chat panel */border-radius: 16px;padding: 1.5rem 2rem;margin: 2rem 0;1 unmodified linemax-width: 500px;text-align: left;box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);margin-left: 0rem; /* Aligns left edge */}#title-container h1 {color: #222 !important;32 unmodified lines}"""# Model client (consider switching to a public model like mistralai if 401 persists)client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")# Level prompt selectordef level_to_prompt(level):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.","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.","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.","B2": "You are a French tutor. Respond primarily in French and include only concise, relevant elaborations. Avoid suggesting voice interaction or unrelated content.","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.","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."}.get(level, "You are a helpful French tutor.")# Chat handlerdef respond(message, history, user_level, max_tokens, temperature, top_p):system_message = level_to_prompt(user_level)messages = [{"role": "system", "content": system_message}]# Handle historyif history and isinstance(history[0], tuple):for user_msg, assistant_msg in history:if user_msg:messages.append({"role": "user", "content": user_msg})if assistant_msg:messages.append({"role": "assistant", "content": assistant_msg})else:messages.extend(history)messages.append({"role": "user", "content": message})response = ""try:for msg in client.chat_completion(messages,max_tokens=max_tokens,stream=True,temperature=temperature,top_p=top_p,):token = msg.choices[0].delta.contentif token:response += tokenyield responseexcept Exception as e:yield f"Désolé! There was an error: {str(e)}"# Gradio interfacewith 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, 2048, value=400, step=1, label="Response Length")temperature = gr.Slider(0.1, 4.0, value=0.5, step=0.1, label="Creativity")top_p = gr.Slider(0.1, 1.0, value=0.85, step=0.05, label="Dynamic Text Sampling")gr.ChatInterface(respond,additional_inputs=[user_level, max_tokens, temperature, top_p],type="messages")if __name__ == "__main__":demo.launch()12345678910111210 unmodified lines232425262728291 unmodified line3132333435363732 unmodified lines707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197# app.pyimport osfrom typing import Any, Dict, Iterable, Listimport gradio as grfrom huggingface_hub import InferenceClient, hf_api# ---- Background CSS (kept from your snippet) ----css = """body {background-image: url('https://cdn-uploads.huggingface.co/production/uploads/67351c643fe51cb1aa28f2e5/YcsJnPk8HJvXiB5WkVmf1.jpeg');10 unmodified linespadding-bottom: 2rem;}#title-container {background-color: rgba(255, 255, 255, 0.85);border-radius: 16px;padding: 1.5rem 2rem;margin: 2rem 0;1 unmodified linemax-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;32 unmodified lines}"""MODEL_ID = "HuggingFaceH4/zephyr-7b-beta" # switch to a public Inference API-enabled model if this is gated# ---- 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.","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.","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.","B2": "You are a French tutor. Respond primarily in French and include only concise, relevant elaborations. Avoid suggesting voice interaction or unrelated content.","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.","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.",}.get(level, "You are a helpful French tutor.")# ---- HF Client ----def create_client(token: str | None) -> InferenceClient:# WHY: re-create per call so users can supply token at runtime (avoids global state & 401s).tok = token or os.getenv("HUGGINGFACEHUB_API_TOKEN") or os.getenv("HF_TOKEN")return InferenceClient(model=MODEL_ID, token=tok)# ---- Message shaping ----def normalize_messages(gradio_messages: List[Dict[str, str]], system_text: str) -> List[Dict[str, str]]:# Gradio (type="messages") sends full chat as list of {role, content}.msgs: List[Dict[str, str]] = []# Drop any incoming system prompts; we control the single system message.for m in gradio_messages:if m.get("role") != "system":msgs.append({"role": m.get("role", "user"), "content": m.get("content", "")})return [{"role": "system", "content": system_text}, *msgs]# ---- Streaming call wrapper ----def stream_chat(client: InferenceClient,messages: List[Dict[str, str]],*,max_tokens: int,temperature: float,top_p: float,) -> Iterable[str]:buf = ""try:# Some servers return events where delta.content can be None (role/tool changes) → guard it.for ev in client.chat_completion(messages=messages,max_tokens=max_tokens,temperature=temperature,top_p=top_p,stream=True,):delta = getattr(ev.choices[0], "delta", None)piece = getattr(delta, "content", None) if delta is not None else Noneif piece:buf += pieceyield bufexcept Exception as e:# WHY: Surface common auth hint for 401 to reduce confusion.msg = str(e)if "401" in msg or "Unauthorized" in msg:yield "Désolé ! Auth error (401). Provide a valid Hugging Face token in Advanced Settings or set HUGGINGFACEHUB_API_TOKEN."else:yield f"Désolé ! An error occurred: {msg}"# ---- Gradio callback (matches `type="messages"` signature) ----def respond(messages: List[Dict[str, str]],user_level: str,max_tokens: int,temperature: float,top_p: float,hf_token: str | None,):system_message = level_to_prompt(user_level)msgs = normalize_messages(messages, system_message)client = create_client(hf_token)# Enforce bounds defensivelymax_tokens = int(max(1, min(int(max_tokens), 4096)))temperature = float(max(0.0, min(float(temperature), 4.0)))top_p = float(max(0.0, min(float(top_p), 1.0)))yield from stream_chat(client,msgs,max_tokens=max_tokens,temperature=temperature,top_p=top_p,)# ---- 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")hf_token = gr.Textbox(label="Hugging Face Token (optional)",type="password",placeholder="hf_xxx — leave empty if set via env",)gr.ChatInterface(fn=respond,additional_inputs=[user_level, max_tokens, temperature, top_p, hf_token],type="messages", # IMPORTANT: pairs with respond(messages, ...))if __name__ == "__main__":# WHY: show URL in logs; enable queues for streaming concurrency.demo.launch(server_name="0.0.0.0", server_port=7860, share=False)
app.py+104-50