Spaces:
Running
Running
Update app.py
#3
by mhamoody - opened
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172import gradio as grfrom groq import Groqimport osclient = Groq(api_key=os.environ.get("GROQ_API_KEY"))SYSTEM_PROMPT = """You are an expert in storyboarding. Provide structured and insightful responses to queriesabout creating and refining storyboards"""def respond(message, history, model, temperature, max_tokens):messages = [{"role": "system", "content": SYSTEM_PROMPT}]for h in history:messages.append({"role": "user", "content": h[0]})if h[1]:messages.append({"role": "assistant", "content": h[1]})messages.append({"role": "user", "content": message})try:response = client.chat.completions.create(model=model,messages=messages,temperature=temperature,max_completion_tokens=max_tokens,)return response.choices[0].message.contentexcept Exception as e:return f"Error: {str(e)}"# ChatInterface with additional inputs for parametersdemo = gr.ChatInterface(fn=respond,title="🎬 Storyboard Generator AI",description="Create professional storyboards for films, animations, and more!",additional_inputs=[gr.Dropdown(choices=["llama-3.3-70b-versatile","llama-3.1-8b-instant",],value="llama-3.3-70b-versatile",label="Model",info="Select the AI model to use"),gr.Slider(minimum=0,maximum=2,value=0.9,step=0.1,label="Temperature",info="Controls randomness. Lower = more focused, Higher = more creative"),gr.Slider(minimum=256,maximum=8192,value=2048,step=256,label="Max Tokens",info="Maximum length of the response"),],examples=[["Create a storyboard for a 30-second coffee commercial"],["Generate a horror movie opening scene storyboard"],["Design a storyboard for a romantic comedy meet-cute at a bookstore"],],theme="soft",)if __name__ == "__main__":demo.launch()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312import osimport gradio as grfrom groq import Groq# Initialize Groq client with API key from environmentGROQ_API_KEY = os.getenv("GROQ_API_KEY", "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")client = Groq(api_key=GROQ_API_KEY)# Store conversation historyconversation_history = []max_history_length = 10def stream_response(messages, temperature=1):"""Stream response from Groq API."""completion = client.chat.completions.create(model="openai/gpt-oss-120b",messages=messages,temperature=temperature,max_completion_tokens=8192,top_p=1,stream=True,stop=None)response_text = ""for chunk in completion:if chunk.choices[0].delta.content:response_text += chunk.choices[0].delta.contentyield response_textdef generate_story(story_prompt, story_type):"""Generate a story based on prompt and type."""global conversation_historyif not story_prompt.strip():return "Please enter a story prompt."# Create system message based on story typesystem_messages = {"Fantasy": "You are a creative fantasy storyteller. Generate an engaging, immersive fantasy story with vivid descriptions.","Science Fiction": "You are a sci-fi storyteller. Generate an engaging science fiction story with futuristic elements and world-building.","Mystery": "You are a mystery writer. Generate a compelling mystery story with plot twists and clues.","Romance": "You are a romance novelist. Generate a heartwarming, emotional romance story.","Horror": "You are a horror writer. Generate a suspenseful, atmospheric horror story.","Adventure": "You are an adventure writer. Generate an exciting adventure story with action and discovery.","General": "You are a creative writer. Generate an engaging and well-structured story."}system_prompt = system_messages.get(story_type, system_messages["General"])# Build messages for APImessages = [{"role": "system", "content": system_prompt},{"role": "user", "content": f"Write a story based on this prompt: {story_prompt}"}]# Add conversation history for contextif conversation_history:messages = conversation_history[-max_history_length:] + messages# Stream and collect responsefull_response = ""for partial_response in stream_response(messages):full_response = partial_responseyield full_response# Store in conversation historyconversation_history.append({"role": "user", "content": f"Story ({story_type}): {story_prompt}"})conversation_history.append({"role": "assistant", "content": full_response})def generate_storyboard(scenario):"""Generate a detailed storyboard for a given scenario."""global conversation_historyif not scenario.strip():return "Please enter a scenario for the storyboard."storyboard_prompt = f"""Generate a detailed storyboard for the following scenario:Scenario: {scenario}Please create a storyboard with:1. Scene-by-scene breakdown2. Key visual elements for each scene3. Dialogue or narration4. Transitions between scenes5. Camera angles and movements6. Lighting and mood notes7. Props and set designFormat the output in a clear, structured manner with each scene clearly numbered and separated."""messages = [{"role": "system", "content": "You are a professional storyboard artist and screenwriter. Create detailed, visual storyboards with cinematic descriptions."},{"role": "user", "content": storyboard_prompt}]full_response = ""for partial_response in stream_response(messages):full_response = partial_responseyield full_response# Store in historyconversation_history.append({"role": "user", "content": f"Storyboard: {scenario}"})conversation_history.append({"role": "assistant", "content": full_response})def chat(user_message, chat_history):"""Handle general chat conversations."""global conversation_historyif not user_message.strip():return chat_history# Add user message to chat historychat_history.append((user_message, ""))# Build messages for APImessages = [{"role": "system", "content": "You are a helpful AI assistant specializing in creative writing, storytelling, and narrative development."}]# Add chat history to context (limit to prevent token overflow)for user_msg, assistant_msg in chat_history[-max_history_length:]:messages.append({"role": "user", "content": user_msg})if assistant_msg:messages.append({"role": "assistant", "content": assistant_msg})# Stream responsefull_response = ""for partial_response in stream_response(messages):full_response = partial_responsechat_history[-1] = (user_message, full_response)yield chat_history# Store in conversation historyconversation_history.append({"role": "user", "content": user_message})conversation_history.append({"role": "assistant", "content": full_response})def reset_chat_history():"""Reset chat history."""return []def reset_all_history():"""Reset all conversation history."""global conversation_historyconversation_history = []return []# Create Gradio interfacedef create_interface():with gr.Blocks(title="Story Generator & Chatbot",theme=gr.themes.Soft(),css=""".gradio-container {max-width: 1200px;margin: auto;}""") as demo:gr.Markdown("""# 📖 AI Story Generator & Chatbot**Powered by Groq API** - Generate creative stories, create storyboards, and chat about narrative writing!""")with gr.Tabs():# Story Generation Tabwith gr.Tab("🎭 Story Generator"):gr.Markdown("### Generate creative stories")gr.Markdown("Provide a story prompt and select a genre to generate a unique story.")with gr.Row():with gr.Column(scale=2):story_prompt = gr.Textbox(label="Story Prompt",placeholder="e.g., A mysterious letter arrives at an old mansion on a stormy night...",lines=4,info="Be descriptive for better results")with gr.Row():story_type = gr.Dropdown(choices=["Fantasy", "Science Fiction", "Mystery", "Romance", "Horror", "Adventure", "General"],value="General",label="Story Type",info="Choose the genre for your story")generate_btn = gr.Button("✨ Generate Story", variant="primary", scale=1)with gr.Column(scale=2):story_output = gr.Textbox(label="Generated Story",lines=20,interactive=False,show_copy_button=True)generate_btn.click(generate_story,inputs=[story_prompt, story_type],outputs=story_output)# Storyboard Tabwith gr.Tab("🎬 Storyboard Creator"):gr.Markdown("### Create detailed storyboards")gr.Markdown("Describe your scenario in detail to get a comprehensive visual storyboard.")with gr.Row():with gr.Column(scale=1):scenario = gr.Textbox(label="Scenario Description",placeholder="e.g., A superhero saves the city from an alien invasion. Include setting, characters, and key events...",lines=5,info="More details = better storyboard")storyboard_btn = gr.Button("🎥 Generate Storyboard", variant="primary")with gr.Column(scale=1):storyboard_output = gr.Textbox(label="Generated Storyboard",lines=20,interactive=False,show_copy_button=True)storyboard_btn.click(generate_storyboard,inputs=scenario,outputs=storyboard_output)# Chat Tabwith gr.Tab("💬 Storytelling Chat"):gr.Markdown("### Chat about creative writing")gr.Markdown("Discuss storytelling techniques, get writing advice, and brainstorm ideas.")with gr.Row():with gr.Column():chatbot = gr.Chatbot(label="Conversation",height=500,show_label=True,scale=1)with gr.Row():user_input = gr.Textbox(label="Your message",placeholder="Ask about storytelling, writing tips, or brainstorm ideas...",scale=5,show_label=False)send_btn = gr.Button("Send", variant="primary", scale=1)with gr.Row():clear_chat_btn = gr.Button("Clear Chat", scale=1)# Handle sending messagesdef send_message(msg, history):return chat(msg, history)send_btn.click(send_message,inputs=[user_input, chatbot],outputs=chatbot).then(lambda: "",outputs=user_input)user_input.submit(send_message,inputs=[user_input, chatbot],outputs=chatbot).then(lambda: "",outputs=user_input)clear_chat_btn.click(reset_chat_history,outputs=chatbot)gr.Markdown("""---**Tips for best results:**- 📝 Be detailed and descriptive in your prompts- 🎯 The more context you provide, the better the output- 💡 Use story types to guide the tone and genre- 🔄 Refine your ideas through conversation**Powered by:** [Groq API](https://groq.com) | **Built with:** [Gradio](https://gradio.app)""")return demoif __name__ == "__main__":demo = create_interface()demo.launch(server_name="0.0.0.0",server_port=7860,share=False,show_error=True,max_threads=10)
app.py+304-64