|
|
|
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") |
|
|
|
|
|
self.client = InferenceClient( |
|
"meta-llama/Llama-3.3-70B-Instruct", |
|
provider="cerebras", |
|
token=self.hf_token |
|
) |
|
|
|
|
|
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] |
|
|
|
|
|
|
|
try: |
|
|
|
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_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 |
|
|
|
|
|
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 |
|
} |
|
|
|
|
|
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.", "", "", "" |
|
|
|
|
|
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}", "", "", "" |
|
|
|
|
|
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 = 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'}""" |
|
|
|
|
|
metrics = f"""**Template Quality:** {result['quality_score']}% |
|
**Word Count:** {result['word_count']} words |
|
**Generation Speed:** ~3 seconds (Cerebras) |
|
**Model:** Llama 3.3 70B Instruct""" |
|
|
|
|
|
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 |
|
|
|
|
|
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 |
|
) |
|
|
|
|
|
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%+ |
|
""") |
|
|
|
|
|
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 |
|
|
|
|
|
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!") |