Mel Seto commited on
Commit
f162916
·
1 Parent(s): 8f030ee

adjust app.py formatting

Browse files
Files changed (1) hide show
  1. app.py +44 -39
app.py CHANGED
@@ -1,8 +1,11 @@
1
- import gradio as gr
2
  import os
 
 
3
  from dotenv import load_dotenv
4
  from huggingface_hub import InferenceClient
5
 
 
 
6
  # ======================
7
  # Config
8
  # ======================
@@ -14,90 +17,92 @@ USE_MOCK = False # ✅ Toggle between mock and real API
14
  # ======================
15
  # Instantiate client (if not mocking)
16
  # ======================
17
- client = None
18
  if not USE_MOCK:
19
- client = InferenceClient(
20
- provider="cerebras",
21
- model=MODEL,
22
- api_key=os.environ["HF_TOKEN"]
23
  )
24
 
 
25
  # ======================
26
  # Mock function for UI testing
27
  # ======================
28
- def generate_idiom_mock(situation: str):
29
  idiom = "对症下药"
30
- explanation = "duì zhèng xià yào<br><br>To prescribe the right medicine; to take the right approach to a problem."
 
31
  return idiom, explanation
32
 
 
33
  # ======================
34
  # Real API function
35
  # ======================
36
- def generate_idiom(situation: str, client):
37
- prompt = f"""
38
- You are a wise assistant. Given a situation, respond with exactly:
39
- 1. A traditional Chinese idiom (which includes 成語、俗語、諺語), that conveys the idea of the given situation.
40
- 2. Its pinyin
41
- 3. Its literal English translation
42
- 4. Explain idiom. Keep explanation to 2-3 concise sentences.
 
 
43
 
44
  Format:
45
  Idiom
46
- Pinyin
47
  Literal translation
48
  Explanation
49
 
50
  Situation: {situation}
51
- Answer:
52
- """
53
- response = client.chat.completions.create(
54
- model=MODEL,
55
- messages=[{"role": "user", "content": prompt}],
56
- max_tokens=150
57
  )
58
 
59
  generated_text = response.choices[0].message.content.strip()
60
  lines = [line.strip() for line in generated_text.split("\n") if line.strip()]
61
 
 
 
 
62
  if len(lines) >= 3:
63
- idiom = lines[0]
64
- pinyin = lines[1]
65
- translation = lines[2]
66
- meaning = " ".join(lines[3:])
67
- explanation = f"{pinyin}<br><br>{translation}<br><br>{meaning}"
68
  else:
69
- idiom = generated_text
70
- explanation = ""
71
 
72
  return idiom, explanation
73
 
 
74
  # ======================
75
  # UI Wrapper
76
  # ======================
77
  def update_ui(situation):
78
  if USE_MOCK:
79
- idiom, explanation = generate_idiom_mock(situation)
80
  else:
81
- idiom, explanation = generate_idiom(situation, client)
82
 
83
  return (
84
  f"<div class='idiom-output'>{idiom}</div>",
85
- f"<div class='explanation-output'>{explanation}</div>"
86
  )
87
 
 
88
  # ======================
89
  # Launch app
90
  # ======================
91
  def launch_app():
92
  with gr.Blocks(css="style.css") as demo:
93
- gr.Markdown("# 🎋 Chinese Idioms Finder")
94
 
95
  with gr.Row():
96
  with gr.Column():
97
  situation = gr.Textbox(
98
  label="Enter a situation",
99
  lines=2,
100
- placeholder="e.g., When facing a big challenge"
101
  )
102
  generate_btn = gr.Button("✨ Find Idiom")
103
 
@@ -108,22 +113,22 @@ def launch_app():
108
  ["When someone helps you in a time of need"],
109
  ["When you need to stay calm under pressure"],
110
  ["When teamwork is important to succeed"],
111
- ["When rushing leads to mistakes"]
112
  ],
113
- inputs=situation
114
  )
115
 
116
  with gr.Column():
117
  idiom_output = gr.HTML(label="Idiom")
118
  explanation_output = gr.HTML(label="Explanation")
119
 
 
120
  generate_btn.click(
121
- fn=update_ui,
122
- inputs=situation,
123
- outputs=[idiom_output, explanation_output]
124
  )
125
 
126
  demo.launch()
127
 
 
128
  if __name__ == "__main__":
129
  launch_app()
 
 
1
  import os
2
+
3
+ import gradio as gr
4
  from dotenv import load_dotenv
5
  from huggingface_hub import InferenceClient
6
 
7
+ from utils.utils import get_pinyin
8
+
9
  # ======================
10
  # Config
11
  # ======================
 
17
  # ======================
18
  # Instantiate client (if not mocking)
19
  # ======================
20
+ CLIENT = None
21
  if not USE_MOCK:
22
+ CLIENT = InferenceClient(
23
+ provider="cerebras", model=MODEL, api_key=os.environ["HF_TOKEN"]
 
 
24
  )
25
 
26
+
27
  # ======================
28
  # Mock function for UI testing
29
  # ======================
30
+ def generate_idiom_mock():
31
  idiom = "对症下药"
32
+ explanation = """duì zhèng xià yào<br><br>
33
+ To prescribe the right medicine; to take the right approach to a problem."""
34
  return idiom, explanation
35
 
36
+
37
  # ======================
38
  # Real API function
39
  # ======================
40
+
41
+
42
+ def generate_idiom(situation: str):
43
+ prompt = f"""You are a wise assistant. Given a situation, respond with exactly:
44
+ 1. A Chinese idiom (includes 成語、俗語、諺語),
45
+ written in simplified Chinese characters,
46
+ that conveys the idea of the given situation.
47
+ 2. Its literal English translation
48
+ 3. Explain idiom. Keep explanation to 2-3 concise sentences.
49
 
50
  Format:
51
  Idiom
 
52
  Literal translation
53
  Explanation
54
 
55
  Situation: {situation}
56
+ Answer:"""
57
+
58
+ response = CLIENT.chat.completions.create(
59
+ model=MODEL, messages=[{"role": "user", "content": prompt}], max_tokens=150
 
 
60
  )
61
 
62
  generated_text = response.choices[0].message.content.strip()
63
  lines = [line.strip() for line in generated_text.split("\n") if line.strip()]
64
 
65
+ idiom = lines[0] if lines else generated_text
66
+ pinyin_text = get_pinyin(idiom)
67
+
68
  if len(lines) >= 3:
69
+ translation = lines[1]
70
+ meaning = " ".join(lines[2:])
71
+ explanation = f"{pinyin_text}<br><br>{translation}<br><br>{meaning}"
 
 
72
  else:
73
+ explanation = f"{pinyin_text}<br><br>{' '.join(lines[1:])}"
 
74
 
75
  return idiom, explanation
76
 
77
+
78
  # ======================
79
  # UI Wrapper
80
  # ======================
81
  def update_ui(situation):
82
  if USE_MOCK:
83
+ idiom, explanation = generate_idiom_mock()
84
  else:
85
+ idiom, explanation = generate_idiom(situation)
86
 
87
  return (
88
  f"<div class='idiom-output'>{idiom}</div>",
89
+ f"<div class='explanation-output'>{explanation}</div>",
90
  )
91
 
92
+
93
  # ======================
94
  # Launch app
95
  # ======================
96
  def launch_app():
97
  with gr.Blocks(css="style.css") as demo:
98
+ gr.Markdown("# 🎋 Chinese Idiom Finder")
99
 
100
  with gr.Row():
101
  with gr.Column():
102
  situation = gr.Textbox(
103
  label="Enter a situation",
104
  lines=2,
105
+ placeholder="e.g., When facing a big challenge",
106
  )
107
  generate_btn = gr.Button("✨ Find Idiom")
108
 
 
113
  ["When someone helps you in a time of need"],
114
  ["When you need to stay calm under pressure"],
115
  ["When teamwork is important to succeed"],
116
+ ["When rushing leads to mistakes"],
117
  ],
118
+ inputs=situation,
119
  )
120
 
121
  with gr.Column():
122
  idiom_output = gr.HTML(label="Idiom")
123
  explanation_output = gr.HTML(label="Explanation")
124
 
125
+ # pylint: disable=no-member
126
  generate_btn.click(
127
+ fn=update_ui, inputs=situation, outputs=[idiom_output, explanation_output]
 
 
128
  )
129
 
130
  demo.launch()
131
 
132
+
133
  if __name__ == "__main__":
134
  launch_app()