SlouchyBuffalo commited on
Commit
9fbf06d
·
verified ·
1 Parent(s): a42fe21

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -465
app.py DELETED
@@ -1,465 +0,0 @@
1
- # app.py - Main Hugging Face Spaces Application
2
- import gradio as gr
3
- import os
4
- import json
5
- from datetime import datetime
6
- from huggingface_hub import InferenceClient
7
- import asyncio
8
- from typing import Dict, List, Optional
9
-
10
- class ProfessionalWritingBusiness:
11
- def __init__(self):
12
- """Initialize with Hugging Face Enterprise token for Cerebras acceleration"""
13
- self.hf_token = os.getenv("HF_TOKEN")
14
- if not self.hf_token:
15
- raise ValueError("HF_TOKEN environment variable is required")
16
-
17
- # Initialize Cerebras-accelerated Llama 3.1 70B
18
- self.client = InferenceClient(
19
- model="meta-llama/Llama-3.1-70B-Instruct",
20
- token=self.hf_token
21
- )
22
-
23
- # Load service configurations
24
- self.services = self.load_top_services()
25
-
26
- def load_top_services(self) -> Dict:
27
- """Load the most demanded writing services for testing"""
28
- return {
29
- "academic_essay": {
30
- "name": "Academic Essay Writing",
31
- "category": "Student Writing",
32
- "price": 150,
33
- "description": "Comprehensive academic essays with proper structure and citations",
34
- "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.""",
35
- "fields": [
36
- "Academic Level (High School/Undergraduate/Graduate)",
37
- "Subject Area",
38
- "Citation Style (APA/MLA/Chicago)",
39
- "Target Word Count",
40
- "Essay Type (Argumentative/Analytical/Expository)"
41
- ]
42
- },
43
- "research_paper": {
44
- "name": "Research Paper",
45
- "category": "Student Writing",
46
- "price": 250,
47
- "description": "In-depth research papers with methodology and analysis",
48
- "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.""",
49
- "fields": [
50
- "Academic Level",
51
- "Field of Study",
52
- "Research Type (Quantitative/Qualitative/Mixed)",
53
- "Citation Style",
54
- "Target Page Count",
55
- "Minimum Sources Required"
56
- ]
57
- },
58
- "personal_statement": {
59
- "name": "Personal Statement/Admissions Essay",
60
- "category": "Student Writing",
61
- "price": 200,
62
- "description": "Compelling personal statements for college and graduate applications",
63
- "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.""",
64
- "fields": [
65
- "Application Type (College/Grad School/Scholarship)",
66
- "Specific Program or School",
67
- "Word Limit",
68
- "Key Experiences to Highlight",
69
- "Career Goals"
70
- ]
71
- },
72
- "blog_post": {
73
- "name": "SEO Blog Post",
74
- "category": "Content Marketing",
75
- "price": 150,
76
- "description": "SEO-optimized blog posts that drive traffic and engagement",
77
- "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.""",
78
- "fields": [
79
- "Industry/Niche",
80
- "Target Audience",
81
- "Primary Keyword",
82
- "Target Word Count",
83
- "Content Goal (Educate/Convert/Engage)"
84
- ]
85
- },
86
- "press_release": {
87
- "name": "Press Release",
88
- "category": "Public Relations",
89
- "price": 300,
90
- "description": "Professional press releases that get media attention",
91
- "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.""",
92
- "fields": [
93
- "Announcement Type",
94
- "Company Name",
95
- "Industry",
96
- "Target Media Outlets",
97
- "News Angle/Hook"
98
- ]
99
- },
100
- "grant_proposal": {
101
- "name": "Grant Proposal",
102
- "category": "Nonprofit/Academic",
103
- "price": 800,
104
- "description": "Comprehensive grant proposals for funding success",
105
- "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.""",
106
- "fields": [
107
- "Grant Type (Government/Foundation/Corporate)",
108
- "Funding Amount Requested",
109
- "Organization Type",
110
- "Project Focus Area",
111
- "Funding Agency Name",
112
- "Project Duration"
113
- ]
114
- },
115
- "resume_writing": {
116
- "name": "Professional Resume",
117
- "category": "Career Services",
118
- "price": 150,
119
- "description": "ATS-optimized resumes that get interviews",
120
- "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.""",
121
- "fields": [
122
- "Career Level",
123
- "Industry",
124
- "Target Job Title",
125
- "Years of Experience",
126
- "Key Achievements to Highlight"
127
- ]
128
- },
129
- "website_copy": {
130
- "name": "Website Copy",
131
- "category": "Marketing Copy",
132
- "price": 300,
133
- "description": "Conversion-focused website copy that sells",
134
- "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.""",
135
- "fields": [
136
- "Business Type",
137
- "Target Customer Profile",
138
- "Unique Selling Proposition",
139
- "Primary Call-to-Action",
140
- "Brand Voice (Professional/Casual/Authoritative)"
141
- ]
142
- }
143
- }
144
-
145
- def generate_template(self, service_key: str, client_inputs: str) -> Dict:
146
- """Generate professional template using Cerebras-accelerated Llama 3.1 70B"""
147
- if service_key not in self.services:
148
- return {"error": f"Service {service_key} not found"}
149
-
150
- service = self.services[service_key]
151
-
152
- # Create the prompt using Llama 3.1 chat format
153
- prompt = f"""<|begin_of_text|><|start_header_id|>system<|end_header_id|>
154
-
155
- {service["system_prompt"]}
156
-
157
- CRITICAL QUALITY REQUIREMENTS:
158
- - This template is for a professional writing business charging ${service["price"]}
159
- - Zero grammatical errors and perfect formatting
160
- - Include customizable placeholders in [BRACKETS]
161
- - Professional tone appropriate for {service["category"]}
162
- - Must exceed client expectations and justify the investment
163
- - Template should be immediately usable and comprehensive
164
-
165
- <|eot_id|><|start_header_id|>user<|end_header_id|>
166
-
167
- Create a comprehensive {service["name"]} template based on these client requirements:
168
-
169
- {client_inputs}
170
-
171
- Required Information to Address:
172
- {chr(10).join([f"- {field}" for field in service["fields"]])}
173
-
174
- Generate 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.
175
-
176
- <|eot_id|><|start_header_id|>assistant<|end_header_id|>
177
-
178
- """
179
-
180
- try:
181
- # Generate with Cerebras acceleration
182
- response = self.client.text_generation(
183
- prompt=prompt,
184
- max_new_tokens=2048,
185
- temperature=0.3,
186
- do_sample=True,
187
- stop_sequences=["<|eot_id|>"],
188
- return_full_text=False
189
- )
190
-
191
- template_content = response.strip()
192
-
193
- # Quality assessment
194
- quality_metrics = self.assess_quality(template_content)
195
-
196
- return {
197
- "success": True,
198
- "service_name": service["name"],
199
- "category": service["category"],
200
- "template_content": template_content,
201
- "quality_score": quality_metrics["overall_score"],
202
- "word_count": quality_metrics["word_count"],
203
- "estimated_price": service["price"],
204
- "generated_at": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
205
- "model_info": "Llama 3.1 70B Instruct via Cerebras",
206
- "has_placeholders": quality_metrics["has_placeholders"]
207
- }
208
-
209
- except Exception as e:
210
- return {
211
- "success": False,
212
- "error": f"Generation failed: {str(e)}",
213
- "service_name": service["name"]
214
- }
215
-
216
- def assess_quality(self, content: str) -> Dict:
217
- """Assess template quality for professional standards"""
218
- word_count = len(content.split())
219
- has_placeholders = "[" in content and "]" in content
220
- has_structure = any(marker in content.lower() for marker in
221
- ["#", "##", "1.", "2.", "introduction", "conclusion", "structure"])
222
- appropriate_length = word_count >= 150
223
-
224
- # Calculate overall score
225
- quality_factors = [has_placeholders, has_structure, appropriate_length]
226
- score = (sum(quality_factors) / len(quality_factors)) * 100
227
-
228
- return {
229
- "overall_score": round(score, 1),
230
- "word_count": word_count,
231
- "has_placeholders": has_placeholders,
232
- "has_structure": has_structure,
233
- "appropriate_length": appropriate_length
234
- }
235
-
236
- # Initialize the business app
237
- try:
238
- writing_business = ProfessionalWritingBusiness()
239
- print("✅ Professional Writing Business initialized successfully!")
240
- print(f"🚀 Using Cerebras-accelerated Llama 3.1 70B")
241
- except Exception as e:
242
- print(f"❌ Initialization failed: {e}")
243
- writing_business = None
244
-
245
- def create_template_interface():
246
- """Create the main Gradio interface"""
247
-
248
- def generate_writing_template(service_selection, client_requirements):
249
- """Generate template based on service and requirements"""
250
- if not writing_business:
251
- return "❌ Error: System not properly initialized. Check HF_TOKEN.", "", "", ""
252
-
253
- if not service_selection:
254
- return "❌ Please select a writing service first.", "", "", ""
255
-
256
- if not client_requirements.strip():
257
- return "❌ Please provide client requirements.", "", "", ""
258
-
259
- # Generate the template
260
- result = writing_business.generate_template(service_selection, client_requirements)
261
-
262
- if not result.get("success"):
263
- error_msg = result.get("error", "Unknown error occurred")
264
- return f"❌ Generation Error: {error_msg}", "", "", ""
265
-
266
- # Format the successful result
267
- template_output = f"""# {result['service_name']} Template
268
-
269
- **Quality Score:** {result['quality_score']}% • **Word Count:** {result['word_count']} • **Price:** ${result['estimated_price']}
270
-
271
- ## Generated Template:
272
-
273
- {result['template_content']}
274
-
275
- ---
276
- *Generated: {result['generated_at']} using {result['model_info']}*
277
- """
278
-
279
- # Service info
280
- service_info = f"""**Selected Service:** {result['service_name']}
281
- **Category:** {result['category']}
282
- **Estimated Price:** ${result['estimated_price']}
283
- **Quality Score:** {result['quality_score']}%
284
- **Placeholders Included:** {'✅ Yes' if result['has_placeholders'] else '❌ No'}"""
285
-
286
- # Business metrics
287
- metrics = f"""**Template Quality:** {result['quality_score']}%
288
- **Word Count:** {result['word_count']} words
289
- **Generation Speed:** ~3 seconds (Cerebras)
290
- **Model:** Llama 3.1 70B Instruct"""
291
-
292
- # Client guidance
293
- guidance = f"""**Next Steps:**
294
- 1. Review the template for accuracy and completeness
295
- 2. Customize the [PLACEHOLDER] sections with specific client details
296
- 3. Proofread for any client-specific adjustments
297
- 4. Deliver to client with confidence
298
-
299
- **Template Features:**
300
- - Professional structure and formatting
301
- - Industry best practices included
302
- - Customizable placeholders for easy personalization
303
- - Ready for immediate client use"""
304
-
305
- return template_output, service_info, metrics, guidance
306
-
307
- def get_service_info(service_key):
308
- """Get detailed information about selected service"""
309
- if not writing_business or not service_key:
310
- return "Select a service to see details..."
311
-
312
- service = writing_business.services.get(service_key)
313
- if not service:
314
- return "Service not found."
315
-
316
- info = f"""**{service['name']}**
317
-
318
- **Category:** {service['category']}
319
- **Price:** ${service['price']}
320
- **Description:** {service['description']}
321
-
322
- **Required Information:**
323
- {chr(10).join([f"• {field}" for field in service['fields']])}
324
-
325
- **Example Input:**
326
- "Academic Level: Undergraduate
327
- Subject Area: Psychology
328
- Citation Style: APA
329
- Target Word Count: 1500-2000 words
330
- Essay Type: Argumentative"
331
- """
332
- return info
333
-
334
- # Define the interface
335
- with gr.Blocks(
336
- title="Professional Writing Business - AI Template Generator",
337
- theme=gr.themes.Soft(),
338
- css="""
339
- .main-header { text-align: center; margin-bottom: 2rem; }
340
- .service-card { border: 1px solid #e5e7eb; border-radius: 8px; padding: 1rem; }
341
- .quality-badge { background: linear-gradient(45deg, #10b981, #059669); color: white; padding: 0.25rem 0.75rem; border-radius: 1rem; font-weight: bold; }
342
- """
343
- ) as interface:
344
-
345
- gr.Markdown("""
346
- # 🎓✍️ Professional Writing Business - AI Template Generator
347
-
348
- **Powered by Cerebras-Accelerated Llama 3.1 70B** • Lightning-fast generation for premium writing services
349
-
350
- Specializing in **Student Writing** + High-Demand Business Services
351
- """, elem_classes="main-header")
352
-
353
- with gr.Row():
354
- with gr.Column(scale=1):
355
- gr.Markdown("### 📋 Service Selection")
356
-
357
- service_dropdown = gr.Dropdown(
358
- choices=list(writing_business.services.keys()) if writing_business else [],
359
- label="Choose Writing Service",
360
- value=None,
361
- interactive=True
362
- )
363
-
364
- service_info_display = gr.Textbox(
365
- label="Service Information & Requirements",
366
- lines=12,
367
- interactive=False,
368
- placeholder="Select a service above to see details and requirements..."
369
- )
370
-
371
- gr.Markdown("### ✏️ Client Requirements")
372
-
373
- client_input = gr.Textbox(
374
- label="Enter Client Specifications",
375
- lines=8,
376
- placeholder="""Example for Academic Essay:
377
- Academic Level: Undergraduate
378
- Subject Area: Psychology
379
- Citation Style: APA
380
- Target Word Count: 1500-2000 words
381
- Essay Type: Argumentative
382
- Specific Topic: The impact of social media on mental health""",
383
- info="Provide detailed client requirements based on the service information above"
384
- )
385
-
386
- generate_btn = gr.Button(
387
- "🚀 Generate Professional Template",
388
- variant="primary",
389
- size="lg"
390
- )
391
-
392
- with gr.Column(scale=2):
393
- gr.Markdown("### 📄 Generated Template")
394
-
395
- template_output = gr.Textbox(
396
- label="Professional Template",
397
- lines=25,
398
- show_copy_button=True,
399
- placeholder="Your generated template will appear here..."
400
- )
401
-
402
- with gr.Row():
403
- service_metrics = gr.Textbox(
404
- label="📊 Service Details",
405
- lines=6,
406
- interactive=False
407
- )
408
-
409
- generation_metrics = gr.Textbox(
410
- label="⚡ Generation Metrics",
411
- lines=6,
412
- interactive=False
413
- )
414
-
415
- client_guidance = gr.Textbox(
416
- label="📋 Client Delivery Guide",
417
- lines=6,
418
- interactive=False
419
- )
420
-
421
- # Business Dashboard
422
- with gr.Row():
423
- gr.Markdown("""
424
- ### 💼 Business Dashboard
425
-
426
- | **Service Category** | **Services** | **Price Range** | **Specialization** |
427
- |---------------------|--------------|-----------------|-------------------|
428
- | **Student Writing** | 3 Core Services | $150-$250 | Your Primary Focus |
429
- | **Business Writing** | 2 Services | $300-$800 | High-Value Projects |
430
- | **Marketing Copy** | 3 Services | $150-$300 | Quick Turnaround |
431
-
432
- **Total Portfolio Value:** $1,950 per complete cycle • **Generation Speed:** 2-5 seconds • **Quality Standard:** 90%+
433
- """)
434
-
435
- # Event handlers
436
- service_dropdown.change(
437
- fn=get_service_info,
438
- inputs=[service_dropdown],
439
- outputs=[service_info_display]
440
- )
441
-
442
- generate_btn.click(
443
- fn=generate_writing_template,
444
- inputs=[service_dropdown, client_input],
445
- outputs=[template_output, service_metrics, generation_metrics, client_guidance]
446
- )
447
-
448
- return interface
449
-
450
- # Launch the application
451
- if __name__ == "__main__":
452
- print("🚀 Launching Professional Writing Business Template Generator...")
453
-
454
- interface = create_template_interface()
455
-
456
- interface.launch(
457
- server_name="0.0.0.0",
458
- server_port=7860,
459
- share=True,
460
- show_api=False,
461
- show_error=True
462
- )
463
-
464
- print("✅ Application launched successfully!")
465
- print("🎯 Ready to generate professional writing templates!")