Spaces:
Runtime error
Runtime error
Update app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475764 unmodified lines81828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128import gradio as grfrom huggingface_hub import InferenceClient# --------------------------# NEW: HF Router Client# --------------------------client = InferenceClient(base_url="https://router.huggingface.co/v1" # OpenAI-compatible API)# --------------------------# Tutor Levels# --------------------------def level_to_prompt(level):prompts = {"A1": "You are a friendly French tutor. Use simple French, short sentences, and explain difficult words in English.","A2": "You are a patient French tutor. Use simple French. Give short explanations in English when needed.","B1": "You are a helpful French tutor. Use mostly French, with short English explanations only when truly necessary.","B2": "You are a French tutor. Respond primarily in French with clear, concise explanations.","C1": "You are a native French tutor. Respond in fluent French with occasional linguistic or cultural notes.","C2": "You are a French language professor. Use sophisticated French with precise grammar explanations.",}return prompts.get(level, prompts["A1"])# --------------------------# CLEAN, SAFE CHAT HANDLER# --------------------------def respond(message, history, user_level, max_tokens, temperature, top_p):"""Gradio's ChatInterface will trigger 'dict.strip' errors if anythingexcept a string is returned. This handler forces all history and messagefields to clean strings and always yields strings."""# Ensure user message is a stringif isinstance(message, dict):# Gradio sometimes passes dictsmessage = message.get("content") or message.get("text") or message.get("prompt") or ""message = str(message)# Build the conversation for HuggingFace routermessages = [{"role": "system", "content": level_to_prompt(user_level)}]# Normalize historyif history:for turn in history:# Gradio gives pairs: (user_msg, assistant_msg)if isinstance(turn, (list, tuple)) and len(turn) == 2:user_msg, assistant_msg = turn# normalize user messageif user_msg:if isinstance(user_msg, dict):user_msg = user_msg.get("content") or user_msg.get("text") or ""messages.append({"role": "user", "content": str(user_msg)})# normalize assistant messageif assistant_msg:if isinstance(assistant_msg, dict):assistant_msg = assistant_msg.get("content") or assistant_msg.get("text") or ""messages.append({"role": "assistant", "content": str(assistant_msg)})# Add new messagemessages.append({"role": "user", "content": message})reply = ""# --------------------------# STREAMING FROM HF ROUTER# --------------------------try:stream = client.chat.completions.create(model="HuggingFaceH4/zephyr-7b-beta",4 unmodified linestop_p=top_p,)for chunk in stream:# chunk is dict-like: {"choices":[{"delta":{"content":"..."}}]}delta = chunk.get("choices", [{}])[0].get("delta", {})token = delta.get("content", "")if token:reply += token# MUST yield only stringsyield replyexcept Exception as e:yield f"Désolé ! Une erreur s'est produite : {e}"# --------------------------# GRADIO APP# --------------------------css = """body {background: #f5f5f5;}"""with gr.Blocks(css=css) as demo:gr.Markdown("<h1 style='text-align:center;'>LE PROFESSEUR — French Tutor</h1>")with gr.Accordion("Settings", open=False):user_level = gr.Dropdown(["A1", "A2", "B1", "B2", "C1", "C2"],value="A1",label="Your French Level")max_tokens = gr.Slider(10, 2048, value=200, label="Max Tokens")temperature = gr.Slider(0.1, 2.0, value=0.7, label="Creativity")top_p = gr.Slider(0.1, 1.0, value=0.9, label="Top-p Sampling")gr.ChatInterface(fn=respond,additional_inputs=[user_level, max_tokens, temperature, top_p],type="messages")if __name__ == "__main__":demo.launch()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021034 unmodified lines108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153import gradio as grfrom huggingface_hub import InferenceClient# Background CSScss = """body {background-image: url('https://cdn-uploads.huggingface.co/production/uploads/67351c643fe51cb1aa28f2e5/YcsJnPk8HJvXiB5WkVmf1.jpeg');background-size: cover;background-position: center;background-repeat: no-repeat;}.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%;}"""# === PATCHED CLIENT ===# Uses the new unified HF router for OpenAI-like chat completionclient = InferenceClient(base_url="https://router.huggingface.co/v1")# 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.","A2": "You are a patient French tutor. Respond to the user's question clearly and simply.","B1": "You are a helpful French tutor. Use mostly French with minimal English when needed.","B2": "You are a French tutor. Respond primarily in French with concise, relevant explanations.","C1": "You are a native French tutor. Use fluent French and include brief cultural or historical notes when relevant.","C2": "You are a French language professor. Use sophisticated French with precise explanations.",}.get(level, "You are a helpful French tutor.")# === PATCHED CHAT HANDLER ===def respond(message, history, user_level, max_tokens, temperature, top_p):system_message = level_to_prompt(user_level)messages = [{"role": "system", "content": system_message}]# FIXED: Cleanly add history entriesif history:for h in history:if isinstance(h, dict):messages.append(h)messages.append({"role": "user", "content": message})response = ""try:stream = client.chat.completions.create(model="HuggingFaceH4/zephyr-7b-beta",4 unmodified linestop_p=top_p,)for msg in stream:delta = msg.get("choices", [{}])[0].get("delta", {})token = delta.get("content", "")if token:response += tokenyield responseexcept Exception as e:yield f"Désolé! There was an error: {str(e)}"# === GRADIO INTERFACE ===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, 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()
app.py+118-93