Files changed (1) hide show
  1. app.py +304 -64
app.py CHANGED
@@ -1,72 +1,312 @@
 
1
  import gradio as gr
2
  from groq import Groq
3
- import os
4
 
5
- client = Groq(api_key=os.environ.get("GROQ_API_KEY"))
 
 
6
 
7
- SYSTEM_PROMPT = """You are an expert in storyboarding. Provide structured and insightful responses to queries
8
- about creating and refining storyboards"""
 
9
 
10
- def respond(message, history, model, temperature, max_tokens):
11
- messages = [{"role": "system", "content": SYSTEM_PROMPT}]
12
-
13
- for h in history:
14
- messages.append({"role": "user", "content": h[0]})
15
- if h[1]:
16
- messages.append({"role": "assistant", "content": h[1]})
17
-
18
- messages.append({"role": "user", "content": message})
19
-
20
- try:
21
- response = client.chat.completions.create(
22
- model=model,
23
- messages=messages,
24
- temperature=temperature,
25
- max_completion_tokens=max_tokens,
26
- )
27
- return response.choices[0].message.content
28
- except Exception as e:
29
- return f"Error: {str(e)}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
 
31
- # ChatInterface with additional inputs for parameters
32
- demo = gr.ChatInterface(
33
- fn=respond,
34
- title="🎬 Storyboard Generator AI",
35
- description="Create professional storyboards for films, animations, and more!",
36
- additional_inputs=[
37
- gr.Dropdown(
38
- choices=[
39
- "llama-3.3-70b-versatile",
40
- "llama-3.1-8b-instant",
41
- ],
42
- value="llama-3.3-70b-versatile",
43
- label="Model",
44
- info="Select the AI model to use"
45
- ),
46
- gr.Slider(
47
- minimum=0,
48
- maximum=2,
49
- value=0.9,
50
- step=0.1,
51
- label="Temperature",
52
- info="Controls randomness. Lower = more focused, Higher = more creative"
53
- ),
54
- gr.Slider(
55
- minimum=256,
56
- maximum=8192,
57
- value=2048,
58
- step=256,
59
- label="Max Tokens",
60
- info="Maximum length of the response"
61
- ),
62
- ],
63
- examples=[
64
- ["Create a storyboard for a 30-second coffee commercial"],
65
- ["Generate a horror movie opening scene storyboard"],
66
- ["Design a storyboard for a romantic comedy meet-cute at a bookstore"],
67
- ],
68
- theme="soft",
69
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70
 
71
  if __name__ == "__main__":
72
- demo.launch()
 
 
 
 
 
 
 
 
1
+ import os
2
  import gradio as gr
3
  from groq import Groq
 
4
 
5
+ # Initialize Groq client with API key from environment
6
+ GROQ_API_KEY = os.getenv("GROQ_API_KEY", "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")
7
+ client = Groq(api_key=GROQ_API_KEY)
8
 
9
+ # Store conversation history
10
+ conversation_history = []
11
+ max_history_length = 10
12
 
13
+ def stream_response(messages, temperature=1):
14
+ """Stream response from Groq API."""
15
+ completion = client.chat.completions.create(
16
+ model="openai/gpt-oss-120b",
17
+ messages=messages,
18
+ temperature=temperature,
19
+ max_completion_tokens=8192,
20
+ top_p=1,
21
+ stream=True,
22
+ stop=None
23
+ )
24
+
25
+ response_text = ""
26
+ for chunk in completion:
27
+ if chunk.choices[0].delta.content:
28
+ response_text += chunk.choices[0].delta.content
29
+ yield response_text
30
+
31
+ def generate_story(story_prompt, story_type):
32
+ """Generate a story based on prompt and type."""
33
+ global conversation_history
34
+
35
+ if not story_prompt.strip():
36
+ return "Please enter a story prompt."
37
+
38
+ # Create system message based on story type
39
+ system_messages = {
40
+ "Fantasy": "You are a creative fantasy storyteller. Generate an engaging, immersive fantasy story with vivid descriptions.",
41
+ "Science Fiction": "You are a sci-fi storyteller. Generate an engaging science fiction story with futuristic elements and world-building.",
42
+ "Mystery": "You are a mystery writer. Generate a compelling mystery story with plot twists and clues.",
43
+ "Romance": "You are a romance novelist. Generate a heartwarming, emotional romance story.",
44
+ "Horror": "You are a horror writer. Generate a suspenseful, atmospheric horror story.",
45
+ "Adventure": "You are an adventure writer. Generate an exciting adventure story with action and discovery.",
46
+ "General": "You are a creative writer. Generate an engaging and well-structured story."
47
+ }
48
+
49
+ system_prompt = system_messages.get(story_type, system_messages["General"])
50
+
51
+ # Build messages for API
52
+ messages = [
53
+ {"role": "system", "content": system_prompt},
54
+ {"role": "user", "content": f"Write a story based on this prompt: {story_prompt}"}
55
+ ]
56
+
57
+ # Add conversation history for context
58
+ if conversation_history:
59
+ messages = conversation_history[-max_history_length:] + messages
60
+
61
+ # Stream and collect response
62
+ full_response = ""
63
+ for partial_response in stream_response(messages):
64
+ full_response = partial_response
65
+ yield full_response
66
+
67
+ # Store in conversation history
68
+ conversation_history.append({"role": "user", "content": f"Story ({story_type}): {story_prompt}"})
69
+ conversation_history.append({"role": "assistant", "content": full_response})
70
+
71
+ def generate_storyboard(scenario):
72
+ """Generate a detailed storyboard for a given scenario."""
73
+ global conversation_history
74
+
75
+ if not scenario.strip():
76
+ return "Please enter a scenario for the storyboard."
77
+
78
+ storyboard_prompt = f"""Generate a detailed storyboard for the following scenario:
79
+
80
+ Scenario: {scenario}
81
+
82
+ Please create a storyboard with:
83
+ 1. Scene-by-scene breakdown
84
+ 2. Key visual elements for each scene
85
+ 3. Dialogue or narration
86
+ 4. Transitions between scenes
87
+ 5. Camera angles and movements
88
+ 6. Lighting and mood notes
89
+ 7. Props and set design
90
 
91
+ Format the output in a clear, structured manner with each scene clearly numbered and separated."""
92
+
93
+ messages = [
94
+ {"role": "system", "content": "You are a professional storyboard artist and screenwriter. Create detailed, visual storyboards with cinematic descriptions."},
95
+ {"role": "user", "content": storyboard_prompt}
96
+ ]
97
+
98
+ full_response = ""
99
+ for partial_response in stream_response(messages):
100
+ full_response = partial_response
101
+ yield full_response
102
+
103
+ # Store in history
104
+ conversation_history.append({"role": "user", "content": f"Storyboard: {scenario}"})
105
+ conversation_history.append({"role": "assistant", "content": full_response})
106
+
107
+ def chat(user_message, chat_history):
108
+ """Handle general chat conversations."""
109
+ global conversation_history
110
+
111
+ if not user_message.strip():
112
+ return chat_history
113
+
114
+ # Add user message to chat history
115
+ chat_history.append((user_message, ""))
116
+
117
+ # Build messages for API
118
+ messages = [
119
+ {"role": "system", "content": "You are a helpful AI assistant specializing in creative writing, storytelling, and narrative development."}
120
+ ]
121
+
122
+ # Add chat history to context (limit to prevent token overflow)
123
+ for user_msg, assistant_msg in chat_history[-max_history_length:]:
124
+ messages.append({"role": "user", "content": user_msg})
125
+ if assistant_msg:
126
+ messages.append({"role": "assistant", "content": assistant_msg})
127
+
128
+ # Stream response
129
+ full_response = ""
130
+ for partial_response in stream_response(messages):
131
+ full_response = partial_response
132
+ chat_history[-1] = (user_message, full_response)
133
+ yield chat_history
134
+
135
+ # Store in conversation history
136
+ conversation_history.append({"role": "user", "content": user_message})
137
+ conversation_history.append({"role": "assistant", "content": full_response})
138
+
139
+ def reset_chat_history():
140
+ """Reset chat history."""
141
+ return []
142
+
143
+ def reset_all_history():
144
+ """Reset all conversation history."""
145
+ global conversation_history
146
+ conversation_history = []
147
+ return []
148
+
149
+ # Create Gradio interface
150
+ def create_interface():
151
+ with gr.Blocks(
152
+ title="Story Generator & Chatbot",
153
+ theme=gr.themes.Soft(),
154
+ css="""
155
+ .gradio-container {
156
+ max-width: 1200px;
157
+ margin: auto;
158
+ }
159
+ """
160
+ ) as demo:
161
+ gr.Markdown(
162
+ """
163
+ # πŸ“– AI Story Generator & Chatbot
164
+
165
+ **Powered by Groq API** - Generate creative stories, create storyboards, and chat about narrative writing!
166
+ """
167
+ )
168
+
169
+ with gr.Tabs():
170
+ # Story Generation Tab
171
+ with gr.Tab("🎭 Story Generator"):
172
+ gr.Markdown("### Generate creative stories")
173
+ gr.Markdown("Provide a story prompt and select a genre to generate a unique story.")
174
+
175
+ with gr.Row():
176
+ with gr.Column(scale=2):
177
+ story_prompt = gr.Textbox(
178
+ label="Story Prompt",
179
+ placeholder="e.g., A mysterious letter arrives at an old mansion on a stormy night...",
180
+ lines=4,
181
+ info="Be descriptive for better results"
182
+ )
183
+
184
+ with gr.Row():
185
+ story_type = gr.Dropdown(
186
+ choices=["Fantasy", "Science Fiction", "Mystery", "Romance", "Horror", "Adventure", "General"],
187
+ value="General",
188
+ label="Story Type",
189
+ info="Choose the genre for your story"
190
+ )
191
+ generate_btn = gr.Button("✨ Generate Story", variant="primary", scale=1)
192
+
193
+ with gr.Column(scale=2):
194
+ story_output = gr.Textbox(
195
+ label="Generated Story",
196
+ lines=20,
197
+ interactive=False,
198
+ show_copy_button=True
199
+ )
200
+
201
+ generate_btn.click(
202
+ generate_story,
203
+ inputs=[story_prompt, story_type],
204
+ outputs=story_output
205
+ )
206
+
207
+ # Storyboard Tab
208
+ with gr.Tab("🎬 Storyboard Creator"):
209
+ gr.Markdown("### Create detailed storyboards")
210
+ gr.Markdown("Describe your scenario in detail to get a comprehensive visual storyboard.")
211
+
212
+ with gr.Row():
213
+ with gr.Column(scale=1):
214
+ scenario = gr.Textbox(
215
+ label="Scenario Description",
216
+ placeholder="e.g., A superhero saves the city from an alien invasion. Include setting, characters, and key events...",
217
+ lines=5,
218
+ info="More details = better storyboard"
219
+ )
220
+ storyboard_btn = gr.Button("πŸŽ₯ Generate Storyboard", variant="primary")
221
+
222
+ with gr.Column(scale=1):
223
+ storyboard_output = gr.Textbox(
224
+ label="Generated Storyboard",
225
+ lines=20,
226
+ interactive=False,
227
+ show_copy_button=True
228
+ )
229
+
230
+ storyboard_btn.click(
231
+ generate_storyboard,
232
+ inputs=scenario,
233
+ outputs=storyboard_output
234
+ )
235
+
236
+ # Chat Tab
237
+ with gr.Tab("πŸ’¬ Storytelling Chat"):
238
+ gr.Markdown("### Chat about creative writing")
239
+ gr.Markdown("Discuss storytelling techniques, get writing advice, and brainstorm ideas.")
240
+
241
+ with gr.Row():
242
+ with gr.Column():
243
+ chatbot = gr.Chatbot(
244
+ label="Conversation",
245
+ height=500,
246
+ show_label=True,
247
+ scale=1
248
+ )
249
+
250
+ with gr.Row():
251
+ user_input = gr.Textbox(
252
+ label="Your message",
253
+ placeholder="Ask about storytelling, writing tips, or brainstorm ideas...",
254
+ scale=5,
255
+ show_label=False
256
+ )
257
+ send_btn = gr.Button("Send", variant="primary", scale=1)
258
+
259
+ with gr.Row():
260
+ clear_chat_btn = gr.Button("Clear Chat", scale=1)
261
+
262
+ # Handle sending messages
263
+ def send_message(msg, history):
264
+ return chat(msg, history)
265
+
266
+ send_btn.click(
267
+ send_message,
268
+ inputs=[user_input, chatbot],
269
+ outputs=chatbot
270
+ ).then(
271
+ lambda: "",
272
+ outputs=user_input
273
+ )
274
+
275
+ user_input.submit(
276
+ send_message,
277
+ inputs=[user_input, chatbot],
278
+ outputs=chatbot
279
+ ).then(
280
+ lambda: "",
281
+ outputs=user_input
282
+ )
283
+
284
+ clear_chat_btn.click(
285
+ reset_chat_history,
286
+ outputs=chatbot
287
+ )
288
+
289
+ gr.Markdown(
290
+ """
291
+ ---
292
+ **Tips for best results:**
293
+ - πŸ“ Be detailed and descriptive in your prompts
294
+ - 🎯 The more context you provide, the better the output
295
+ - πŸ’‘ Use story types to guide the tone and genre
296
+ - πŸ”„ Refine your ideas through conversation
297
+
298
+ **Powered by:** [Groq API](https://groq.com) | **Built with:** [Gradio](https://gradio.app)
299
+ """
300
+ )
301
+
302
+ return demo
303
 
304
  if __name__ == "__main__":
305
+ demo = create_interface()
306
+ demo.launch(
307
+ server_name="0.0.0.0",
308
+ server_port=7860,
309
+ share=False,
310
+ show_error=True,
311
+ max_threads=10
312
+ )