CCockrum commited on
Commit
c3ba9b1
·
verified ·
1 Parent(s): 4c2ff2c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +118 -93
app.py CHANGED
@@ -1,76 +1,103 @@
1
  import gradio as gr
2
  from huggingface_hub import InferenceClient
3
 
4
- # --------------------------
5
- # NEW: HF Router Client
6
- # --------------------------
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
  client = InferenceClient(
8
- base_url="https://router.huggingface.co/v1" # OpenAI-compatible API
9
  )
10
 
11
- # --------------------------
12
- # Tutor Levels
13
- # --------------------------
14
  def level_to_prompt(level):
15
- prompts = {
16
- "A1": "You are a friendly French tutor. Use simple French, short sentences, and explain difficult words in English.",
17
- "A2": "You are a patient French tutor. Use simple French. Give short explanations in English when needed.",
18
- "B1": "You are a helpful French tutor. Use mostly French, with short English explanations only when truly necessary.",
19
- "B2": "You are a French tutor. Respond primarily in French with clear, concise explanations.",
20
- "C1": "You are a native French tutor. Respond in fluent French with occasional linguistic or cultural notes.",
21
- "C2": "You are a French language professor. Use sophisticated French with precise grammar explanations.",
22
- }
23
- return prompts.get(level, prompts["A1"])
24
-
25
-
26
- # --------------------------
27
- # CLEAN, SAFE CHAT HANDLER
28
- # --------------------------
29
  def respond(message, history, user_level, max_tokens, temperature, top_p):
30
- """
31
- Gradio's ChatInterface will trigger 'dict.strip' errors if anything
32
- except a string is returned. This handler forces all history and message
33
- fields to clean strings and always yields strings.
34
- """
35
-
36
- # Ensure user message is a string
37
- if isinstance(message, dict):
38
- # Gradio sometimes passes dicts
39
- message = message.get("content") or message.get("text") or message.get("prompt") or ""
40
- message = str(message)
41
-
42
- # Build the conversation for HuggingFace router
43
- messages = [
44
- {"role": "system", "content": level_to_prompt(user_level)}
45
- ]
46
-
47
- # Normalize history
48
  if history:
49
- for turn in history:
50
- # Gradio gives pairs: (user_msg, assistant_msg)
51
- if isinstance(turn, (list, tuple)) and len(turn) == 2:
52
- user_msg, assistant_msg = turn
53
-
54
- # normalize user message
55
- if user_msg:
56
- if isinstance(user_msg, dict):
57
- user_msg = user_msg.get("content") or user_msg.get("text") or ""
58
- messages.append({"role": "user", "content": str(user_msg)})
59
-
60
- # normalize assistant message
61
- if assistant_msg:
62
- if isinstance(assistant_msg, dict):
63
- assistant_msg = assistant_msg.get("content") or assistant_msg.get("text") or ""
64
- messages.append({"role": "assistant", "content": str(assistant_msg)})
65
-
66
- # Add new message
67
  messages.append({"role": "user", "content": message})
68
 
69
- reply = ""
70
 
71
- # --------------------------
72
- # STREAMING FROM HF ROUTER
73
- # --------------------------
74
  try:
75
  stream = client.chat.completions.create(
76
  model="HuggingFaceH4/zephyr-7b-beta",
@@ -81,48 +108,46 @@ def respond(message, history, user_level, max_tokens, temperature, top_p):
81
  top_p=top_p,
82
  )
83
 
84
- for chunk in stream:
85
- # chunk is dict-like: {"choices":[{"delta":{"content":"..."}}]}
86
- delta = chunk.get("choices", [{}])[0].get("delta", {})
87
  token = delta.get("content", "")
88
 
89
  if token:
90
- reply += token
91
 
92
- # MUST yield only strings
93
- yield reply
94
 
95
  except Exception as e:
96
- yield f"Désolé ! Une erreur s'est produite : {e}"
97
 
98
 
99
- # --------------------------
100
- # GRADIO APP
101
- # --------------------------
102
- css = """
103
- body {
104
- background: #f5f5f5;
105
- }
106
- """
107
 
 
108
  with gr.Blocks(css=css) as demo:
109
- gr.Markdown("<h1 style='text-align:center;'>LE PROFESSEUR — French Tutor</h1>")
110
-
111
- with gr.Accordion("Settings", open=False):
112
- user_level = gr.Dropdown(
113
- ["A1", "A2", "B1", "B2", "C1", "C2"],
114
- value="A1",
115
- label="Your French Level"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
116
  )
117
- max_tokens = gr.Slider(10, 2048, value=200, label="Max Tokens")
118
- temperature = gr.Slider(0.1, 2.0, value=0.7, label="Creativity")
119
- top_p = gr.Slider(0.1, 1.0, value=0.9, label="Top-p Sampling")
120
-
121
- gr.ChatInterface(
122
- fn=respond,
123
- additional_inputs=[user_level, max_tokens, temperature, top_p],
124
- type="messages"
125
- )
126
 
127
  if __name__ == "__main__":
128
- demo.launch()
 
1
  import gradio as gr
2
  from huggingface_hub import InferenceClient
3
 
4
+ # Background CSS
5
+ css = """
6
+ body {
7
+ background-image: url('https://cdn-uploads.huggingface.co/production/uploads/67351c643fe51cb1aa28f2e5/YcsJnPk8HJvXiB5WkVmf1.jpeg');
8
+ background-size: cover;
9
+ background-position: center;
10
+ background-repeat: no-repeat;
11
+ }
12
+ .gradio-container {
13
+ display: flex;
14
+ flex-direction: column;
15
+ justify-content: center;
16
+ min-height: 100vh;
17
+ padding-top: 2rem;
18
+ padding-bottom: 2rem;
19
+ }
20
+ #title-container {
21
+ background-color: rgba(255, 255, 255, 0.85);
22
+ border-radius: 16px;
23
+ padding: 1.5rem 2rem;
24
+ margin: 2rem 0;
25
+ width: fit-content;
26
+ max-width: 500px;
27
+ text-align: left;
28
+ box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
29
+ margin-left: 0rem;
30
+ }
31
+ #title-container h1 {
32
+ color: #222 !important;
33
+ font-size: 4rem;
34
+ font-family: 'Noto Sans JP', sans-serif;
35
+ margin: 0;
36
+ }
37
+ #title-container .subtitle {
38
+ font-size: 1.1rem;
39
+ font-family: 'Noto Sans', sans-serif;
40
+ color: #222 !important;
41
+ margin-top: 0.5rem;
42
+ margin-bottom: 0;
43
+ width: 100%;
44
+ display: block;
45
+ }
46
+ #chat-panel {
47
+ background-color: rgba(255, 255, 255, 0.85);
48
+ padding: 2rem;
49
+ border-radius: 12px;
50
+ justify-content: center;
51
+ width: 100%;
52
+ max-width: 700px;
53
+ height: 70vh;
54
+ box-shadow: 0 0 12px rgba(0, 0, 0, 0.3);
55
+ overflow-y: auto;
56
+ }
57
+ .gradio-container .chatbot h1 {
58
+ color: var(--custom-title-color) !important;
59
+ font-family: 'Noto Sans', serif !important;
60
+ font-size: 5rem !important;
61
+ font-weight: bold !important;
62
+ text-align: center !important;
63
+ margin-bottom: 1.5rem !important;
64
+ width: 100%;
65
+ }
66
+ """
67
+
68
+ # === PATCHED CLIENT ===
69
+ # Uses the new unified HF router for OpenAI-like chat completion
70
  client = InferenceClient(
71
+ base_url="https://router.huggingface.co/v1"
72
  )
73
 
74
+ # Level prompt selector
 
 
75
  def level_to_prompt(level):
76
+ return {
77
+ "A1": "You are a friendly French tutor. Focus on the user's specific question. Use simple French and explain in English.",
78
+ "A2": "You are a patient French tutor. Respond to the user's question clearly and simply.",
79
+ "B1": "You are a helpful French tutor. Use mostly French with minimal English when needed.",
80
+ "B2": "You are a French tutor. Respond primarily in French with concise, relevant explanations.",
81
+ "C1": "You are a native French tutor. Use fluent French and include brief cultural or historical notes when relevant.",
82
+ "C2": "You are a French language professor. Use sophisticated French with precise explanations.",
83
+ }.get(level, "You are a helpful French tutor.")
84
+
85
+
86
+ # === PATCHED CHAT HANDLER ===
 
 
 
87
  def respond(message, history, user_level, max_tokens, temperature, top_p):
88
+ system_message = level_to_prompt(user_level)
89
+ messages = [{"role": "system", "content": system_message}]
90
+
91
+ # FIXED: Cleanly add history entries
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92
  if history:
93
+ for h in history:
94
+ if isinstance(h, dict):
95
+ messages.append(h)
96
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
97
  messages.append({"role": "user", "content": message})
98
 
99
+ response = ""
100
 
 
 
 
101
  try:
102
  stream = client.chat.completions.create(
103
  model="HuggingFaceH4/zephyr-7b-beta",
 
108
  top_p=top_p,
109
  )
110
 
111
+ for msg in stream:
112
+ delta = msg.get("choices", [{}])[0].get("delta", {})
 
113
  token = delta.get("content", "")
114
 
115
  if token:
116
+ response += token
117
 
118
+ yield response
 
119
 
120
  except Exception as e:
121
+ yield f"Désolé! There was an error: {str(e)}"
122
 
123
 
 
 
 
 
 
 
 
 
124
 
125
+ # === GRADIO INTERFACE ===
126
  with gr.Blocks(css=css) as demo:
127
+ gr.HTML("""
128
+ <div id="title-container">
129
+ <h1>LE PROFESSEUR</h1>
130
+ <p class="subtitle">French Tutor</p>
131
+ </div>
132
+ """)
133
+
134
+ with gr.Column(elem_id="chat-panel"):
135
+
136
+ with gr.Accordion("Advanced Settings", open=False):
137
+ user_level = gr.Dropdown(
138
+ choices=["A1", "A2", "B1", "B2", "C1", "C2"],
139
+ value="A1",
140
+ label="Your French Level (CEFR)"
141
+ )
142
+ max_tokens = gr.Slider(1, 2048, value=400, step=1, label="Response Length")
143
+ temperature = gr.Slider(0.1, 4.0, value=0.5, step=0.1, label="Creativity")
144
+ top_p = gr.Slider(0.1, 1.0, value=0.85, step=0.05, label="Dynamic Text Sampling")
145
+
146
+ gr.ChatInterface(
147
+ respond,
148
+ additional_inputs=[user_level, max_tokens, temperature, top_p],
149
+ type="messages"
150
  )
 
 
 
 
 
 
 
 
 
151
 
152
  if __name__ == "__main__":
153
+ demo.launch()