Spaces:
Runtime error
Runtime error
Update app.py
Browse files1234567891011121 unmodified line14151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677784 unmodified lines83848586878889909192939495969798991001011021031041051061071081091101 unmodified line1121131141151161171181191201214 unmodified lines1261271281291301311321331341351361371381391401411421431441451461471481491501511526 unmodified lines15916016116216316416521 unmodified lines187188189190191192193194195196197# 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');1 unmodified linebackground-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%;}"""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.",4 unmodified lines"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,1 unmodified line) -> 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,4 unmodified linesbuf += 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)))6 unmodified linestop_p=top_p,)# ---- UI ----with gr.Blocks(css=css) as demo:gr.HTML("""21 unmodified lines)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)12345678910111213141 unmodified line1617181920212223242526272829303132334 unmodified lines38394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192931 unmodified line95969798991001011021034 unmodified lines1081091101111121131141151161171181191201211221231241251261271281291301311321331341356 unmodified lines14214314414514614714814921 unmodified lines171172173174175176177178179180# app.pyfrom __future__ import annotationsimport osfrom typing import Any, Dict, Iterable, List, Optional, Sequence, Tuple, Unionimport gradio as grfrom huggingface_hub import InferenceClient# -------------------- CSS --------------------css = """body {background-image: url('https://cdn-uploads.huggingface.co/production/uploads/67351c643fe51cb1aa28f2e5/YcsJnPk8HJvXiB5WkVmf1.jpeg');1 unmodified linebackground-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%; }"""MODEL_ID = "HuggingFaceH4/zephyr-7b-beta" # ensure your HF token has access if 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.",4 unmodified lines"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: Optional[str]) -> InferenceClient:# why: allow runtime token; avoids hard-failing with 401 when model is gatedtok = token or os.getenv("HUGGINGFACEHUB_API_TOKEN") or os.getenv("HF_TOKEN")return InferenceClient(model=MODEL_ID, token=tok)# -------------------- Message shaping --------------------GradioMessage = Dict[str, str]HistoryItem = Union[Tuple[str, str], GradioMessage]History = Optional[Sequence[HistoryItem]]def _history_to_messages(history: History) -> List[GradioMessage]:msgs: List[GradioMessage] = []if not history:return msgs# Accept either tuples (user, assistant) or already-shaped dictsfor 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]:# Handle both call modes: (str, history) and (messages_list, None)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]# Default: current user message + legacy history tuples/dictsmsgs = [{"role": "system", "content": system_text}, *_history_to_messages(history)]if isinstance(message, str) and message:msgs.append({"role": "user", "content": message})return msgs# -------------------- Streaming wrapper --------------------def stream_chat(client: InferenceClient,messages: List[GradioMessage],*,max_tokens: int,temperature: float,1 unmodified line) -> Iterable[str]:buf = ""try:for ev in client.chat_completion(messages=messages,max_tokens=max_tokens, # if your server expects max_new_tokens, rename heretemperature=temperature,top_p=top_p,stream=True,4 unmodified linesbuf += pieceyield bufexcept Exception as e: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 --------------------def respond(message: Union[str, List[GradioMessage]],history: History,user_level: str,max_tokens: int,temperature: float,top_p: float,hf_token: Optional[str],):system_message = level_to_prompt(user_level)msgs = coerce_to_messages(message, history, system_message)client = create_client(hf_token)# defensive boundsmax_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)))6 unmodified linestop_p=top_p,)# -------------------- UI --------------------with gr.Blocks(css=css) as demo:gr.HTML("""21 unmodified lines)gr.ChatInterface(fn=respond, # expects (message, history, *inputs)additional_inputs=[user_level, max_tokens, temperature, top_p, hf_token],type="messages", # still fine; we normalize both call shapes)if __name__ == "__main__":demo.launch(server_name="0.0.0.0", server_port=7860, share=False)
app.py+71-88