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import os
|
| 5 |
+
import io
|
| 6 |
+
from reportlab.lib.pagesizes import letter
|
| 7 |
+
from reportlab.pdfgen import canvas
|
| 8 |
+
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer
|
| 9 |
+
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
|
| 10 |
+
from reportlab.lib.units import inch
|
| 11 |
+
import speech_recognition as sr
|
| 12 |
+
|
| 13 |
+
# xAI API setup - SECURE DUMMY PLACEHOLDER
|
| 14 |
+
API_KEY = os.getenv("XAI_API_KEY", "your-xai-api-key-here")
|
| 15 |
+
if API_KEY == "your-xai-api-key-here":
|
| 16 |
+
print("π API Key: Using placeholder - replace with your actual xAI API key")
|
| 17 |
+
|
| 18 |
+
API_URL = "https://api.x.ai/v1/chat/completions"
|
| 19 |
+
|
| 20 |
+
# Expanded stars list
|
| 21 |
+
STARS = [
|
| 22 |
+
"Tom Hanks", "Meryl Streep", "Leonardo DiCaprio", "Emma Watson",
|
| 23 |
+
"Chris Hemsworth", "Scarlett Johansson", "Denzel Washington", "Zendaya",
|
| 24 |
+
"Ryan Reynolds", "Margot Robbie", "Brad Pitt", "Viola Davis",
|
| 25 |
+
"Keanu Reeves", "Florence Pugh", "Pedro Pascal", "Anya Taylor-Joy"
|
| 26 |
+
]
|
| 27 |
+
|
| 28 |
+
def speech_to_text(audio):
|
| 29 |
+
"""Convert audio to text using Google STT."""
|
| 30 |
+
if audio is None:
|
| 31 |
+
return ""
|
| 32 |
+
r = sr.Recognizer()
|
| 33 |
+
try:
|
| 34 |
+
if isinstance(audio, tuple):
|
| 35 |
+
audio_path = audio[1]
|
| 36 |
+
else:
|
| 37 |
+
audio_path = audio
|
| 38 |
+
|
| 39 |
+
with sr.AudioFile(audio_path) as source:
|
| 40 |
+
audio_data = r.record(source)
|
| 41 |
+
text = r.recognize_google(audio_data)
|
| 42 |
+
return text
|
| 43 |
+
except sr.UnknownValueError:
|
| 44 |
+
return "π Couldn't understand audio. Please try speaking clearly."
|
| 45 |
+
except sr.RequestError as e:
|
| 46 |
+
return f"π€ Speech service error: {str(e)}"
|
| 47 |
+
except Exception as e:
|
| 48 |
+
return f"β οΈ Audio processing error: {str(e)}"
|
| 49 |
+
|
| 50 |
+
def generate_sequel(original_plot, continuation_point, selected_stars, custom_star, word_count):
|
| 51 |
+
"""Generate story with Grok-4."""
|
| 52 |
+
if not API_KEY or API_KEY == "your-xai-api-key-here":
|
| 53 |
+
return "π API key not configured. Please set XAI_API_KEY environment variable with your actual xAI API key.", None, None
|
| 54 |
+
|
| 55 |
+
if not original_plot.strip():
|
| 56 |
+
return "π Please provide an original plot to continue from!", None, None
|
| 57 |
+
|
| 58 |
+
# Build cast description
|
| 59 |
+
cast_parts = []
|
| 60 |
+
if selected_stars:
|
| 61 |
+
cast_parts.append(f"Starring: {', '.join(selected_stars)}")
|
| 62 |
+
if custom_star.strip():
|
| 63 |
+
cast_parts.append(f"Introducing: {custom_star}")
|
| 64 |
+
|
| 65 |
+
stars_section = " ".join(cast_parts) if cast_parts else "Featuring an all-star cast."
|
| 66 |
+
|
| 67 |
+
# Smart token calculation
|
| 68 |
+
max_tokens = max(100, min(3000, int(word_count * 1.3)))
|
| 69 |
+
|
| 70 |
+
prompt = f"""You are an award-winning screenwriter crafting the perfect sequel.
|
| 71 |
+
|
| 72 |
+
ORIGINAL STORY: "{original_plot}"
|
| 73 |
+
CONTINUATION POINT: "{continuation_point}"
|
| 74 |
+
CAST: {stars_section}
|
| 75 |
+
|
| 76 |
+
Create an engaging sequel that honors the original while bringing fresh excitement.
|
| 77 |
+
Target length: approximately {word_count} words.
|
| 78 |
+
|
| 79 |
+
STRUCTURE:
|
| 80 |
+
- TITLE: [Catchy sequel title]
|
| 81 |
+
- LOGLINE: [One-sentence premise]
|
| 82 |
+
- ACT 1: [Setup and character reintroduction]
|
| 83 |
+
- ACT 2: [Rising action with meaningful twists]
|
| 84 |
+
- ACT 3: [Satisfying climax and resolution]
|
| 85 |
+
- POST-CREDITS TEASER: [Hint at future adventures]
|
| 86 |
+
|
| 87 |
+
Include memorable dialogue moments and character development. Balance nostalgia with innovation.
|
| 88 |
+
"""
|
| 89 |
+
|
| 90 |
+
headers = {
|
| 91 |
+
"Authorization": f"Bearer {API_KEY}",
|
| 92 |
+
"Content-Type": "application/json"
|
| 93 |
+
}
|
| 94 |
+
data = {
|
| 95 |
+
"model": "grok-4",
|
| 96 |
+
"messages": [{"role": "user", "content": prompt}],
|
| 97 |
+
"max_tokens": max_tokens,
|
| 98 |
+
"temperature": 0.85,
|
| 99 |
+
"top_p": 0.9
|
| 100 |
+
}
|
| 101 |
+
|
| 102 |
+
try:
|
| 103 |
+
response = requests.post(API_URL, headers=headers, json=data, timeout=60)
|
| 104 |
+
response.raise_for_status()
|
| 105 |
+
story = response.json()["choices"][0]["message"]["content"]
|
| 106 |
+
return story, gr.update(visible=True), gr.update(visible=False)
|
| 107 |
+
except requests.exceptions.Timeout:
|
| 108 |
+
return "β° API timeout - try again with a shorter word count.", None, None
|
| 109 |
+
except Exception as e:
|
| 110 |
+
return f"π API error: {str(e)}", None, None
|
| 111 |
+
|
| 112 |
+
def create_pdf(story_text):
|
| 113 |
+
"""Generate a well-formatted PDF from story text."""
|
| 114 |
+
if not story_text or "API" in story_text or "Please provide" in story_text:
|
| 115 |
+
return None, None
|
| 116 |
+
|
| 117 |
+
buffer = io.BytesIO()
|
| 118 |
+
doc = SimpleDocTemplate(buffer, pagesize=letter,
|
| 119 |
+
topMargin=0.5*inch, bottomMargin=0.5*inch,
|
| 120 |
+
leftMargin=0.5*inch, rightMargin=0.5*inch)
|
| 121 |
+
|
| 122 |
+
styles = getSampleStyleSheet()
|
| 123 |
+
title_style = ParagraphStyle(
|
| 124 |
+
'CustomTitle',
|
| 125 |
+
parent=styles['Heading1'],
|
| 126 |
+
fontSize=16,
|
| 127 |
+
spaceAfter=12,
|
| 128 |
+
textColor='#2E86AB'
|
| 129 |
+
)
|
| 130 |
+
body_style = ParagraphStyle(
|
| 131 |
+
'CustomBody',
|
| 132 |
+
parent=styles['BodyText'],
|
| 133 |
+
fontSize=11,
|
| 134 |
+
spaceAfter=6,
|
| 135 |
+
leading=14
|
| 136 |
+
)
|
| 137 |
+
|
| 138 |
+
story_parts = []
|
| 139 |
+
|
| 140 |
+
# Add title
|
| 141 |
+
story_parts.append(Paragraph("π¬ AI-Generated Sequel Story", title_style))
|
| 142 |
+
story_parts.append(Spacer(1, 0.2*inch))
|
| 143 |
+
|
| 144 |
+
# Process story text with basic formatting
|
| 145 |
+
lines = story_text.split('\n')
|
| 146 |
+
for line in lines:
|
| 147 |
+
line = line.strip()
|
| 148 |
+
if not line:
|
| 149 |
+
continue
|
| 150 |
+
if any(marker in line for marker in ['TITLE:', 'LOGLINE:', 'ACT 1:', 'ACT 2:', 'ACT 3:', 'TEASER:']):
|
| 151 |
+
story_parts.append(Paragraph(f"<b>{line}</b>", body_style))
|
| 152 |
+
else:
|
| 153 |
+
story_parts.append(Paragraph(line, body_style))
|
| 154 |
+
story_parts.append(Spacer(1, 0.1*inch))
|
| 155 |
+
|
| 156 |
+
try:
|
| 157 |
+
doc.build(story_parts)
|
| 158 |
+
buffer.seek(0)
|
| 159 |
+
return buffer.getvalue(), "sequel_story.pdf"
|
| 160 |
+
except Exception as e:
|
| 161 |
+
print(f"PDF generation error: {e}")
|
| 162 |
+
return None, None
|
| 163 |
+
|
| 164 |
+
# Gradio UI
|
| 165 |
+
with gr.Blocks(
|
| 166 |
+
title="IdeaForge Studio - Voice your vision. Forge the future.",
|
| 167 |
+
theme=gr.themes.Soft(),
|
| 168 |
+
css="""
|
| 169 |
+
.gradio-container {
|
| 170 |
+
max-width: 1200px !important;
|
| 171 |
+
}
|
| 172 |
+
"""
|
| 173 |
+
) as demo:
|
| 174 |
+
gr.Markdown("""
|
| 175 |
+
# π¬ IdeaForge Studio
|
| 176 |
+
*Voice your vision. Forge the future.*
|
| 177 |
+
""")
|
| 178 |
+
|
| 179 |
+
gr.Markdown("""
|
| 180 |
+
**How it works:**
|
| 181 |
+
1. π Provide the original story (text or voice)
|
| 182 |
+
2. π― Set where the sequel begins
|
| 183 |
+
3. π Cast your stars
|
| 184 |
+
4. π Choose story depth
|
| 185 |
+
5. π Generate & export!
|
| 186 |
+
""")
|
| 187 |
+
|
| 188 |
+
with gr.Tabs():
|
| 189 |
+
with gr.TabItem("π€ Voice Input"):
|
| 190 |
+
with gr.Row():
|
| 191 |
+
with gr.Column(scale=2):
|
| 192 |
+
audio_input = gr.Audio(
|
| 193 |
+
sources=["microphone"],
|
| 194 |
+
type="filepath",
|
| 195 |
+
label="Record Original Plot"
|
| 196 |
+
)
|
| 197 |
+
with gr.Column(scale=3):
|
| 198 |
+
plot_text = gr.Textbox(
|
| 199 |
+
label="Transcribed Plot",
|
| 200 |
+
interactive=True,
|
| 201 |
+
lines=3,
|
| 202 |
+
placeholder="Your spoken plot will appear here..."
|
| 203 |
+
)
|
| 204 |
+
voice_btn = gr.Button("π€ Transcribe Voice", variant="secondary")
|
| 205 |
+
voice_btn.click(speech_to_text, inputs=audio_input, outputs=plot_text)
|
| 206 |
+
|
| 207 |
+
with gr.TabItem("π Text Input"):
|
| 208 |
+
plot_text = gr.Textbox(
|
| 209 |
+
label="Original Plot/Theme",
|
| 210 |
+
placeholder="E.g., 'A young wizard discovers his magical heritage and must defeat the dark lord who killed his parents'",
|
| 211 |
+
lines=4
|
| 212 |
+
)
|
| 213 |
+
|
| 214 |
+
with gr.Row():
|
| 215 |
+
continuation = gr.Textbox(
|
| 216 |
+
label="π― Sequel Starting Point",
|
| 217 |
+
placeholder="E.g., 'Five years after the final battle, a new dark force emerges from an unexpected source...'",
|
| 218 |
+
lines=2,
|
| 219 |
+
scale=3
|
| 220 |
+
)
|
| 221 |
+
|
| 222 |
+
with gr.Row():
|
| 223 |
+
with gr.Column():
|
| 224 |
+
stars_multiselect = gr.CheckboxGroup(
|
| 225 |
+
choices=STARS,
|
| 226 |
+
label="π Cast Existing Stars",
|
| 227 |
+
info="Select from popular actors"
|
| 228 |
+
)
|
| 229 |
+
with gr.Column():
|
| 230 |
+
custom_star = gr.Textbox(
|
| 231 |
+
label="β¨ Add Custom Character",
|
| 232 |
+
placeholder="E.g., 'Zara Voss, time-traveling detective'",
|
| 233 |
+
info="Create original characters"
|
| 234 |
+
)
|
| 235 |
+
|
| 236 |
+
word_slider = gr.Slider(
|
| 237 |
+
minimum=100,
|
| 238 |
+
maximum=2000,
|
| 239 |
+
value=600,
|
| 240 |
+
step=100,
|
| 241 |
+
label="π Story Length (Words)",
|
| 242 |
+
info="Short summary (100) β Detailed treatment (2000)"
|
| 243 |
+
)
|
| 244 |
+
|
| 245 |
+
with gr.Row():
|
| 246 |
+
generate_btn = gr.Button("π Generate Sequel!", variant="primary", scale=2)
|
| 247 |
+
pdf_btn = gr.Button("π Export PDF", visible=False, variant="secondary", scale=1)
|
| 248 |
+
|
| 249 |
+
story_output = gr.Markdown(
|
| 250 |
+
label="π Your Generated Sequel",
|
| 251 |
+
placeholder="Your AI-generated sequel will appear here..."
|
| 252 |
+
)
|
| 253 |
+
|
| 254 |
+
pdf_file = gr.File(
|
| 255 |
+
label="π₯ Download PDF",
|
| 256 |
+
visible=False,
|
| 257 |
+
file_types=[".pdf"]
|
| 258 |
+
)
|
| 259 |
+
|
| 260 |
+
def full_generate(audio, plot, cont, stars, custom, words):
|
| 261 |
+
if audio is not None:
|
| 262 |
+
transcribed = speech_to_text(audio)
|
| 263 |
+
if transcribed and not transcribed.startswith("π") and not transcribed.startswith("π€"):
|
| 264 |
+
plot = transcribed
|
| 265 |
+
|
| 266 |
+
story, btn_visible, file_visible = generate_sequel(plot, cont, stars, custom, words)
|
| 267 |
+
return story, btn_visible, file_visible
|
| 268 |
+
|
| 269 |
+
def export_pdf(story):
|
| 270 |
+
pdf_data, filename = create_pdf(story)
|
| 271 |
+
if pdf_data:
|
| 272 |
+
return gr.update(value=pdf_data, visible=True, label=f"π₯ Download {filename}")
|
| 273 |
+
else:
|
| 274 |
+
return gr.update(visible=False)
|
| 275 |
+
|
| 276 |
+
generate_btn.click(
|
| 277 |
+
full_generate,
|
| 278 |
+
inputs=[audio_input, plot_text, continuation, stars_multiselect, custom_star, word_slider],
|
| 279 |
+
outputs=[story_output, pdf_btn, pdf_file]
|
| 280 |
+
)
|
| 281 |
+
|
| 282 |
+
pdf_btn.click(export_pdf, inputs=story_output, outputs=pdf_file)
|
| 283 |
+
|
| 284 |
+
# Examples
|
| 285 |
+
gr.Markdown("### πͺ Quick Start Examples")
|
| 286 |
+
gr.Examples(
|
| 287 |
+
examples=[
|
| 288 |
+
[
|
| 289 |
+
None,
|
| 290 |
+
"A hobbit's quest to destroy a powerful ring in the fires of Mount Doom",
|
| 291 |
+
"Years after the ring's destruction, a new shadow grows in the South",
|
| 292 |
+
["Elijah Wood", "Ian McKellen", "Orlando Bloom"],
|
| 293 |
+
"Elara, ranger of the Northern wastes",
|
| 294 |
+
800
|
| 295 |
+
],
|
| 296 |
+
[
|
| 297 |
+
None,
|
| 298 |
+
"80s cop thriller about an undercover detective infiltrating a drug ring",
|
| 299 |
+
"After the diner shootout, the detective's past comes back to haunt him",
|
| 300 |
+
["Al Pacino", "Michelle Pfeiffer"],
|
| 301 |
+
"Echo Kane, rogue AI informant",
|
| 302 |
+
1200
|
| 303 |
+
]
|
| 304 |
+
],
|
| 305 |
+
inputs=[audio_input, plot_text, continuation, stars_multiselect, custom_star, word_slider],
|
| 306 |
+
outputs=[story_output],
|
| 307 |
+
fn=full_generate,
|
| 308 |
+
cache_examples=False
|
| 309 |
+
)
|
| 310 |
+
|
| 311 |
+
gr.Markdown("---")
|
| 312 |
+
gr.Markdown("""
|
| 313 |
+
<div style='text-align: center; color: #666;'>
|
| 314 |
+
<i>Powered by Grok-4 Γ Gradio Γ PiForge</i><br>
|
| 315 |
+
<small>Voice processing requires microphone access. PDF export works best on desktop.</small>
|
| 316 |
+
</div>
|
| 317 |
+
""")
|
| 318 |
+
|
| 319 |
+
if __name__ == "__main__":
|
| 320 |
+
demo.launch(share=False, show_error=True)
|