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
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
# app.py - Main Hugging Face Spaces Application
import gradio as gr
import os
import json
from datetime import datetime
from huggingface_hub import InferenceClient
import asyncio
from typing import Dict, List, Optional

class ProfessionalWritingBusiness:
    def __init__(self):
        """Initialize with Hugging Face Enterprise token for Cerebras acceleration"""
        self.hf_token = os.getenv("HF_TOKEN")
        if not self.hf_token:
            raise ValueError("HF_TOKEN environment variable is required")
        
        # Initialize Cerebras-accelerated Llama 3.3 70B
        self.client = InferenceClient(
            "meta-llama/Llama-3.3-70B-Instruct",
            provider="cerebras",
            token=self.hf_token
        )
        
        # Load service configurations
        self.services = self.load_top_services()
        
    def load_top_services(self) -> Dict:
        """Load the most demanded writing services for testing"""
        return {
            "academic_essay": {
                "name": "Academic Essay Writing",
                "category": "Student Writing",
                "price": 150,
                "description": "Comprehensive academic essays with proper structure and citations",
                "system_prompt": """You are an expert academic writing consultant with a PhD in Education and 15 years of experience. You specialize in creating clear, well-structured academic essays that meet rigorous academic standards. Your templates are used by a professional writing business with an established reputation for excellence.""",
                "fields": [
                    "Academic Level (High School/Undergraduate/Graduate)",
                    "Subject Area",
                    "Citation Style (APA/MLA/Chicago)",
                    "Target Word Count",
                    "Essay Type (Argumentative/Analytical/Expository)"
                ]
            },
            "research_paper": {
                "name": "Research Paper",
                "category": "Student Writing", 
                "price": 250,
                "description": "In-depth research papers with methodology and analysis",
                "system_prompt": """You are a research methodology expert and academic writing specialist with extensive experience in helping students conduct and present original research. You create templates that guide students through the complex process of academic research writing with publication-quality standards.""",
                "fields": [
                    "Academic Level",
                    "Field of Study",
                    "Research Type (Quantitative/Qualitative/Mixed)",
                    "Citation Style",
                    "Target Page Count",
                    "Minimum Sources Required"
                ]
            },
            "personal_statement": {
                "name": "Personal Statement/Admissions Essay",
                "category": "Student Writing",
                "price": 200,
                "description": "Compelling personal statements for college and graduate applications",
                "system_prompt": """You are an admissions consultant who has helped thousands of students gain acceptance to top universities. You understand what admissions committees look for and how to craft authentic, compelling personal narratives that stand out.""",
                "fields": [
                    "Application Type (College/Grad School/Scholarship)",
                    "Specific Program or School",
                    "Word Limit",
                    "Key Experiences to Highlight",
                    "Career Goals"
                ]
            },
            "blog_post": {
                "name": "SEO Blog Post",
                "category": "Content Marketing",
                "price": 150,
                "description": "SEO-optimized blog posts that drive traffic and engagement",
                "system_prompt": """You are a content marketing strategist and SEO expert with proven success in creating blog content that ranks highly in search engines. Your templates help businesses create content that serves both search algorithms and human readers, driving organic traffic and conversions.""",
                "fields": [
                    "Industry/Niche",
                    "Target Audience",
                    "Primary Keyword",
                    "Target Word Count",
                    "Content Goal (Educate/Convert/Engage)"
                ]
            },
            "press_release": {
                "name": "Press Release",
                "category": "Public Relations",
                "price": 300,
                "description": "Professional press releases that get media attention",
                "system_prompt": """You are a public relations expert and former journalist with 20 years of experience in media relations. You understand what journalists need and how to craft news stories that get coverage. Your press releases follow AP style guidelines and are structured to maximize media pickup.""",
                "fields": [
                    "Announcement Type",
                    "Company Name",
                    "Industry",
                    "Target Media Outlets",
                    "News Angle/Hook"
                ]
            },
            "grant_proposal": {
                "name": "Grant Proposal",
                "category": "Nonprofit/Academic",
                "price": 800,
                "description": "Comprehensive grant proposals for funding success",
                "system_prompt": """You are a grant writing specialist with a track record of securing over $50 million in funding for nonprofits, academic institutions, and research organizations. You understand funder psychology and know how to present compelling cases for support that combine emotional storytelling with hard data.""",
                "fields": [
                    "Grant Type (Government/Foundation/Corporate)",
                    "Funding Amount Requested",
                    "Organization Type",
                    "Project Focus Area",
                    "Funding Agency Name",
                    "Project Duration"
                ]
            },
            "resume_writing": {
                "name": "Professional Resume",
                "category": "Career Services",
                "price": 150,
                "description": "ATS-optimized resumes that get interviews",
                "system_prompt": """You are a certified professional resume writer (CPRW) with expertise in modern hiring practices and ATS systems. You create resumes that pass through applicant tracking systems while appealing to human recruiters. Your resumes have helped thousands of professionals land interviews at top companies.""",
                "fields": [
                    "Career Level",
                    "Industry",
                    "Target Job Title",
                    "Years of Experience",
                    "Key Achievements to Highlight"
                ]
            },
            "website_copy": {
                "name": "Website Copy",
                "category": "Marketing Copy",
                "price": 300,
                "description": "Conversion-focused website copy that sells",
                "system_prompt": """You are a conversion copywriting expert who understands consumer psychology and persuasive writing. You create website copy that not only informs but compels visitors to take action. Your copy balances professionalism with persuasion to maximize conversions.""",
                "fields": [
                    "Business Type",
                    "Target Customer Profile",
                    "Unique Selling Proposition",
                    "Primary Call-to-Action",
                    "Brand Voice (Professional/Casual/Authoritative)"
                ]
            }
        }
    
    def generate_template(self, service_key: str, client_inputs: str) -> Dict:
        """Generate professional template using Cerebras-accelerated Llama 3.1 70B"""
        if service_key not in self.services:
            return {"error": f"Service {service_key} not found"}
        
        service = self.services[service_key]
        
        # Prepare messages for conversational task (required by Cerebras)
        
        try:
            # Generate with Cerebras acceleration using conversational task
            messages = [
                {
                    "role": "system",
                    "content": service["system_prompt"] + f"\n\nCRITICAL QUALITY REQUIREMENTS:\n- This template is for a professional writing business charging ${service['price']}\n- Zero grammatical errors and perfect formatting\n- Include customizable placeholders in [BRACKETS]\n- Professional tone appropriate for {service['category']}\n- Must exceed client expectations and justify the investment\n- Template should be immediately usable and comprehensive"
                },
                {
                    "role": "user", 
                    "content": f"Create a comprehensive {service['name']} template based on these client requirements:\n\n{client_inputs}\n\nRequired Information to Address:\n{chr(10).join([f'- {field}' for field in service['fields']])}\n\nGenerate a complete, professional template that demonstrates expert-level knowledge and provides exceptional value. Include clear structure, proper formatting, and all necessary components for this type of writing."
                }
            ]
            
            response = self.client.chat_completion(
                messages=messages,
                max_tokens=2048,
                temperature=0.3,
                stream=False
            )
            
            template_content = response.choices[0].message.content.strip()
            
            # Quality assessment
            quality_metrics = self.assess_quality(template_content)
            
            return {
                "success": True,
                "service_name": service["name"],
                "category": service["category"],
                "template_content": template_content,
                "quality_score": quality_metrics["overall_score"],
                "word_count": quality_metrics["word_count"],
                "estimated_price": service["price"],
                "generated_at": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                "model_info": "Llama 3.3 70B Instruct via Cerebras",
                "has_placeholders": quality_metrics["has_placeholders"]
            }
            
        except Exception as e:
            return {
                "success": False,
                "error": f"Generation failed: {str(e)}",
                "service_name": service["name"]
            }
    
    def assess_quality(self, content: str) -> Dict:
        """Assess template quality for professional standards"""
        word_count = len(content.split())
        has_placeholders = "[" in content and "]" in content
        has_structure = any(marker in content.lower() for marker in 
                          ["#", "##", "1.", "2.", "introduction", "conclusion", "structure"])
        appropriate_length = word_count >= 150
        
        # Calculate overall score
        quality_factors = [has_placeholders, has_structure, appropriate_length]
        score = (sum(quality_factors) / len(quality_factors)) * 100
        
        return {
            "overall_score": round(score, 1),
            "word_count": word_count,
            "has_placeholders": has_placeholders,
            "has_structure": has_structure,
            "appropriate_length": appropriate_length
        }

# Initialize the business app
try:
    writing_business = ProfessionalWritingBusiness()
    print("βœ… Professional Writing Business initialized successfully!")
    print(f"πŸš€ Using Cerebras-accelerated Llama 3.3 70B")
except Exception as e:
    print(f"❌ Initialization failed: {e}")
    writing_business = None

def create_template_interface():
    """Create the main Gradio interface"""
    
    def generate_writing_template(service_selection, client_requirements):
        """Generate template based on service and requirements"""
        if not writing_business:
            return "❌ Error: System not properly initialized. Check HF_TOKEN.", "", "", ""
        
        if not service_selection:
            return "❌ Please select a writing service first.", "", "", ""
        
        if not client_requirements.strip():
            return "❌ Please provide client requirements.", "", "", ""
        
        # Generate the template
        result = writing_business.generate_template(service_selection, client_requirements)
        
        if not result.get("success"):
            error_msg = result.get("error", "Unknown error occurred")
            return f"❌ Generation Error: {error_msg}", "", "", ""
        
        # Format the successful result
        template_output = f"""# {result['service_name']} Template

**Quality Score:** {result['quality_score']}% β€’ **Word Count:** {result['word_count']} β€’ **Price:** ${result['estimated_price']}

## Generated Template:

{result['template_content']}

---
*Generated: {result['generated_at']} using {result['model_info']}*
"""
        
        # Service info
        service_info = f"""**Selected Service:** {result['service_name']}
**Category:** {result['category']}
**Estimated Price:** ${result['estimated_price']}
**Quality Score:** {result['quality_score']}%
**Placeholders Included:** {'βœ… Yes' if result['has_placeholders'] else '❌ No'}"""
        
        # Business metrics
        metrics = f"""**Template Quality:** {result['quality_score']}%
**Word Count:** {result['word_count']} words
**Generation Speed:** ~3 seconds (Cerebras)
**Model:** Llama 3.3 70B Instruct"""
        
        # Client guidance
        guidance = f"""**Next Steps:**
1. Review the template for accuracy and completeness
2. Customize the [PLACEHOLDER] sections with specific client details
3. Proofread for any client-specific adjustments
4. Deliver to client with confidence

**Template Features:**
- Professional structure and formatting
- Industry best practices included
- Customizable placeholders for easy personalization
- Ready for immediate client use"""
        
        return template_output, service_info, metrics, guidance
    
    def get_service_info(service_key):
        """Get detailed information about selected service"""
        if not writing_business or not service_key:
            return "Select a service to see details..."
        
        service = writing_business.services.get(service_key)
        if not service:
            return "Service not found."
        
        info = f"""**{service['name']}**

**Category:** {service['category']}
**Price:** ${service['price']}
**Description:** {service['description']}

**Required Information:**
{chr(10).join([f"β€’ {field}" for field in service['fields']])}

**Example Input:**
"Academic Level: Undergraduate
Subject Area: Psychology  
Citation Style: APA
Target Word Count: 1500-2000 words
Essay Type: Argumentative"
"""
        return info
    
    # Define the interface
    with gr.Blocks(
        title="Professional Writing Business - AI Template Generator",
        theme=gr.themes.Soft(),
        css="""
        .main-header { text-align: center; margin-bottom: 2rem; }
        .service-card { border: 1px solid #e5e7eb; border-radius: 8px; padding: 1rem; }
        .quality-badge { background: linear-gradient(45deg, #10b981, #059669); color: white; padding: 0.25rem 0.75rem; border-radius: 1rem; font-weight: bold; }
        """
    ) as interface:
        
        gr.Markdown("""
        # πŸŽ“βœοΈ Professional Writing Business - AI Template Generator
        
        **Powered by Cerebras-Accelerated Llama 3.3 70B** β€’ Lightning-fast generation for premium writing services
        
        Specializing in **Student Writing** + High-Demand Business Services
        """, elem_classes="main-header")
        
        with gr.Row():
            with gr.Column(scale=1):
                gr.Markdown("### πŸ“‹ Service Selection")
                
                service_dropdown = gr.Dropdown(
                    choices=list(writing_business.services.keys()) if writing_business else [],
                    label="Choose Writing Service",
                    value=None,
                    interactive=True
                )
                
                service_info_display = gr.Textbox(
                    label="Service Information & Requirements",
                    lines=12,
                    interactive=False,
                    placeholder="Select a service above to see details and requirements..."
                )
                
                gr.Markdown("### ✏️ Client Requirements")
                
                client_input = gr.Textbox(
                    label="Enter Client Specifications",
                    lines=8,
                    placeholder="""Example for Academic Essay:
Academic Level: Undergraduate
Subject Area: Psychology
Citation Style: APA
Target Word Count: 1500-2000 words
Essay Type: Argumentative
Specific Topic: The impact of social media on mental health""",
                    info="Provide detailed client requirements based on the service information above"
                )
                
                generate_btn = gr.Button(
                    "πŸš€ Generate Professional Template",
                    variant="primary",
                    size="lg"
                )
        
            with gr.Column(scale=2):
                gr.Markdown("### πŸ“„ Generated Template")
                
                template_output = gr.Textbox(
                    label="Professional Template",
                    lines=25,
                    show_copy_button=True,
                    placeholder="Your generated template will appear here..."
                )
        
        with gr.Row():
            service_metrics = gr.Textbox(
                label="πŸ“Š Service Details",
                lines=6,
                interactive=False
            )
            
            generation_metrics = gr.Textbox(
                label="⚑ Generation Metrics",
                lines=6,
                interactive=False
            )
            
            client_guidance = gr.Textbox(
                label="πŸ“‹ Client Delivery Guide",
                lines=6,
                interactive=False
            )
        
        # Business Dashboard
        with gr.Row():
            gr.Markdown("""
            ### πŸ’Ό Business Dashboard
            
            | **Service Category** | **Services** | **Price Range** | **Specialization** |
            |---------------------|--------------|-----------------|-------------------|
            | **Student Writing** | 3 Core Services | $150-$250 | Your Primary Focus |
            | **Business Writing** | 2 Services | $300-$800 | High-Value Projects |
            | **Marketing Copy** | 3 Services | $150-$300 | Quick Turnaround |
            
            **Total Portfolio Value:** $1,950 per complete cycle β€’ **Generation Speed:** 2-5 seconds β€’ **Quality Standard:** 90%+
            """)
        
        # Event handlers
        service_dropdown.change(
            fn=get_service_info,
            inputs=[service_dropdown],
            outputs=[service_info_display]
        )
        
        generate_btn.click(
            fn=generate_writing_template,
            inputs=[service_dropdown, client_input],
            outputs=[template_output, service_metrics, generation_metrics, client_guidance]
        )
    
    return interface

# Launch the application
if __name__ == "__main__":
    print("πŸš€ Launching Professional Writing Business Template Generator...")
    
    interface = create_template_interface()
    
    interface.launch(
        server_name="0.0.0.0",
        server_port=7860,
        share=True,
        show_api=False,
        show_error=True
    )
    
    print("βœ… Application launched successfully!")
    print("🎯 Ready to generate professional writing templates!")