rtpeterson02's picture
Upload 2 files
aaaa185 verified
"""
PowerPoint Script Generator for HuggingFace Spaces
Uses HuggingFace Inference API - No local model download required!
Compatible with Gradio 4.x and 6.x
"""
import gradio as gr
from huggingface_hub import InferenceClient
import os
# ============================================================================
# HUGGINGFACE INFERENCE CLIENT SETUP
# ============================================================================
class PPTScriptGenerator:
"""Handles script generation using HuggingFace Inference API"""
def __init__(self):
"""Initialize the inference client"""
# Using the Inference API - no local model needed!
self.client = InferenceClient(
model="tiiuae/Falcon3-1B-Instruct",
token=os.getenv("HF_TOKEN") # HF Spaces automatically provides this
)
print("βœ… Inference client initialized")
def create_prompt(self, topic, num_slides, audience="General audience", tone="Professional"):
"""
Create a structured prompt for PPT script generation
Args:
topic: The presentation topic
num_slides: Number of slides to generate scripts for
audience: Target audience
tone: Presentation tone
Returns:
Formatted prompt string
"""
prompt = f"""You are an expert presentation script writer. Your goal is to create engaging, clear, and well-structured speaker notes for a PowerPoint presentation.
**Presentation Topic**: {topic}
**Number of Slides**: {num_slides}
**Target Audience**: {audience}
**Tone**: {tone}
**Instructions**:
1. Generate a complete script for each slide in the presentation
2. Each slide should have:
- A clear slide title
- Detailed speaker notes (2-4 sentences)
- Key talking points (3-4 bullet points)
- Suggested timing in seconds
3. Ensure smooth transitions between slides
4. Make the content engaging and appropriate for the target audience
5. Use the specified tone throughout
**Output Format**:
For each slide, provide:
---
**Slide [Number]: [Title]**
**Speaker Script**:
[Detailed script with 2-4 sentences that the presenter should say]
**Key Points**:
- [Point 1]
- [Point 2]
- [Point 3]
**Timing**: [Suggested time in seconds]
---
Begin generating the presentation script now:"""
return prompt
def generate_script(self, topic, num_slides=5, audience="General audience",
tone="Professional", temperature=0.7, max_tokens=2000):
"""
Generate the PPT script using HuggingFace Inference API
Args:
topic: Presentation topic
num_slides: Number of slides
audience: Target audience
tone: Presentation tone
temperature: Sampling temperature (0.0-1.0)
max_tokens: Maximum tokens to generate
Returns:
Generated script as string
"""
if not topic or not topic.strip():
return "⚠️ Please enter a presentation topic."
try:
prompt = self.create_prompt(topic, num_slides, audience, tone)
# Generate using the Inference API
response = self.client.text_generation(
prompt,
max_new_tokens=max_tokens,
temperature=temperature,
top_p=0.9,
repetition_penalty=1.1,
do_sample=True,
return_full_text=False
)
return response.strip()
except Exception as e:
error_msg = f"❌ Error generating script: {str(e)}\n\n"
error_msg += "πŸ’‘ This might be due to:\n"
error_msg += "- High server load (try again in a moment)\n"
error_msg += "- Topic complexity (try a simpler topic)\n"
error_msg += "- Token limit exceeded (reduce number of slides)\n"
return error_msg
# ============================================================================
# GRADIO INTERFACE FOR HUGGINGFACE SPACES
# ============================================================================
def create_interface():
"""Create the Gradio UI optimized for HuggingFace Spaces"""
# Initialize the generator
generator = PPTScriptGenerator()
# Welcome message
welcome_html = """
<div style="text-align: center; padding: 20px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); border-radius: 10px; margin-bottom: 20px;">
<h1 style="color: white; margin: 0; font-size: 2.5em;">🎀 PowerPoint Script Generator</h1>
<p style="color: #f0f0f0; font-size: 1.2em; margin-top: 10px;">
Powered by Falcon3-1B-Instruct
</p>
<p style="color: #e0e0e0; font-size: 0.9em; margin-top: 5px;">
Generate professional presentation scripts in seconds ✨
</p>
</div>
"""
# Instructions
instructions_html = """
<div style="background: #f8f9fa; padding: 15px; border-radius: 8px; margin-bottom: 20px; border-left: 4px solid #667eea;">
<h3 style="margin-top: 0; color: #667eea;">πŸ“‹ How to Use:</h3>
<ol style="margin-bottom: 0;">
<li><strong>Enter your topic</strong> - Be specific about what you want to present</li>
<li><strong>Choose number of slides</strong> - Select 3-10 slides</li>
<li><strong>Select audience & tone</strong> - Customize for your needs</li>
<li><strong>Click Generate</strong> - Wait 10-30 seconds for your script</li>
</ol>
</div>
"""
def generate_wrapper(topic, num_slides, audience, tone, temperature, max_tokens):
"""Wrapper function for Gradio"""
if not topic.strip():
return "⚠️ Please enter a presentation topic."
# Show generating message
yield "πŸ”„ Generating your presentation script...\n\nThis may take 10-30 seconds depending on server load.\n\nPlease wait..."
# Generate script
script = generator.generate_script(
topic=topic,
num_slides=num_slides,
audience=audience,
tone=tone,
temperature=temperature,
max_tokens=max_tokens
)
yield script
# Create interface using Blocks
with gr.Blocks(title="PPT Script Generator") as demo:
gr.HTML(welcome_html)
gr.HTML(instructions_html)
with gr.Row():
with gr.Column(scale=1):
gr.Markdown("### πŸ“ Input Configuration")
# Main inputs
topic_input = gr.Textbox(
label="πŸ“Œ Presentation Topic",
placeholder="e.g., Introduction to Artificial Intelligence in Healthcare",
lines=3
)
num_slides = gr.Slider(
minimum=3,
maximum=10,
value=5,
step=1,
label="πŸ“Š Number of Slides"
)
audience = gr.Dropdown(
choices=[
"General audience",
"Business executives",
"Technical professionals",
"Students",
"Healthcare professionals",
"Marketing professionals",
"Investors",
"Academic researchers"
],
value="General audience",
label="πŸ‘₯ Target Audience"
)
tone = gr.Dropdown(
choices=[
"Professional",
"Casual and friendly",
"Technical and detailed",
"Inspirational",
"Educational",
"Persuasive"
],
value="Professional",
label="🎨 Presentation Tone"
)
# Advanced settings
with gr.Accordion("βš™οΈ Advanced Settings", open=False):
temperature = gr.Slider(
minimum=0.3,
maximum=0.9,
value=0.7,
step=0.1,
label="🌑️ Temperature"
)
max_tokens = gr.Slider(
minimum=1000,
maximum=3000,
value=2000,
step=100,
label="πŸ“ Max Tokens"
)
# Generate button
generate_btn = gr.Button(
"πŸš€ Generate Presentation Script",
variant="primary"
)
# Example topics
gr.Markdown("### πŸ’‘ Example Topics:")
gr.Examples(
examples=[
["The Future of Renewable Energy", 5, "Business executives", "Professional"],
["Introduction to Machine Learning", 7, "Students", "Educational"],
["Quarterly Sales Performance Review", 4, "Business executives", "Professional"],
["Cybersecurity Best Practices for Small Businesses", 6, "Technical professionals", "Technical and detailed"],
["Building a Strong Company Culture", 5, "Business executives", "Inspirational"]
],
inputs=[topic_input, num_slides, audience, tone]
)
with gr.Column(scale=1):
gr.Markdown("### πŸ“„ Generated Script")
output = gr.Textbox(
label="Presentation Script",
lines=30,
placeholder="Your generated presentation script will appear here...\n\n⏱️ Generation typically takes 10-30 seconds.",
interactive=False
)
# Tips section
with gr.Accordion("πŸ’‘ Tips for Best Results", open=False):
gr.Markdown("""
**Best Practices:**
- πŸ“– Be specific in your topic description
- 🎯 Choose appropriate audience and tone
- ⏱️ Use 3-7 slides for best results
- πŸ”„ Try different temperatures for variety
- ✏️ Review and customize the output
- 🎀 Practice with the suggested timings
**If generation fails:**
- Wait a moment and try again (server might be busy)
- Simplify your topic
- Reduce number of slides
- Lower max tokens to 1500
""")
# Connect the button to the function
generate_btn.click(
fn=generate_wrapper,
inputs=[topic_input, num_slides, audience, tone, temperature, max_tokens],
outputs=output
)
# Footer
gr.Markdown("""
---
<div style="text-align: center; color: #666; font-size: 0.9em;">
<p>πŸ€– Powered by <strong>Falcon3-1B-Instruct</strong> via HuggingFace Inference API</p>
<p>Built with ❀️ using Gradio | No local model download required!</p>
</div>
""")
return demo
# ============================================================================
# MAIN EXECUTION
# ============================================================================
if __name__ == "__main__":
print("="*80)
print("🎀 PowerPoint Script Generator - HuggingFace Spaces Version")
print("="*80)
print("\nπŸš€ Launching Gradio interface...")
print("="*80)
# Create and launch the interface
demo = create_interface()
# Launch with appropriate settings
demo.launch(
show_error=True
)