File size: 7,343 Bytes
846419b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
"""
Dispatch AI — Arabic Proverb Generator
Input: topic → Output: Arabic proverb in traditional style + English translation.
Uses Qwen2.5-7B via HF Inference API.
"""

import os
import json
import gradio as gr
from huggingface_hub import InferenceClient

# --- Configuration -----------------------------------------------------------
HF_TOKEN = os.environ.get("HF_TOKEN", None)
MODEL_ID = "Qwen/Qwen2.5-7B-Instruct"

client = InferenceClient(model=MODEL_ID, token=HF_TOKEN)

BG_COLOR = "#0A0F1A"
ACCENT = "#1FE0E6"

# Preset topics
PRESET_TOPICS = [
    "patience",
    "knowledge",
    "friendship",
    "honesty",
    "hard work",
    "wisdom",
    "family",
    "courage",
    "generosity",
    "time",
    "hope",
    "unity",
    "travel",
    "mother",
    "neighbor",
]


def generate_proverb(topic, style):
    """Generate an Arabic proverb using Qwen2.5-7B via HF Inference API."""
    if not topic or not topic.strip():
        topic = "wisdom"

    style_instruction = {
        "Classical": "in the style of classical Arabic literature, like ancient Bedouin wisdom",
        "Poetic": "in a poetic, rhyming style with rhythm (saja')",
        "Simple": "in simple, everyday Arabic that anyone can understand",
        "Bedouin": "in the style of Bedouin desert wisdom, referencing desert life and nature",
        "Royal": "in the style of royal court wisdom, grand and majestic",
    }.get(style, "in the style of classical Arabic literature")

    system_prompt = (
        f"You are an expert in Arabic culture and literature. "
        f"Generate a traditional Arabic proverb about '{topic}' {style_instruction}. "
        f"Respond ONLY in valid JSON format with these exact keys:\n"
        f'{{"arabic": "the proverb in Arabic", "english": "English translation", '
        f'"transliteration": "Arabic in Latin script", "explanation": "brief explanation of meaning"}}'
    )

    try:
        response = client.chat_completion(
            messages=[
                {"role": "system", "content": system_prompt},
                {"role": "user", "content": f"Generate a proverb about: {topic}"},
            ],
            max_tokens=300,
            temperature=0.8,
        )
        raw = response.choices[0].message.content.strip()

        # Try to parse JSON
        try:
            # Extract JSON from response (may have markdown code blocks)
            if "```json" in raw:
                raw = raw.split("```json")[1].split("```")[0].strip()
            elif "```" in raw:
                raw = raw.split("```")[1].split("```")[0].strip()
            data = json.loads(raw)
        except (json.JSONDecodeError, IndexError):
            # Fallback: use raw text as Arabic proverb
            data = {
                "arabic": raw,
                "english": "(Translation unavailable)",
                "transliteration": "",
                "explanation": "",
            }

        arabic = data.get("arabic", "—")
        english = data.get("english", "—")
        transliteration = data.get("transliteration", "—")
        explanation = data.get("explanation", "—")

        result = f"""
### 📜 Arabic Proverb

**{arabic}**

---

### 🌐 English Translation

*{english}*

---

### 🔤 Transliteration

{transliteration}

---

### 💡 Meaning

{explanation}

---

*Topic: {topic} · Style: {style} · Model: {MODEL_ID}*
"""
        return result, "✅ Proverb generated!"

    except Exception as e:
        return f"❌ Error: {str(e)}", f"❌ Error: {str(e)}"


def generate_multiple_proverbs(topic, style, count):
    """Generate multiple proverbs about a topic."""
    results = []
    n = int(count) if count else 3
    for i in range(min(n, 5)):
        result, status = generate_proverb(topic, style)
        results.append(f"### Proverb {i+1}\n\n{result}\n\n---\n")
    return "\n".join(results), "✅ Generated!"


# --- UI -----------------------------------------------------------------------
CSS = """
#dispatch-header h1 {
    color: #FFFFFF; font-size: 2.2rem; margin: 0;
    background: linear-gradient(90deg, #1FE0E6 0%, #FFFFFF 60%);
    -webkit-background-clip: text; -webkit-text-fill-color: transparent;
}
#dispatch-header p { color: #1FE0E6; font-size: 1.05rem; margin: 6px 0 0 0; }
.dispatch-footer { text-align: center; color: #8A8F9C; font-size: 0.9rem; padding-top: 8px; }
"""

with gr.Blocks(
    title="Dispatch AI — Arabic Proverb Generator",
    theme=gr.themes.Base(
        primary_hue="cyan", secondary_hue="cyan", neutral_hue="slate",
        font=[gr.themes.GoogleFont("Inter"), "ui-sans-serif", "system-ui"],
    ).set(
        body_background_fill="#0A0F1A", body_background_fill_dark="#0A0F1A",
        body_text_color="#FFFFFF", body_text_color_dark="#FFFFFF",
        block_background_fill="#0E1424", block_background_fill_dark="#0E1424",
        block_border_color="#1FE0E6", block_border_width="1px",
        block_label_text_color="#1FE0E6", block_title_text_color="#1FE0E6",
        button_primary_background_fill="#1FE0E6", button_primary_background_fill_dark="#1FE0E6",
        button_primary_text_color="#0A0F1A", button_primary_border_color="#1FE0E6",
        input_background_fill="#0E1424", input_background_fill_dark="#0E1424",
        input_border_color="#1FE0E6", input_border_width="1px",
    ),
    css=CSS,
) as demo:
    with gr.Column(elem_id="dispatch-header"):
        gr.Markdown(
            """
            # Dispatch AI — Arabic Proverb Generator
            Generate traditional Arabic proverbs + English translation · Qwen2.5-7B · Dispatch AI (FZE) · UAE
            """
        )

    with gr.Row():
        with gr.Column(scale=1):
            topic_input = gr.Textbox(
                label="Topic",
                placeholder="e.g. patience, friendship, knowledge...",
                value="patience",
                lines=1,
            )
            style_select = gr.Radio(
                ["Classical", "Poetic", "Simple", "Bedouin", "Royal"],
                label="Style", value="Classical",
            )
            generate_btn = gr.Button("📜 Generate Proverb", variant="primary")
            gr.Markdown("### Quick Topics")
            topic_buttons = gr.Dataset(
                label="Preset Topics",
                components=[topic_input],
                samples=[[t] for t in PRESET_TOPICS],
            )
            with gr.Accordion("Generate Multiple", open=False):
                count_slider = gr.Slider(1, 5, value=3, step=1, label="Number of Proverbs")
                multi_btn = gr.Button("📚 Generate Multiple Proverbs", variant="secondary")

        with gr.Column(scale=2):
            status_box = gr.Textbox(label="Status", interactive=False)
            output_md = gr.Markdown()

    # Events
    generate_btn.click(
        generate_proverb,
        inputs=[topic_input, style_select],
        outputs=[output_md, status_box],
    )
    multi_btn.click(
        generate_multiple_proverbs,
        inputs=[topic_input, style_select, count_slider],
        outputs=[output_md, status_box],
    )

    gr.Markdown(
        """
        <div class="dispatch-footer">
        © 2026 Dispatch AI (FZE) · UAE · License 10818 · Model: Qwen2.5-7B-Instruct via HF Inference API
        </div>
        """
    )

if __name__ == "__main__":
    demo.queue()
    demo.launch()