3morixd commited on
Commit
846419b
·
verified ·
1 Parent(s): e944a2f

Upload app.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. app.py +224 -0
app.py ADDED
@@ -0,0 +1,224 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Dispatch AI — Arabic Proverb Generator
3
+ Input: topic → Output: Arabic proverb in traditional style + English translation.
4
+ Uses Qwen2.5-7B via HF Inference API.
5
+ """
6
+
7
+ import os
8
+ import json
9
+ import gradio as gr
10
+ from huggingface_hub import InferenceClient
11
+
12
+ # --- Configuration -----------------------------------------------------------
13
+ HF_TOKEN = os.environ.get("HF_TOKEN", None)
14
+ MODEL_ID = "Qwen/Qwen2.5-7B-Instruct"
15
+
16
+ client = InferenceClient(model=MODEL_ID, token=HF_TOKEN)
17
+
18
+ BG_COLOR = "#0A0F1A"
19
+ ACCENT = "#1FE0E6"
20
+
21
+ # Preset topics
22
+ PRESET_TOPICS = [
23
+ "patience",
24
+ "knowledge",
25
+ "friendship",
26
+ "honesty",
27
+ "hard work",
28
+ "wisdom",
29
+ "family",
30
+ "courage",
31
+ "generosity",
32
+ "time",
33
+ "hope",
34
+ "unity",
35
+ "travel",
36
+ "mother",
37
+ "neighbor",
38
+ ]
39
+
40
+
41
+ def generate_proverb(topic, style):
42
+ """Generate an Arabic proverb using Qwen2.5-7B via HF Inference API."""
43
+ if not topic or not topic.strip():
44
+ topic = "wisdom"
45
+
46
+ style_instruction = {
47
+ "Classical": "in the style of classical Arabic literature, like ancient Bedouin wisdom",
48
+ "Poetic": "in a poetic, rhyming style with rhythm (saja')",
49
+ "Simple": "in simple, everyday Arabic that anyone can understand",
50
+ "Bedouin": "in the style of Bedouin desert wisdom, referencing desert life and nature",
51
+ "Royal": "in the style of royal court wisdom, grand and majestic",
52
+ }.get(style, "in the style of classical Arabic literature")
53
+
54
+ system_prompt = (
55
+ f"You are an expert in Arabic culture and literature. "
56
+ f"Generate a traditional Arabic proverb about '{topic}' {style_instruction}. "
57
+ f"Respond ONLY in valid JSON format with these exact keys:\n"
58
+ f'{{"arabic": "the proverb in Arabic", "english": "English translation", '
59
+ f'"transliteration": "Arabic in Latin script", "explanation": "brief explanation of meaning"}}'
60
+ )
61
+
62
+ try:
63
+ response = client.chat_completion(
64
+ messages=[
65
+ {"role": "system", "content": system_prompt},
66
+ {"role": "user", "content": f"Generate a proverb about: {topic}"},
67
+ ],
68
+ max_tokens=300,
69
+ temperature=0.8,
70
+ )
71
+ raw = response.choices[0].message.content.strip()
72
+
73
+ # Try to parse JSON
74
+ try:
75
+ # Extract JSON from response (may have markdown code blocks)
76
+ if "```json" in raw:
77
+ raw = raw.split("```json")[1].split("```")[0].strip()
78
+ elif "```" in raw:
79
+ raw = raw.split("```")[1].split("```")[0].strip()
80
+ data = json.loads(raw)
81
+ except (json.JSONDecodeError, IndexError):
82
+ # Fallback: use raw text as Arabic proverb
83
+ data = {
84
+ "arabic": raw,
85
+ "english": "(Translation unavailable)",
86
+ "transliteration": "",
87
+ "explanation": "",
88
+ }
89
+
90
+ arabic = data.get("arabic", "—")
91
+ english = data.get("english", "—")
92
+ transliteration = data.get("transliteration", "—")
93
+ explanation = data.get("explanation", "—")
94
+
95
+ result = f"""
96
+ ### 📜 Arabic Proverb
97
+
98
+ **{arabic}**
99
+
100
+ ---
101
+
102
+ ### 🌐 English Translation
103
+
104
+ *{english}*
105
+
106
+ ---
107
+
108
+ ### 🔤 Transliteration
109
+
110
+ {transliteration}
111
+
112
+ ---
113
+
114
+ ### 💡 Meaning
115
+
116
+ {explanation}
117
+
118
+ ---
119
+
120
+ *Topic: {topic} · Style: {style} · Model: {MODEL_ID}*
121
+ """
122
+ return result, "✅ Proverb generated!"
123
+
124
+ except Exception as e:
125
+ return f"❌ Error: {str(e)}", f"❌ Error: {str(e)}"
126
+
127
+
128
+ def generate_multiple_proverbs(topic, style, count):
129
+ """Generate multiple proverbs about a topic."""
130
+ results = []
131
+ n = int(count) if count else 3
132
+ for i in range(min(n, 5)):
133
+ result, status = generate_proverb(topic, style)
134
+ results.append(f"### Proverb {i+1}\n\n{result}\n\n---\n")
135
+ return "\n".join(results), "✅ Generated!"
136
+
137
+
138
+ # --- UI -----------------------------------------------------------------------
139
+ CSS = """
140
+ #dispatch-header h1 {
141
+ color: #FFFFFF; font-size: 2.2rem; margin: 0;
142
+ background: linear-gradient(90deg, #1FE0E6 0%, #FFFFFF 60%);
143
+ -webkit-background-clip: text; -webkit-text-fill-color: transparent;
144
+ }
145
+ #dispatch-header p { color: #1FE0E6; font-size: 1.05rem; margin: 6px 0 0 0; }
146
+ .dispatch-footer { text-align: center; color: #8A8F9C; font-size: 0.9rem; padding-top: 8px; }
147
+ """
148
+
149
+ with gr.Blocks(
150
+ title="Dispatch AI — Arabic Proverb Generator",
151
+ theme=gr.themes.Base(
152
+ primary_hue="cyan", secondary_hue="cyan", neutral_hue="slate",
153
+ font=[gr.themes.GoogleFont("Inter"), "ui-sans-serif", "system-ui"],
154
+ ).set(
155
+ body_background_fill="#0A0F1A", body_background_fill_dark="#0A0F1A",
156
+ body_text_color="#FFFFFF", body_text_color_dark="#FFFFFF",
157
+ block_background_fill="#0E1424", block_background_fill_dark="#0E1424",
158
+ block_border_color="#1FE0E6", block_border_width="1px",
159
+ block_label_text_color="#1FE0E6", block_title_text_color="#1FE0E6",
160
+ button_primary_background_fill="#1FE0E6", button_primary_background_fill_dark="#1FE0E6",
161
+ button_primary_text_color="#0A0F1A", button_primary_border_color="#1FE0E6",
162
+ input_background_fill="#0E1424", input_background_fill_dark="#0E1424",
163
+ input_border_color="#1FE0E6", input_border_width="1px",
164
+ ),
165
+ css=CSS,
166
+ ) as demo:
167
+ with gr.Column(elem_id="dispatch-header"):
168
+ gr.Markdown(
169
+ """
170
+ # Dispatch AI — Arabic Proverb Generator
171
+ Generate traditional Arabic proverbs + English translation · Qwen2.5-7B · Dispatch AI (FZE) · UAE
172
+ """
173
+ )
174
+
175
+ with gr.Row():
176
+ with gr.Column(scale=1):
177
+ topic_input = gr.Textbox(
178
+ label="Topic",
179
+ placeholder="e.g. patience, friendship, knowledge...",
180
+ value="patience",
181
+ lines=1,
182
+ )
183
+ style_select = gr.Radio(
184
+ ["Classical", "Poetic", "Simple", "Bedouin", "Royal"],
185
+ label="Style", value="Classical",
186
+ )
187
+ generate_btn = gr.Button("📜 Generate Proverb", variant="primary")
188
+ gr.Markdown("### Quick Topics")
189
+ topic_buttons = gr.Dataset(
190
+ label="Preset Topics",
191
+ components=[topic_input],
192
+ samples=[[t] for t in PRESET_TOPICS],
193
+ )
194
+ with gr.Accordion("Generate Multiple", open=False):
195
+ count_slider = gr.Slider(1, 5, value=3, step=1, label="Number of Proverbs")
196
+ multi_btn = gr.Button("📚 Generate Multiple Proverbs", variant="secondary")
197
+
198
+ with gr.Column(scale=2):
199
+ status_box = gr.Textbox(label="Status", interactive=False)
200
+ output_md = gr.Markdown()
201
+
202
+ # Events
203
+ generate_btn.click(
204
+ generate_proverb,
205
+ inputs=[topic_input, style_select],
206
+ outputs=[output_md, status_box],
207
+ )
208
+ multi_btn.click(
209
+ generate_multiple_proverbs,
210
+ inputs=[topic_input, style_select, count_slider],
211
+ outputs=[output_md, status_box],
212
+ )
213
+
214
+ gr.Markdown(
215
+ """
216
+ <div class="dispatch-footer">
217
+ © 2026 Dispatch AI (FZE) · UAE · License 10818 · Model: Qwen2.5-7B-Instruct via HF Inference API
218
+ </div>
219
+ """
220
+ )
221
+
222
+ if __name__ == "__main__":
223
+ demo.queue()
224
+ demo.launch()