File size: 29,059 Bytes
4ba3bf6
 
631c246
4ba3bf6
 
 
 
 
631c246
4ba3bf6
 
 
 
 
631c246
 
 
4ba3bf6
631c246
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4ba3bf6
 
631c246
4ba3bf6
631c246
 
 
4ba3bf6
631c246
 
4ba3bf6
 
 
 
 
 
631c246
 
4ba3bf6
631c246
 
 
 
 
 
 
 
 
 
 
 
4ba3bf6
 
 
 
 
 
 
631c246
4ba3bf6
 
 
 
 
 
 
 
 
 
 
 
631c246
4ba3bf6
 
631c246
4ba3bf6
 
631c246
 
 
 
4ba3bf6
 
 
 
 
 
631c246
4ba3bf6
631c246
4ba3bf6
 
631c246
 
4ba3bf6
 
 
 
 
 
 
 
631c246
4ba3bf6
 
 
631c246
4ba3bf6
631c246
4ba3bf6
631c246
 
 
4ba3bf6
 
 
 
 
 
 
 
 
631c246
 
 
 
 
4ba3bf6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
631c246
4ba3bf6
631c246
4ba3bf6
 
 
 
 
 
 
631c246
 
4ba3bf6
 
 
 
631c246
4ba3bf6
631c246
4ba3bf6
 
 
 
 
 
 
631c246
4ba3bf6
 
 
631c246
 
 
 
4ba3bf6
 
 
 
 
 
 
631c246
4ba3bf6
631c246
4ba3bf6
 
631c246
4ba3bf6
631c246
4ba3bf6
631c246
4ba3bf6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
631c246
4ba3bf6
 
631c246
4ba3bf6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
631c246
4ba3bf6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
631c246
4ba3bf6
 
 
 
 
 
 
 
 
 
 
 
 
 
631c246
4ba3bf6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
631c246
4ba3bf6
 
 
 
 
 
 
631c246
4ba3bf6
631c246
 
 
4ba3bf6
 
 
 
631c246
 
4ba3bf6
 
631c246
4ba3bf6
631c246
 
4ba3bf6
631c246
4ba3bf6
 
 
631c246
4ba3bf6
 
631c246
4ba3bf6
 
 
 
 
 
 
 
 
 
 
 
631c246
4ba3bf6
631c246
 
4ba3bf6
631c246
 
4ba3bf6
 
 
631c246
4ba3bf6
 
631c246
4ba3bf6
 
 
 
 
 
 
 
 
 
631c246
4ba3bf6
 
 
631c246
4ba3bf6
 
 
631c246
4ba3bf6
631c246
 
4ba3bf6
631c246
4ba3bf6
631c246
 
4ba3bf6
631c246
 
 
4ba3bf6
 
631c246
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4ba3bf6
 
 
 
 
631c246
 
4ba3bf6
 
 
631c246
4ba3bf6
 
 
631c246
 
 
 
 
 
4ba3bf6
 
 
 
 
631c246
 
4ba3bf6
 
 
 
631c246
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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
"""
HIX-Gen: Multi-Agent Writing Suite
Powered by Groq API (FREE - llama-3.3-70b) β€” No quota issues!
Designed for Hugging Face Spaces deployment
"""

import os
import gradio as gr
from groq import Groq
from dotenv import load_dotenv

# ── Load environment variables (for local dev) ──────────────────────────────
load_dotenv()

# ── Groq API Setup ───────────────────────────────────────────────────────────
def get_groq_client():
    api_key = os.environ.get("GROQ_API_KEY")
    if not api_key:
        raise ValueError("GROQ_API_KEY not set. Please add it in HF Spaces Secrets.")
    return Groq(api_key=api_key)

def call_groq(system_prompt: str, user_message: str) -> str:
    """Single Groq API call with system + user message."""
    client = get_groq_client()
    response = client.chat.completions.create(
        model="llama-3.3-70b-versatile",
        messages=[
            {"role": "system", "content": system_prompt},
            {"role": "user",   "content": user_message},
        ],
        temperature=0.75,
        max_tokens=2048,
    )
    return response.choices[0].message.content.strip()

# ── Multi-Agent Core ─────────────────────────────────────────────────────────
def multi_agent_pipeline(agent1_system: str, agent2_system: str, input_text: str) -> tuple[str, str]:
    """
    Agent 1 β†’ generates / transforms
    Agent 2 β†’ polishes / humanizes
    Returns (agent1_draft, agent2_final)
    """
    draft = call_groq(agent1_system, input_text)
    final = call_groq(agent2_system, f"Here is the draft to refine:\n\n{draft}")
    return draft, final


# ════════════════════════════════════════════════════════════════════════════
# MODULE 1 β€” AI HUMANIZER
# ════════════════════════════════════════════════════════════════════════════
HUMANIZER_A1 = """You are Agent-1: an expert linguistic analyst and rewriter.
Your job is to take AI-generated text and rewrite it to sound 100% human by:
1. Replacing robotic, overly formal phrases with natural conversational language.
2. Varying sentence length β€” mix short punchy sentences with longer flowing ones.
3. Adding subtle human nuances (e.g., "Honestly,", "Look,", "Here's the thing β€”").
4. Removing AI giveaways: excessive bullet points, hollow transitions like "In conclusion", "Furthermore", "It is worth noting".
5. Keeping ALL the original meaning and facts perfectly intact.
Output ONLY the rewritten text. No explanations, no preamble."""

HUMANIZER_A2 = """You are Agent-2: a professional editor and AI-detection bypass specialist.
You receive a human-ified draft and make it even MORE natural:
1. Inject mild personal perspective where fitting (e.g., "I'd argue...", "Most people overlook...").
2. Fix any remaining stiff or AI-sounding phrasing.
3. Ensure the tone is warm, engaging, and reads like a real expert wrote it.
4. It must pass AI detectors like GPTZero, Originality.ai, and Turnitin.
Output ONLY the final polished text. No explanations, no meta-commentary."""

def run_humanizer(ai_text: str, progress=gr.Progress()):
    if not ai_text.strip():
        return "", "", "⚠️ Please paste some AI-generated text first."
    try:
        progress(0.2, desc="Agent 1: Rewriting for natural flow...")
        draft, final = multi_agent_pipeline(HUMANIZER_A1, HUMANIZER_A2, ai_text)
        progress(1.0, desc="Done!")
        return draft, final, "βœ… Humanization complete! Two agents processed your text."
    except Exception as e:
        return "", "", f"❌ Error: {str(e)}"


# ════════════════════════════════════════════════════════════════════════════
# MODULE 2 β€” AI WRITER
# ════════════════════════════════════════════════════════════════════════════
WRITER_TEMPLATES = {
    "πŸ“ Blog Post": {
        "agent1": """You are Agent-1: a skilled content strategist and blog writer.
Write a complete, engaging blog post based on the details provided.
Structure: Hook intro β†’ 3-4 body sections with subheadings β†’ Strong conclusion with CTA.
Tone: Conversational yet authoritative. Use real examples. Avoid fluff.
Output ONLY the blog post content. No explanations.""",
        "agent2": """You are Agent-2: a senior editor at a top digital publication.
Polish this blog post draft to be publication-ready:
1. Strengthen the opening hook β€” it must grab attention immediately.
2. Ensure smooth, natural transitions between sections.
3. Add a compelling meta-description at the very top (marked [META]:).
4. Make the closing CTA irresistible.
Output ONLY the final polished blog post.""",
        "fields": ["Topic / Title", "Target Audience", "Key Points to Cover", "Tone (casual/formal/witty)"]
    },
    "πŸ“§ Professional Email": {
        "agent1": """You are Agent-1: an expert business communications writer.
Draft a professional email based on the context provided.
Requirements: Clear subject line, concise body (3-4 short paragraphs max), clear CTA.
Tone: Professional but human β€” not robotic corporate-speak.
Output ONLY the email (Subject: ... then body). No explanations.""",
        "agent2": """You are Agent-2: a C-suite communications coach.
Refine this email draft to be razor-sharp and persuasive:
1. Subject line must be compelling β€” gets opened.
2. Tighten every sentence β€” eliminate filler words.
3. Make the ask crystal clear.
4. Close with confidence, not desperation.
Output ONLY the final email.""",
        "fields": ["Email Purpose", "Recipient (role/context)", "Key Message", "Desired Outcome"]
    },
    "πŸ“± Social Media Post": {
        "agent1": """You are Agent-1: a viral social media copywriter.
Create an engaging social media post based on the input.
Rules: Hook in first line (don't start with "I"), use action/question/stat openers, add relevant hashtags.
Make it share-worthy and conversation-starting.
Output ONLY the post content.""",
        "agent2": """You are Agent-2: a growth hacking social media specialist.
Supercharge this post:
1. Make the opening hook impossible to scroll past.
2. Add a pattern-interrupt (unexpected angle or bold claim).
3. Optimize hashtags for reach (mix niche + broad).
4. Add a strong engagement CTA.
5. End with: [BEST FOR: platform recommendation]
Output ONLY the final post.""",
        "fields": ["Topic / Message", "Target Platform (LinkedIn/X/Instagram)", "Brand Voice", "Goal (awareness/leads/engagement)"]
    }
}

def run_writer(template_type: str, field1: str, field2: str, field3: str, field4: str, progress=gr.Progress()):
    if not field1.strip():
        return "", "", "⚠️ Please fill in at least the first field."
    try:
        template = WRITER_TEMPLATES[template_type]
        fields = template["fields"]
        combined_input = f"""{fields[0]}: {field1}
{fields[1]}: {field2}
{fields[2]}: {field3}
{fields[3]}: {field4}""".strip()

        progress(0.2, desc="Agent 1: Generating first draft...")
        draft, final = multi_agent_pipeline(template["agent1"], template["agent2"], combined_input)
        progress(1.0, desc="Done!")
        return draft, final, f"βœ… {template_type} generated successfully by 2 AI agents."
    except Exception as e:
        return "", "", f"❌ Error: {str(e)}"

def update_writer_labels(template_type: str):
    fields = WRITER_TEMPLATES[template_type]["fields"]
    return (
        gr.update(label=fields[0], placeholder=f"Enter {fields[0].lower()}..."),
        gr.update(label=fields[1], placeholder=f"Enter {fields[1].lower()}..."),
        gr.update(label=fields[2], placeholder=f"Enter {fields[2].lower()}..."),
        gr.update(label=fields[3], placeholder=f"Enter {fields[3].lower()}..."),
    )


# ════════════════════════════════════════════════════════════════════════════
# MODULE 3 β€” SMART EDITOR
# ════════════════════════════════════════════════════════════════════════════
EDITOR_MODES = {
    "πŸ” Summarize": {
        "agent1": """You are Agent-1: a master summarizer.
Condense the input text into a clear, accurate summary.
Preserve all KEY points, remove redundancy, keep it ~20-30% of original length.
Use bullet points for long content, prose for short content.
Output ONLY the summary.""",
        "agent2": """You are Agent-2: a communications expert.
Refine this summary:
1. Lead with the single most important takeaway.
2. Ensure every line earns its place β€” no redundancy.
3. End with the key implication or action item.
Output ONLY the final polished summary."""
    },
    "✨ Improve Writing": {
        "agent1": """You are Agent-1: an expert writing coach.
Improve the given text by:
1. Fixing grammar, spelling, and punctuation errors.
2. Improving clarity and sentence flow.
3. Replacing vague words with precise, powerful ones.
4. Restructuring awkward sentences.
Keep the author's voice and intent intact.
Output ONLY the improved text.""",
        "agent2": """You are Agent-2: an award-winning editor.
Do a final pass:
1. Elevate the most impactful sentences.
2. Ensure the opening grabs attention immediately.
3. Cut any remaining filler or redundancy.
4. Verify the tone is consistent throughout.
Output ONLY the final polished text."""
    },
    "πŸ”„ Change Tone": {
        "agent1": """You are Agent-1: a tone adaptation specialist.
The user will specify a target tone in their input. Rewrite the text in that exact tone.
Common tones: formal, casual, confident, empathetic, persuasive, academic, friendly, Gen-Z.
Maintain all factual content while completely transforming the voice.
Output ONLY the rewritten text.""",
        "agent2": """You are Agent-2: a brand voice consultant.
Review the tone-adapted draft:
1. Ensure the new tone is consistent from start to finish (no tone slippage).
2. Word choice and sentence rhythm must feel authentic to that tone.
3. The core message must still come through clearly.
Output ONLY the final version."""
    },
    "πŸ“ Expand": {
        "agent1": """You are Agent-1: a content expansion specialist.
Expand the given text with:
1. More detail, context, and explanation.
2. Relevant examples or analogies.
3. Supporting reasoning or evidence.
4. Smooth transitions between ideas.
Target: 2-3x the original length while adding REAL value β€” no padding.
Output ONLY the expanded text.""",
        "agent2": """You are Agent-2: a senior content strategist.
Review the expanded draft:
1. Remove any filler that crept in.
2. Ensure all new additions feel organic, not bolted-on.
3. Strengthen the opening and closing.
4. Verify the expanded version flows naturally from start to finish.
Output ONLY the final polished expanded text."""
    }
}

def run_editor(text: str, mode: str, extra_instruction: str, progress=gr.Progress()):
    if not text.strip():
        return "", "", "⚠️ Please enter some text to edit."
    try:
        config = EDITOR_MODES[mode]
        full_input = text
        if extra_instruction.strip():
            full_input = f"[Special Instruction: {extra_instruction}]\n\n{text}"

        progress(0.2, desc=f"Agent 1: Applying {mode}...")
        draft, final = multi_agent_pipeline(config["agent1"], config["agent2"], full_input)
        progress(1.0, desc="Done!")
        return draft, final, f"βœ… {mode} complete! Text processed by 2 AI agents."
    except Exception as e:
        return "", "", f"❌ Error: {str(e)}"


# ════════════════════════════════════════════════════════════════════════════
# GRADIO UI
# ════════════════════════════════════════════════════════════════════════════
custom_css = """
@import url('https://fonts.googleapis.com/css2?family=DM+Mono:wght@300;400;500&family=Syne:wght@400;600;700;800&family=DM+Sans:wght@300;400;500&display=swap');

:root {
    --bg-void: #080b0f;
    --bg-deep: #0d1117;
    --bg-panel: #111620;
    --bg-card: #161c27;
    --bg-input: #1a2130;
    --border-dim: #1f2d3d;
    --border-glow: #2a3f5a;
    --accent-cyan: #00d4ff;
    --accent-teal: #00b894;
    --accent-amber: #f0a500;
    --text-primary: #e8edf5;
    --text-secondary: #8899aa;
    --text-muted: #4a5568;
    --font-display: 'Syne', sans-serif;
    --font-body: 'DM Sans', sans-serif;
    --font-mono: 'DM Mono', monospace;
    --radius: 10px;
}

* { box-sizing: border-box; }

body, .gradio-container {
    background: var(--bg-void) !important;
    font-family: var(--font-body) !important;
    color: var(--text-primary) !important;
}

.hix-header {
    background: linear-gradient(135deg, var(--bg-deep) 0%, var(--bg-panel) 100%);
    border-bottom: 1px solid var(--border-dim);
    padding: 28px 40px 24px;
    text-align: center;
    position: relative;
    overflow: hidden;
}

.hix-header::before {
    content: '';
    position: absolute;
    top: 0; left: 0; right: 0; bottom: 0;
    background: radial-gradient(ellipse 60% 50% at 50% -20%, rgba(0,212,255,0.08) 0%, transparent 70%);
    pointer-events: none;
}

.hix-logo {
    font-family: var(--font-display);
    font-weight: 800;
    font-size: 2.4rem;
    letter-spacing: -0.02em;
    background: linear-gradient(135deg, var(--accent-cyan) 0%, #7b9fff 50%, var(--accent-teal) 100%);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    background-clip: text;
    margin: 0;
    line-height: 1;
}

.hix-tagline {
    font-family: var(--font-mono);
    font-size: 0.75rem;
    color: var(--text-secondary);
    letter-spacing: 0.12em;
    text-transform: uppercase;
    margin-top: 6px;
}

.hix-badge {
    display: inline-block;
    background: rgba(0,212,255,0.1);
    border: 1px solid rgba(0,212,255,0.25);
    color: var(--accent-cyan);
    font-family: var(--font-mono);
    font-size: 0.65rem;
    letter-spacing: 0.1em;
    padding: 3px 10px;
    border-radius: 20px;
    margin-top: 10px;
}

.tabs > .tab-nav {
    background: var(--bg-panel) !important;
    border-bottom: 1px solid var(--border-dim) !important;
    padding: 0 20px !important;
    gap: 4px !important;
}

.tabs > .tab-nav > button {
    font-family: var(--font-display) !important;
    font-weight: 600 !important;
    font-size: 0.82rem !important;
    letter-spacing: 0.04em !important;
    color: var(--text-muted) !important;
    background: transparent !important;
    border: none !important;
    border-bottom: 2px solid transparent !important;
    padding: 14px 18px !important;
    border-radius: 0 !important;
    transition: all 0.2s ease !important;
}

.tabs > .tab-nav > button:hover {
    color: var(--text-secondary) !important;
    background: rgba(255,255,255,0.03) !important;
}

.tabs > .tab-nav > button.selected {
    color: var(--accent-cyan) !important;
    border-bottom-color: var(--accent-cyan) !important;
}

.tab-content, .tabitem {
    background: var(--bg-deep) !important;
    padding: 24px !important;
}

textarea, .gr-textbox textarea {
    background: var(--bg-input) !important;
    border: 1px solid var(--border-dim) !important;
    border-radius: var(--radius) !important;
    color: var(--text-primary) !important;
    font-family: var(--font-body) !important;
    font-size: 0.9rem !important;
    line-height: 1.6 !important;
    transition: border-color 0.2s ease !important;
}

textarea:focus {
    border-color: var(--accent-cyan) !important;
    box-shadow: 0 0 0 3px rgba(0,212,255,0.08) !important;
    outline: none !important;
}

.gr-textbox label span, label span {
    font-family: var(--font-display) !important;
    font-size: 0.78rem !important;
    font-weight: 600 !important;
    letter-spacing: 0.06em !important;
    text-transform: uppercase !important;
    color: var(--text-secondary) !important;
}

button.primary, .gr-button.primary, button[variant="primary"] {
    background: linear-gradient(135deg, #006fff 0%, var(--accent-cyan) 100%) !important;
    border: none !important;
    border-radius: var(--radius) !important;
    color: #fff !important;
    font-family: var(--font-display) !important;
    font-weight: 700 !important;
    font-size: 0.85rem !important;
    letter-spacing: 0.06em !important;
    padding: 12px 28px !important;
    transition: all 0.25s ease !important;
    box-shadow: 0 4px 16px rgba(0,111,255,0.3) !important;
}

button.primary:hover {
    transform: translateY(-1px) !important;
    box-shadow: 0 6px 24px rgba(0,212,255,0.4) !important;
}

.hix-footer {
    text-align: center;
    padding: 20px;
    border-top: 1px solid var(--border-dim);
    font-family: var(--font-mono);
    font-size: 0.7rem;
    color: var(--text-muted);
    background: var(--bg-panel);
}

::-webkit-scrollbar { width: 6px; }
::-webkit-scrollbar-track { background: var(--bg-deep); }
::-webkit-scrollbar-thumb { background: var(--border-glow); border-radius: 3px; }
::-webkit-scrollbar-thumb:hover { background: var(--accent-cyan); }
"""

with gr.Blocks(
    theme=gr.themes.Base(
        primary_hue="cyan",
        secondary_hue="blue",
        neutral_hue="slate",
        font=gr.themes.GoogleFont("DM Sans"),
    ),
    css=custom_css,
    title="HIX-Gen: Multi-Agent Writing Suite",
) as demo:

    gr.HTML("""
    <div class="hix-header">
        <h1 class="hix-logo">HIX-Gen</h1>
        <p class="hix-tagline">Multi-Agent Writing Suite</p>
        <span class="hix-badge">⚑ Powered by Groq · Llama 3.3 70B · Dual-Agent Architecture · 100% Free</span>
    </div>
    """)

    with gr.Tabs():

        # ── Tab 1: AI Humanizer ──────────────────────────────────────────
        with gr.TabItem("🧬 AI Humanizer"):
            gr.HTML("""<div style="padding:16px 0 8px">
                <p style="color:#8899aa;font-size:0.9rem;line-height:1.6;margin:0">
                    Paste robotic AI-generated text and our <strong style="color:#00d4ff">dual-agent system</strong>
                    will transform it into natural, human-sounding prose that bypasses AI detectors.
                </p></div>""")
            with gr.Row():
                with gr.Column(scale=1):
                    h_input = gr.Textbox(
                        label="πŸ€– AI-Generated Text (Input)",
                        placeholder="Paste your AI-generated text here...",
                        lines=12,
                    )
                    h_btn = gr.Button("πŸš€ Humanize Text", variant="primary")
                    h_status = gr.Markdown("")
                with gr.Column(scale=1):
                    h_draft = gr.Textbox(label="πŸ“ Agent 1 β€” Natural Draft", lines=5, interactive=False)
                    h_final = gr.Textbox(label="✨ Agent 2 β€” Final Human Output", lines=10, interactive=False)

            h_btn.click(fn=run_humanizer, inputs=[h_input], outputs=[h_draft, h_final, h_status])

        # ── Tab 2: AI Writer ─────────────────────────────────────────────
        with gr.TabItem("✍️ AI Writer"):
            gr.HTML("""<div style="padding:16px 0 8px">
                <p style="color:#8899aa;font-size:0.9rem;line-height:1.6;margin:0">
                    Select a content template, fill in your details, and let two AI agents craft and polish your content.
                </p></div>""")
            with gr.Row():
                with gr.Column(scale=1):
                    w_template = gr.Dropdown(
                        choices=list(WRITER_TEMPLATES.keys()),
                        value="πŸ“ Blog Post",
                        label="Content Template",
                    )
                    w_f1 = gr.Textbox(label="Topic / Title", placeholder="Enter topic / title...", lines=2)
                    w_f2 = gr.Textbox(label="Target Audience", placeholder="Enter target audience...", lines=2)
                    w_f3 = gr.Textbox(label="Key Points to Cover", placeholder="Enter key points...", lines=3)
                    w_f4 = gr.Textbox(label="Tone (casual/formal/witty)", placeholder="Enter tone...", lines=1)
                    w_btn = gr.Button("πŸš€ Generate Content", variant="primary")
                    w_status = gr.Markdown("")
                with gr.Column(scale=1):
                    w_draft = gr.Textbox(label="πŸ“ Agent 1 β€” First Draft", lines=8, interactive=False)
                    w_final = gr.Textbox(label="✨ Agent 2 β€” Polished Output", lines=14, interactive=False)

            w_template.change(fn=update_writer_labels, inputs=[w_template], outputs=[w_f1, w_f2, w_f3, w_f4])
            w_btn.click(fn=run_writer, inputs=[w_template, w_f1, w_f2, w_f3, w_f4], outputs=[w_draft, w_final, w_status])

        # ── Tab 3: Smart Editor ──────────────────────────────────────────
        with gr.TabItem("πŸ”§ Smart Editor"):
            gr.HTML("""<div style="padding:16px 0 8px">
                <p style="color:#8899aa;font-size:0.9rem;line-height:1.6;margin:0">
                    Paste any text and choose an editing mode. Two agents will transform your content with precision.
                </p></div>""")
            with gr.Row():
                with gr.Column(scale=1):
                    e_mode = gr.Dropdown(
                        choices=list(EDITOR_MODES.keys()),
                        value="✨ Improve Writing",
                        label="Editing Mode",
                    )
                    e_input = gr.Textbox(
                        label="πŸ“„ Your Text",
                        placeholder="Paste the text you want to edit here...",
                        lines=12,
                    )
                    e_extra = gr.Textbox(
                        label="πŸ’‘ Special Instructions (optional)",
                        placeholder="e.g. 'Make it sound like Gen-Z' or 'Target tone: empathetic'",
                        lines=2
                    )
                    e_btn = gr.Button("πŸš€ Process Text", variant="primary")
                    e_status = gr.Markdown("")
                with gr.Column(scale=1):
                    e_draft = gr.Textbox(label="πŸ“ Agent 1 β€” Processed Draft", lines=8, interactive=False)
                    e_final = gr.Textbox(label="✨ Agent 2 β€” Final Output", lines=14, interactive=False)

            e_btn.click(fn=run_editor, inputs=[e_input, e_mode, e_extra], outputs=[e_draft, e_final, e_status])

        # ── Tab 4: Setup Guide ───────────────────────────────────────────
        with gr.TabItem("βš™οΈ Setup"):
            gr.HTML("""
            <div style="max-width:680px;margin:32px auto;padding:0 16px">
                <h2 style="font-family:'Syne',sans-serif;font-weight:800;color:#e8edf5;margin-bottom:16px">
                    πŸ”‘ How to Get Your FREE Groq API Key
                </h2>

                <div style="background:#161c27;border:1px solid #1f2d3d;border-radius:10px;padding:24px;margin-bottom:20px">
                    <div style="display:flex;flex-direction:column;gap:16px">

                        <div style="display:flex;gap:14px;align-items:flex-start">
                            <div style="background:rgba(0,212,255,0.15);color:#00d4ff;font-family:'DM Mono',monospace;font-weight:700;font-size:0.85rem;padding:4px 10px;border-radius:6px;white-space:nowrap">Step 1</div>
                            <div style="color:#c8d8e8;font-size:0.9rem;line-height:1.6">
                                Go to <strong style="color:#00d4ff">console.groq.com</strong> β†’ Sign up FREE (no credit card!)
                            </div>
                        </div>

                        <div style="display:flex;gap:14px;align-items:flex-start">
                            <div style="background:rgba(0,212,255,0.15);color:#00d4ff;font-family:'DM Mono',monospace;font-weight:700;font-size:0.85rem;padding:4px 10px;border-radius:6px;white-space:nowrap">Step 2</div>
                            <div style="color:#c8d8e8;font-size:0.9rem;line-height:1.6">
                                Click <strong>API Keys</strong> in sidebar β†’ <strong>Create API Key</strong> β†’ Copy it
                            </div>
                        </div>

                        <div style="display:flex;gap:14px;align-items:flex-start">
                            <div style="background:rgba(0,212,255,0.15);color:#00d4ff;font-family:'DM Mono',monospace;font-weight:700;font-size:0.85rem;padding:4px 10px;border-radius:6px;white-space:nowrap">Step 3</div>
                            <div style="color:#c8d8e8;font-size:0.9rem;line-height:1.6">
                                HF Space β†’ <strong>Settings</strong> β†’ <strong>Repository Secrets</strong> β†’ Add:<br>
                                <code style="background:#0d1117;padding:3px 10px;border-radius:4px;color:#f0a500;font-family:'DM Mono',monospace;display:inline-block;margin-top:6px">Name: GROQ_API_KEY &nbsp;&nbsp; Value: gsk_xxxxxxxxxx</code>
                            </div>
                        </div>

                        <div style="display:flex;gap:14px;align-items:flex-start">
                            <div style="background:rgba(0,184,148,0.15);color:#00b894;font-family:'DM Mono',monospace;font-weight:700;font-size:0.85rem;padding:4px 10px;border-radius:6px;white-space:nowrap">Done βœ…</div>
                            <div style="color:#c8d8e8;font-size:0.9rem;line-height:1.6">
                                Restart your Space β€” it works instantly!
                            </div>
                        </div>
                    </div>
                </div>

                <div style="background:#111620;border:1px solid #1f2d3d;border-radius:10px;padding:20px;margin-bottom:20px">
                    <div style="font-family:'Syne',sans-serif;font-weight:700;color:#e8edf5;margin-bottom:12px">βš™οΈ Tech Stack</div>
                    <div style="display:grid;grid-template-columns:auto 1fr;gap:8px 24px;font-size:0.85rem">
                        <span style="color:#8899aa">AI Engine</span><span style="color:#00d4ff;font-family:'DM Mono',monospace">Groq Β· Llama 3.3 70B (FREE)</span>
                        <span style="color:#8899aa">Framework</span><span style="color:#00d4ff;font-family:'DM Mono',monospace">Gradio 4.x</span>
                        <span style="color:#8899aa">Architecture</span><span style="color:#00d4ff;font-family:'DM Mono',monospace">Dual-Agent Pipeline</span>
                        <span style="color:#8899aa">Platform</span><span style="color:#00d4ff;font-family:'DM Mono',monospace">Hugging Face Spaces</span>
                        <span style="color:#8899aa">Cost</span><span style="color:#00b894;font-family:'DM Mono',monospace">$0 β€” Completely Free</span>
                    </div>
                </div>

                <div style="background:rgba(240,165,0,0.08);border:1px solid rgba(240,165,0,0.2);border-radius:10px;padding:16px">
                    <div style="color:#f0a500;font-size:0.85rem;line-height:1.6">
                        <strong>πŸ’‘ Groq Free Tier:</strong> 30 requests/min Β· 14,400 requests/day Β· 500,000 tokens/day
                        β€” plenty for any personal or demo project!
                    </div>
                </div>
            </div>
            """)

    gr.HTML("""
    <div class="hix-footer">
        HIX-Gen v2.0 &nbsp;Β·&nbsp; Dual-Agent Architecture &nbsp;Β·&nbsp;
        Powered by Groq + Llama 3.3 70B &nbsp;Β·&nbsp; 100% Free &nbsp;Β·&nbsp; Hugging Face Spaces
    </div>
    """)

if __name__ == "__main__":
    demo.launch(server_name="0.0.0.0", server_port=7860, show_error=True)