"""
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 = """
š¤ PowerPoint Script Generator
Powered by Falcon3-1B-Instruct
Generate professional presentation scripts in seconds āØ
"""
# Instructions
instructions_html = """
š How to Use:
- Enter your topic - Be specific about what you want to present
- Choose number of slides - Select 3-10 slides
- Select audience & tone - Customize for your needs
- Click Generate - Wait 10-30 seconds for your script
"""
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("""
---
š¤ Powered by Falcon3-1B-Instruct via HuggingFace Inference API
Built with ā¤ļø using Gradio | No local model download required!
""")
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
)