Download app.py from mgbam/naso: direct link, hf CLI and curl.
- Browser
- Download file 20.4 kB
-
https://huggingface.co/spaces/mgbam/naso/resolve/70f392097d206b86332c150154c8e21e37cae0a2/app.py
- Command line
-
hf download hf://spaces/mgbam/naso@70f392097d206b86332c150154c8e21e37cae0a2/app.py
-
curl -L -o app.py https://huggingface.co/spaces/mgbam/naso/resolve/70f392097d206b86332c150154c8e21e37cae0a2/app.py
20.4 kB
| import os | |
| import json | |
| import requests | |
| from dotenv import load_dotenv | |
| from openai import OpenAI | |
| from flask import Flask, render_template_string, request | |
| # Load environment variables | |
| load_dotenv() | |
| # Initialize API clients | |
| OPENAI_API_KEY = os.getenv("OPENAI_API_KEY") | |
| openai_client = OpenAI(api_key=OPENAI_API_KEY) if OPENAI_API_KEY else None | |
| ELEVENLABS_API_KEY = os.getenv("ELEVENLABS_API_KEY") | |
| app = Flask(__name__) | |
| # ---------- Agent implementations ---------- | |
| class TopicAgent: | |
| def generate_outline(self, topic, duration, difficulty): | |
| if not openai_client: | |
| print("OpenAI API not set - using enhanced mock data for outline.") | |
| return self._mock_outline(topic, duration, difficulty) | |
| try: | |
| response = openai_client.chat.completions.create( | |
| model="gpt-4-turbo", | |
| messages=[ | |
| { | |
| "role": "system", | |
| "content": ( | |
| "You are an expert corporate trainer with 20+ years of experience creating " | |
| "high-value workshops for Fortune 500 companies. Create a professional workshop outline that " | |
| "includes: 1) Clear learning objectives, 2) Practical real-world exercises, " | |
| "3) Industry case studies, 4) Measurable outcomes. Format as JSON." | |
| ) | |
| }, | |
| { | |
| "role": "user", | |
| "content": ( | |
| f"Create a comprehensive {duration}-hour {difficulty} workshop outline on '{topic}' for corporate executives. " | |
| "Structure: title, duration, difficulty, learning_goals (3-5 bullet points), " | |
| "modules (5-7 modules). Each module should have: title, duration, learning_points (3 bullet points), " | |
| "case_study (real company example), exercises (2 practical exercises)." | |
| ) | |
| } | |
| ], | |
| temperature=0.3, | |
| max_tokens=1500, | |
| response_format={"type": "json_object"} | |
| ) | |
| return json.loads(response.choices[0].message.content) | |
| except Exception as e: | |
| print(f"Error during OpenAI outline generation: {e}. Falling back to mock outline.") | |
| return self._mock_outline(topic, duration, difficulty) | |
| def _mock_outline(self, topic, duration, difficulty): | |
| return { | |
| "title": f"Mastering {topic} for Business Impact", | |
| "duration": f"{duration} hours", | |
| "difficulty": difficulty, | |
| "learning_goals": [ | |
| "Apply advanced techniques to real business challenges", | |
| "Measure ROI of prompt engineering initiatives", | |
| "Develop organizational prompt engineering standards", | |
| "Implement ethical AI governance frameworks" | |
| ], | |
| "modules": [ | |
| { | |
| "title": "Strategic Foundations", | |
| "duration": "45 min", | |
| "learning_points": [ | |
| "Business value assessment framework", | |
| "ROI calculation models", | |
| "Stakeholder alignment strategies" | |
| ], | |
| "case_study": "How JPMorgan reduced operational costs by 37% with prompt optimization", | |
| "exercises": [ | |
| "Calculate potential ROI for your organization", | |
| "Develop stakeholder communication plan" | |
| ] | |
| }, | |
| { | |
| "title": "Advanced Pattern Engineering", | |
| "duration": "60 min", | |
| "learning_points": [ | |
| "Chain-of-thought implementations", | |
| "Self-correcting prompt architectures", | |
| "Domain-specific pattern libraries" | |
| ], | |
| "case_study": "McKinsey's knowledge management transformation", | |
| "exercises": [ | |
| "Design pattern library for your industry", | |
| "Implement self-correction workflow" | |
| ] | |
| } | |
| ] | |
| } | |
| class ContentAgent: | |
| def generate_content(self, outline): | |
| if not openai_client: | |
| print("OpenAI API not set - using enhanced mock data for content.") | |
| return self._mock_content(outline) | |
| try: | |
| response = openai_client.chat.completions.create( | |
| model="gpt-4-turbo", | |
| messages=[ | |
| { | |
| "role": "system", | |
| "content": ( | |
| "You are a senior instructional designer creating premium corporate training materials. " | |
| "Develop comprehensive workshop content with: 1) Practitioner-level insights, " | |
| "2) Actionable frameworks, 3) Real-world examples, 4) Practical exercises. " | |
| "Avoid generic AI content - focus on business impact." | |
| ) | |
| }, | |
| { | |
| "role": "user", | |
| "content": ( | |
| f"Create premium workshop content for this outline: {json.dumps(outline)}. " | |
| "For each module: " | |
| "1) Detailed script (executive summary, 3 key concepts, business applications) " | |
| "2) Speaker notes (presentation guidance) " | |
| "3) 3 discussion questions with executive-level responses " | |
| "4) 2 practical exercises with solution blueprints " | |
| "Format as JSON." | |
| ) | |
| } | |
| ], | |
| temperature=0.4, | |
| max_tokens=3000, | |
| response_format={"type": "json_object"} | |
| ) | |
| return json.loads(response.choices[0].message.content) | |
| except Exception as e: | |
| print(f"Error during OpenAI content generation: {e}. Falling back to mock content.") | |
| return self._mock_content(outline) | |
| def _mock_content(self, outline): | |
| return { | |
| "workshop_title": outline.get("title", "Premium AI Workshop"), | |
| "modules": [ | |
| { | |
| "title": "Strategic Foundations", | |
| "script": ( | |
| "## Executive Summary\n" | |
| "This module establishes the business case for advanced prompt engineering, " | |
| "focusing on measurable ROI and stakeholder alignment.\n\n" | |
| "### Key Concepts:\n" | |
| "1. **Value Assessment Framework**: Quantify potential savings and revenue opportunities\n" | |
| "2. **ROI Calculation Models**: Custom models for different industries\n" | |
| "3. **Stakeholder Alignment**: Executive communication strategies\n\n" | |
| "### Business Applications:\n" | |
| "- Cost reduction in customer service operations\n" | |
| "- Acceleration of R&D processes\n" | |
| "- Enhanced competitive intelligence" | |
| ), | |
| "speaker_notes": [ | |
| "Emphasize real dollar impact - use JPMorgan case study numbers", | |
| "Show ROI calculator template", | |
| "Highlight C-suite communication strategies" | |
| ], | |
| "discussion_questions": [ | |
| { | |
| "question": "How could prompt engineering impact your bottom line?", | |
| "response": "Typical results: 30-40% operational efficiency gains, 15-25% innovation acceleration" | |
| } | |
| ], | |
| "exercises": [ | |
| { | |
| "title": "ROI Calculation Workshop", | |
| "instructions": "Calculate potential savings using our enterprise ROI model", | |
| "solution": "Template: (Current Cost × Efficiency Gain) - Implementation Cost" | |
| } | |
| ] | |
| } | |
| ] | |
| } | |
| class SlideAgent: | |
| def generate_slides(self, content): | |
| if not openai_client: | |
| print("OpenAI API not set - using enhanced mock slides.") | |
| return self._professional_slides(content) | |
| try: | |
| response = openai_client.chat.completions.create( | |
| model="gpt-4-turbo", | |
| messages=[ | |
| { | |
| "role": "system", | |
| "content": ( | |
| "You are a McKinsey-level presentation specialist. Create professional slides with: " | |
| "1) Clean, executive-friendly design 2) Data visualization frameworks " | |
| "3) Action-oriented content 4) Brand-compliant styling. " | |
| "Use Marp Markdown format with the 'gaia' theme." | |
| ) | |
| }, | |
| { | |
| "role": "user", | |
| "content": ( | |
| f"Create a boardroom-quality slide deck for: {json.dumps(content)}. " | |
| "Structure: Title slide, module slides (objective, 3 key points, case study, exercise), " | |
| "summary slide. Include placeholders for data visualization." | |
| ) | |
| } | |
| ], | |
| temperature=0.2, | |
| max_tokens=2500 | |
| ) | |
| return response.choices[0].message.content | |
| except Exception as e: | |
| print(f"Error during slide generation: {e}. Using mock slides.") | |
| return self._professional_slides(content) | |
| def _professional_slides(self, content): | |
| return f"""--- | |
| marp: true | |
| theme: gaia | |
| class: lead | |
| paginate: true | |
| backgroundColor: #fff | |
| backgroundImage: url('https://marp.app/assets/hero-background.svg') | |
| --- | |
| # {content.get('workshop_title', 'Executive AI Workshop')} | |
| ## Transforming Business Through Advanced AI | |
| --- | |
| <!-- _class: invert --> | |
| ## Module 1: Strategic Foundations | |
| ### Driving Measurable Business Value | |
|  | |
| - **ROI Framework**: Quantifying impact | |
| - **Stakeholder Alignment**: Executive buy-in strategies | |
| - **Implementation Roadmap**: Phased adoption plan | |
| --- | |
| ## Case Study: Financial Services Transformation | |
| ### JPMorgan Chase | |
| | Metric | Before | After | Improvement | | |
| |--------|--------|-------|-------------| | |
| | Operation Costs | $4.2M | $2.6M | 38% reduction | | |
| | Process Time | 14 days | 3 days | 79% faster | | |
| | Error Rate | 8.2% | 0.4% | 95% reduction | | |
| --- | |
| ## Practical Exercise: ROI Calculation | |
| ```mermaid | |
| graph TD | |
| A[Current Costs] --> B[Potential Savings] | |
| C[Implementation Costs] --> D[Net ROI] | |
| B --> D | |
| Document current process costs | |
| Estimate efficiency gains | |
| Calculate net ROI | |
| Q&A | |
| Let's discuss your specific challenges | |
| ```""" | |
| class CodeAgent: | |
| def generate_code(self, content): | |
| if not openai_client: | |
| print("OpenAI API not set - using enhanced mock code.") | |
| return self._professional_code(content) | |
| try: | |
| response = openai_client.chat.completions.create( | |
| model="gpt-4-turbo", | |
| messages=[ | |
| { | |
| "role": "system", | |
| "content": ( | |
| "You are an enterprise solutions architect. Create professional-grade code labs with: " | |
| "1) Production-ready patterns 2) Comprehensive documentation " | |
| "3) Enterprise security practices 4) Scalable architectures. " | |
| "Use Python with the latest best practices." | |
| ) | |
| }, | |
| { | |
| "role": "user", | |
| "content": ( | |
| f"Create a professional code lab for: {json.dumps(content)}. " | |
| "Include: Setup instructions, business solution patterns, " | |
| "enterprise integration examples, and security best practices." | |
| ) | |
| } | |
| ], | |
| temperature=0.3, | |
| max_tokens=2500 | |
| ) | |
| return response.choices[0].message.content | |
| except Exception as e: | |
| print(f"Error during code generation: {e}. Using mock code.") | |
| return self._professional_code(content) | |
| def _professional_code(self, content): | |
| return f"""# Enterprise-Grade Prompt Engineering Lab | |
| # Business Solution Framework | |
| class PromptOptimizer: | |
| def __init__(self, model="gpt-4-turbo"): | |
| self.model = model | |
| self.pattern_library = {{ | |
| "financial_analysis": "Extract key metrics from financial reports", | |
| "customer_service": "Resolve tier-2 support tickets" | |
| }} | |
| def optimize_prompt(self, business_case): | |
| # Implement enterprise optimization logic | |
| return f"Business-optimized prompt for {{business_case}}" | |
| def calculate_roi(self, current_cost, expected_efficiency): | |
| return current_cost * expected_efficiency | |
| # Example usage | |
| optimizer = PromptOptimizer() | |
| print(optimizer.calculate_roi(500000, 0.35)) # $175,000 savings | |
| # Security Best Practices | |
| def secure_prompt_handling(user_input): | |
| # Implement OWASP security standards | |
| sanitized = sanitize_input(user_input) | |
| validate_business_context(sanitized) | |
| return apply_enterprise_guardrails(sanitized) | |
| # Integration Pattern: CRM System | |
| def integrate_with_salesforce(prompt, salesforce_data): | |
| # Enterprise integration example | |
| enriched_prompt = f"{{prompt}} using {{salesforce_data}}" | |
| return call_ai_api(enriched_prompt) | |
| """ | |
| class DesignAgent: | |
| def generate_design(self, slide_content): | |
| if not openai_client: | |
| print("OpenAI API not set - skipping design generation.") | |
| return None | |
| try: | |
| response = openai_client.images.generate( | |
| model="dall-e-3", | |
| prompt=( | |
| f"Professional corporate slide background for '{slide_content[:200]}' workshop. " | |
| "Modern business style, clean lines, premium gradient, boardroom appropriate. " | |
| "Include abstract technology elements in corporate colors." | |
| ), | |
| n=1, | |
| size="1024x1024" | |
| ) | |
| return response.data[0].url | |
| except Exception as e: | |
| print(f"Error during design generation: {e}.") | |
| return None | |
| class VoiceoverAgent: | |
| def __init__(self): | |
| self.api_key = ELEVENLABS_API_KEY | |
| self.voice_id = "21m00Tcm4TlvDq8ikWAM" # Default voice ID | |
| self.model = "eleven_monolingual_v1" | |
| def generate_voiceover(self, text, voice_id=None): | |
| if not self.api_key: | |
| print("ElevenLabs API key not set - skipping voiceover generation.") | |
| return None | |
| try: | |
| voice = voice_id if voice_id else self.voice_id | |
| url = f"https://api.elevenlabs.io/v1/text-to-speech/{voice}" | |
| headers = { | |
| "Accept": "audio/mpeg", | |
| "Content-Type": "application/json", | |
| "xi-api-key": self.api_key | |
| } | |
| data = { | |
| "text": text, | |
| "model_id": self.model, | |
| "voice_settings": { | |
| "stability": 0.7, | |
| "similarity_boost": 0.8, | |
| "style": 0.5, | |
| "use_speaker_boost": True | |
| } | |
| } | |
| response = requests.post(url, json=data, headers=headers) | |
| response.raise_for_status() | |
| return response.content | |
| except requests.exceptions.RequestException as e: | |
| print(f"Error generating voiceover: {e}") | |
| return None | |
| def get_voices(self): | |
| if not self.api_key: | |
| print("ElevenLabs API key not set - cannot fetch voices.") | |
| return [] | |
| try: | |
| url = "https://api.elevenlabs.io/v1/voices" | |
| headers = {"xi-api-key": self.api_key} | |
| response = requests.get(url, headers=headers) | |
| response.raise_for_status() | |
| return response.json().get("voices", []) | |
| except requests.exceptions.RequestException as e: | |
| print(f"Error fetching voices: {e}") | |
| return [] | |
| # ---------- Simple frontend to show workshop focus input ---------- | |
| HTML_PAGE = """ | |
| <!doctype html> | |
| <html lang="en"> | |
| <head> | |
| <meta charset="utf-8" /> | |
| <title>Executive Workshop Configuration</title> | |
| <meta name="viewport" content="width=device-width,initial-scale=1" /> | |
| <style> | |
| body { font-family: system-ui,-apple-system,BlinkMacSystemFont,sans-serif; background:#f0f4f8; padding:30px; } | |
| .card { background:#fff; padding:20px; border-radius:12px; max-width:500px; margin:auto; box-shadow:0 10px 25px rgba(0,0,0,0.05); } | |
| h1 { font-size:1.75rem; margin-bottom:4px; display:flex; align-items:center; gap:8px; } | |
| label { display:block; margin-top:16px; font-weight:600; } | |
| input { width:100%; padding:10px 14px; border:1px solid #cbd5e1; border-radius:6px; font-size:1rem; transition: all .2s; color:#1f2937; background:#fff; } | |
| input:focus { outline:none; border-color:#2563eb; box-shadow:0 0 0 3px rgba(59,130,246,0.35); } | |
| input::placeholder { color:#94a3b8; } | |
| ::selection { background: rgba(59,130,246,0.4); color:#000; } | |
| .status { margin-bottom:12px; padding:12px; border-radius:8px; } | |
| .warn { background:#fff8e1; border:1px solid #f5e1a4; color:#886f1b; } | |
| .ok { background:#e6f6ed; border:1px solid #b8e0c5; color:#1e5f3d; } | |
| .note { margin-top:8px; font-size:.9rem; color:#475569; } | |
| </style> | |
| </head> | |
| <body> | |
| <div class="card"> | |
| <div class="status {{ 'ok' if openai_set else 'warn' }}"> | |
| {% if openai_set %} | |
| <div class="ok">OpenAI API Key Found</div> | |
| {% else %} | |
| <div class="warn">OpenAI API not set - using enhanced mock data</div> | |
| {% endif %} | |
| {% if elevenlabs_set %} | |
| <div class="ok" style="margin-top:6px;">ElevenLabs API Key Found</div> | |
| {% else %} | |
| <div class="warn" style="margin-top:6px;">ElevenLabs API Key not set</div> | |
| {% endif %} | |
| </div> | |
| <h1>Executive Workshop Configuration</h1> | |
| <form method="post" action="/submit"> | |
| <label for="focus">Workshop Focus</label> | |
| <input id="focus" name="focus" placeholder="e.g., AI-Driven Business Transformation" value="{{ prefill }}" autocomplete="off" /> | |
| <div class="note">Type here to set the workshop's focus. Selection and text are styled for clarity.</div> | |
| <button type="submit" style="margin-top:16px; padding:10px 16px; border:none; background:#2563eb; color:#fff; border-radius:6px; cursor:pointer;">Save</button> | |
| </form> | |
| </div> | |
| </body> | |
| </html> | |
| """ | |
| def index(): | |
| return render_template_string( | |
| HTML_PAGE, | |
| openai_set=bool(OPENAI_API_KEY), | |
| elevenlabs_set=bool(ELEVENLABS_API_KEY), | |
| prefill="" | |
| ) | |
| def submit(): | |
| focus = request.form.get("focus", "") | |
| # For demo: echo back with prefill | |
| return render_template_string( | |
| HTML_PAGE, | |
| openai_set=bool(OPENAI_API_KEY), | |
| elevenlabs_set=bool(ELEVENLABS_API_KEY), | |
| prefill=focus | |
| ) | |
| if __name__ == "__main__": | |
| print(f"Loaded OPENAI_API_KEY: {bool(OPENAI_API_KEY)}, ELEVENLABS_API_KEY: {bool(ELEVENLABS_API_KEY)}") | |
| # Disable the reloader to avoid the signal-in-non-main-thread error | |
| app.run(host="0.0.0.0", port=8080, debug=True, use_reloader=False) | |