CCockrum commited on
Commit
569604f
·
verified ·
1 Parent(s): cd9d03f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +71 -88
app.py CHANGED
@@ -1,12 +1,14 @@
1
  # app.py
2
 
 
 
3
  import os
4
- from typing import Any, Dict, Iterable, List
5
 
6
  import gradio as gr
7
- from huggingface_hub import InferenceClient, hf_api
8
 
9
- # ---- Background CSS (kept from your snippet) ----
10
  css = """
11
  body {
12
  background-image: url('https://cdn-uploads.huggingface.co/production/uploads/67351c643fe51cb1aa28f2e5/YcsJnPk8HJvXiB5WkVmf1.jpeg');
@@ -14,65 +16,18 @@ body {
14
  background-position: center;
15
  background-repeat: no-repeat;
16
  }
17
- .gradio-container {
18
- display: flex;
19
- flex-direction: column;
20
- justify-content: center;
21
- min-height: 100vh;
22
- padding-top: 2rem;
23
- padding-bottom: 2rem;
24
- }
25
- #title-container {
26
- background-color: rgba(255, 255, 255, 0.85);
27
- border-radius: 16px;
28
- padding: 1.5rem 2rem;
29
- margin: 2rem 0;
30
- width: fit-content;
31
- max-width: 500px;
32
- text-align: left;
33
- box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
34
- margin-left: 0rem;
35
- }
36
- #title-container h1 {
37
- color: #222 !important;
38
- font-size: 4rem;
39
- font-family: 'Noto Sans JP', sans-serif;
40
- margin: 0;
41
- }
42
- #title-container .subtitle {
43
- font-size: 1.1rem;
44
- font-family: 'Noto Sans', sans-serif;
45
- color: #222 !important;
46
- margin-top: 0.5rem;
47
- margin-bottom: 0;
48
- width: 100%;
49
- display: block;
50
- }
51
- #chat-panel {
52
- background-color: rgba(255, 255, 255, 0.85);
53
- padding: 2rem;
54
- border-radius: 12px;
55
- justify-content: center;
56
- width: 100%;
57
- max-width: 700px;
58
- height: 70vh;
59
- box-shadow: 0 0 12px rgba(0, 0, 0, 0.3);
60
- overflow-y: auto;
61
- }
62
- .gradio-container .chatbot h1 {
63
- color: var(--custom-title-color) !important;
64
- font-family: 'Noto Sans', serif !important;
65
- font-size: 5rem !important;
66
- font-weight: bold !important;
67
- text-align: center !important;
68
- margin-bottom: 1.5rem !important;
69
- width: 100%;
70
- }
71
  """
72
 
73
- MODEL_ID = "HuggingFaceH4/zephyr-7b-beta" # switch to a public Inference API-enabled model if this is gated
 
74
 
75
- # ---- Prompting ----
76
  def level_to_prompt(level: str) -> str:
77
  return {
78
  "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.",
@@ -83,28 +38,56 @@ def level_to_prompt(level: str) -> str:
83
  "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.",
84
  }.get(level, "You are a helpful French tutor.")
85
 
86
- # ---- HF Client ----
87
- def create_client(token: str | None) -> InferenceClient:
88
- # WHY: re-create per call so users can supply token at runtime (avoids global state & 401s).
 
89
  tok = token or os.getenv("HUGGINGFACEHUB_API_TOKEN") or os.getenv("HF_TOKEN")
90
  return InferenceClient(model=MODEL_ID, token=tok)
91
 
92
- # ---- Message shaping ----
93
- def normalize_messages(
94
- gradio_messages: List[Dict[str, str]], system_text: str
95
- ) -> List[Dict[str, str]]:
96
- # Gradio (type="messages") sends full chat as list of {role, content}.
97
- msgs: List[Dict[str, str]] = []
98
- # Drop any incoming system prompts; we control the single system message.
99
- for m in gradio_messages:
100
- if m.get("role") != "system":
101
- msgs.append({"role": m.get("role", "user"), "content": m.get("content", "")})
102
- return [{"role": "system", "content": system_text}, *msgs]
103
-
104
- # ---- Streaming call wrapper ----
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
105
  def stream_chat(
106
  client: InferenceClient,
107
- messages: List[Dict[str, str]],
108
  *,
109
  max_tokens: int,
110
  temperature: float,
@@ -112,10 +95,9 @@ def stream_chat(
112
  ) -> Iterable[str]:
113
  buf = ""
114
  try:
115
- # Some servers return events where delta.content can be None (role/tool changes) → guard it.
116
  for ev in client.chat_completion(
117
  messages=messages,
118
- max_tokens=max_tokens,
119
  temperature=temperature,
120
  top_p=top_p,
121
  stream=True,
@@ -126,27 +108,28 @@ def stream_chat(
126
  buf += piece
127
  yield buf
128
  except Exception as e:
129
- # WHY: Surface common auth hint for 401 to reduce confusion.
130
  msg = str(e)
131
  if "401" in msg or "Unauthorized" in msg:
132
  yield "Désolé ! Auth error (401). Provide a valid Hugging Face token in Advanced Settings or set HUGGINGFACEHUB_API_TOKEN."
133
  else:
134
  yield f"Désolé ! An error occurred: {msg}"
135
 
136
- # ---- Gradio callback (matches `type="messages"` signature) ----
 
137
  def respond(
138
- messages: List[Dict[str, str]],
 
139
  user_level: str,
140
  max_tokens: int,
141
  temperature: float,
142
  top_p: float,
143
- hf_token: str | None,
144
  ):
145
  system_message = level_to_prompt(user_level)
146
- msgs = normalize_messages(messages, system_message)
147
  client = create_client(hf_token)
148
 
149
- # Enforce bounds defensively
150
  max_tokens = int(max(1, min(int(max_tokens), 4096)))
151
  temperature = float(max(0.0, min(float(temperature), 4.0)))
152
  top_p = float(max(0.0, min(float(top_p), 1.0)))
@@ -159,7 +142,8 @@ def respond(
159
  top_p=top_p,
160
  )
161
 
162
- # ---- UI ----
 
163
  with gr.Blocks(css=css) as demo:
164
  gr.HTML(
165
  """
@@ -187,11 +171,10 @@ with gr.Blocks(css=css) as demo:
187
  )
188
 
189
  gr.ChatInterface(
190
- fn=respond,
191
  additional_inputs=[user_level, max_tokens, temperature, top_p, hf_token],
192
- type="messages", # IMPORTANT: pairs with respond(messages, ...)
193
  )
194
 
195
  if __name__ == "__main__":
196
- # WHY: show URL in logs; enable queues for streaming concurrency.
197
  demo.launch(server_name="0.0.0.0", server_port=7860, share=False)
 
1
  # app.py
2
 
3
+ from __future__ import annotations
4
+
5
  import os
6
+ from typing import Any, Dict, Iterable, List, Optional, Sequence, Tuple, Union
7
 
8
  import gradio as gr
9
+ from huggingface_hub import InferenceClient
10
 
11
+ # -------------------- CSS --------------------
12
  css = """
13
  body {
14
  background-image: url('https://cdn-uploads.huggingface.co/production/uploads/67351c643fe51cb1aa28f2e5/YcsJnPk8HJvXiB5WkVmf1.jpeg');
 
16
  background-position: center;
17
  background-repeat: no-repeat;
18
  }
19
+ .gradio-container { display: flex; flex-direction: column; justify-content: center; min-height: 100vh; padding-top: 2rem; padding-bottom: 2rem; }
20
+ #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; }
21
+ #title-container h1 { color: #222 !important; font-size: 4rem; font-family: 'Noto Sans JP', sans-serif; margin: 0; }
22
+ #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; }
23
+ #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; }
24
+ .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%; }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
  """
26
 
27
+ MODEL_ID = "HuggingFaceH4/zephyr-7b-beta" # ensure your HF token has access if gated
28
+
29
 
30
+ # -------------------- Prompting --------------------
31
  def level_to_prompt(level: str) -> str:
32
  return {
33
  "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.",
 
38
  "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.",
39
  }.get(level, "You are a helpful French tutor.")
40
 
41
+
42
+ # -------------------- HF Client --------------------
43
+ def create_client(token: Optional[str]) -> InferenceClient:
44
+ # why: allow runtime token; avoids hard-failing with 401 when model is gated
45
  tok = token or os.getenv("HUGGINGFACEHUB_API_TOKEN") or os.getenv("HF_TOKEN")
46
  return InferenceClient(model=MODEL_ID, token=tok)
47
 
48
+
49
+ # -------------------- Message shaping --------------------
50
+ GradioMessage = Dict[str, str]
51
+ HistoryItem = Union[Tuple[str, str], GradioMessage]
52
+ History = Optional[Sequence[HistoryItem]]
53
+
54
+ def _history_to_messages(history: History) -> List[GradioMessage]:
55
+ msgs: List[GradioMessage] = []
56
+ if not history:
57
+ return msgs
58
+ # Accept either tuples (user, assistant) or already-shaped dicts
59
+ for item in history:
60
+ if isinstance(item, tuple) and len(item) == 2:
61
+ u, a = item
62
+ if u:
63
+ msgs.append({"role": "user", "content": u})
64
+ if a:
65
+ msgs.append({"role": "assistant", "content": a})
66
+ elif isinstance(item, dict) and "role" in item and "content" in item:
67
+ if item["role"] != "system":
68
+ msgs.append({"role": item["role"], "content": item["content"]})
69
+ return msgs
70
+
71
+ def coerce_to_messages(
72
+ message: Union[str, List[GradioMessage]],
73
+ history: History,
74
+ system_text: str,
75
+ ) -> List[GradioMessage]:
76
+ # Handle both call modes: (str, history) and (messages_list, None)
77
+ if isinstance(message, list) and all(isinstance(m, dict) and "role" in m for m in message):
78
+ user_msgs = [m for m in message if m.get("role") != "system"]
79
+ return [{"role": "system", "content": system_text}, *user_msgs]
80
+ # Default: current user message + legacy history tuples/dicts
81
+ msgs = [{"role": "system", "content": system_text}, *_history_to_messages(history)]
82
+ if isinstance(message, str) and message:
83
+ msgs.append({"role": "user", "content": message})
84
+ return msgs
85
+
86
+
87
+ # -------------------- Streaming wrapper --------------------
88
  def stream_chat(
89
  client: InferenceClient,
90
+ messages: List[GradioMessage],
91
  *,
92
  max_tokens: int,
93
  temperature: float,
 
95
  ) -> Iterable[str]:
96
  buf = ""
97
  try:
 
98
  for ev in client.chat_completion(
99
  messages=messages,
100
+ max_tokens=max_tokens, # if your server expects max_new_tokens, rename here
101
  temperature=temperature,
102
  top_p=top_p,
103
  stream=True,
 
108
  buf += piece
109
  yield buf
110
  except Exception as e:
 
111
  msg = str(e)
112
  if "401" in msg or "Unauthorized" in msg:
113
  yield "Désolé ! Auth error (401). Provide a valid Hugging Face token in Advanced Settings or set HUGGINGFACEHUB_API_TOKEN."
114
  else:
115
  yield f"Désolé ! An error occurred: {msg}"
116
 
117
+
118
+ # -------------------- Gradio callback --------------------
119
  def respond(
120
+ message: Union[str, List[GradioMessage]],
121
+ history: History,
122
  user_level: str,
123
  max_tokens: int,
124
  temperature: float,
125
  top_p: float,
126
+ hf_token: Optional[str],
127
  ):
128
  system_message = level_to_prompt(user_level)
129
+ msgs = coerce_to_messages(message, history, system_message)
130
  client = create_client(hf_token)
131
 
132
+ # defensive bounds
133
  max_tokens = int(max(1, min(int(max_tokens), 4096)))
134
  temperature = float(max(0.0, min(float(temperature), 4.0)))
135
  top_p = float(max(0.0, min(float(top_p), 1.0)))
 
142
  top_p=top_p,
143
  )
144
 
145
+
146
+ # -------------------- UI --------------------
147
  with gr.Blocks(css=css) as demo:
148
  gr.HTML(
149
  """
 
171
  )
172
 
173
  gr.ChatInterface(
174
+ fn=respond, # expects (message, history, *inputs)
175
  additional_inputs=[user_level, max_tokens, temperature, top_p, hf_token],
176
+ type="messages", # still fine; we normalize both call shapes
177
  )
178
 
179
  if __name__ == "__main__":
 
180
  demo.launch(server_name="0.0.0.0", server_port=7860, share=False)