Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -1,6 +1,5 @@
|
|
1 |
import gradio as gr
|
2 |
import random
|
3 |
-
import time
|
4 |
from datetime import datetime
|
5 |
import tempfile
|
6 |
import os
|
@@ -8,42 +7,34 @@ import edge_tts
|
|
8 |
import asyncio
|
9 |
import warnings
|
10 |
from gradio_client import Client
|
11 |
-
import json
|
12 |
import pytz
|
13 |
import re
|
|
|
14 |
|
15 |
warnings.filterwarnings('ignore')
|
16 |
|
17 |
-
# Initialize
|
18 |
-
|
|
|
|
|
|
|
|
|
19 |
try:
|
20 |
-
|
21 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
22 |
except Exception as e:
|
23 |
-
|
24 |
-
return None
|
25 |
-
|
26 |
-
if "client" not in locals():
|
27 |
-
CLIENT = initialize_clients()
|
28 |
-
|
29 |
-
# Helper function to generate a filename
|
30 |
-
def gen_AI_IO_filename(display_query, output):
|
31 |
-
now_central = datetime.now(pytz.timezone("America/Chicago"))
|
32 |
-
timestamp = now_central.strftime("%Y-%m-%d-%I-%M-%S-%f-%p")
|
33 |
-
display_query = display_query[:50]
|
34 |
-
output_snippet = re.sub(r'[^A-Za-z0-9]+', '_', output[:100])
|
35 |
-
filename = f"{timestamp} - {display_query} - {output_snippet}.md"
|
36 |
-
return filename
|
37 |
-
|
38 |
-
def create_file(filename, prompt, response, should_save=True):
|
39 |
-
"""Create and save a file with prompt and response"""
|
40 |
-
if not should_save:
|
41 |
-
return
|
42 |
-
with open(filename, 'w', encoding='utf-8') as file:
|
43 |
-
file.write(f"Prompt:\n{prompt}\n\nResponse:\n{response}")
|
44 |
|
45 |
async def generate_speech(text, voice="en-US-AriaNeural"):
|
46 |
-
"""Generate speech from text
|
47 |
try:
|
48 |
communicate = edge_tts.Communicate(text, voice)
|
49 |
with tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") as tmp_file:
|
@@ -54,155 +45,72 @@ async def generate_speech(text, voice="en-US-AriaNeural"):
|
|
54 |
print(f"Error in text2speech: {str(e)}")
|
55 |
return None
|
56 |
|
57 |
-
def
|
58 |
-
"""
|
59 |
-
try:
|
60 |
-
if CLIENT is None:
|
61 |
-
return "Error: Story generation service is not available."
|
62 |
-
|
63 |
-
# First pass: Generate initial story with chosen model
|
64 |
-
initial_result = CLIENT.predict(
|
65 |
-
prompt=prompt,
|
66 |
-
llm_model_picked=model_choice,
|
67 |
-
stream_outputs=True,
|
68 |
-
api_name="/ask_llm"
|
69 |
-
)
|
70 |
-
|
71 |
-
# Second pass: Enhance with RAG pattern
|
72 |
-
enhanced_result = CLIENT.predict(
|
73 |
-
message=prompt,
|
74 |
-
llm_results_use=10,
|
75 |
-
database_choice="Semantic Search",
|
76 |
-
llm_model_picked=model_choice,
|
77 |
-
api_name="/update_with_rag_md"
|
78 |
-
)
|
79 |
-
|
80 |
-
# Combine results and save
|
81 |
-
story = initial_result + "\n\nEnhanced version:\n" + enhanced_result[0]
|
82 |
-
|
83 |
-
# Save outputs
|
84 |
-
filename = gen_AI_IO_filename("Story", initial_result)
|
85 |
-
create_file(filename, prompt, initial_result)
|
86 |
-
|
87 |
-
filename = gen_AI_IO_filename("Enhanced", enhanced_result[0])
|
88 |
-
create_file(filename, prompt, enhanced_result[0])
|
89 |
-
|
90 |
-
return story
|
91 |
-
except Exception as e:
|
92 |
-
return f"Error generating story: {str(e)}"
|
93 |
-
|
94 |
-
def story_generator_interface(prompt, genre, structure, model_choice, num_scenes, words_per_scene):
|
95 |
-
"""Main story generation and audio creation function"""
|
96 |
try:
|
97 |
-
# Create storytelling prompt
|
98 |
-
story_prompt = f"""Create a {genre} story following this structure: {structure}
|
99 |
-
Base concept: {prompt}
|
100 |
-
Make it engaging and suitable for narration.
|
101 |
-
Include vivid descriptions and sensory details.
|
102 |
-
Use approximately {words_per_scene} words per scene.
|
103 |
-
Create {num_scenes} distinct scenes."""
|
104 |
-
|
105 |
# Generate story
|
106 |
-
story = generate_story(
|
107 |
if story.startswith("Error"):
|
108 |
return story, None
|
109 |
-
|
110 |
-
# Generate
|
111 |
audio_path = asyncio.run(generate_speech(story))
|
112 |
|
113 |
return story, audio_path
|
114 |
-
|
115 |
except Exception as e:
|
116 |
-
|
117 |
-
return error_msg, None
|
118 |
|
119 |
-
#
|
120 |
-
|
121 |
-
gr.
|
122 |
-
|
123 |
-
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
with gr.
|
128 |
-
|
129 |
-
|
130 |
-
|
131 |
-
|
132 |
-
|
133 |
-
|
134 |
-
|
135 |
-
|
136 |
-
|
137 |
-
|
138 |
-
|
139 |
-
|
140 |
-
"
|
141 |
-
|
142 |
-
|
143 |
-
|
144 |
-
|
145 |
-
value="Fantasy"
|
146 |
-
)
|
147 |
-
structure_input = gr.Dropdown(
|
148 |
-
label="Story Structure",
|
149 |
-
choices=[
|
150 |
-
"Three Act (Setup -> Confrontation -> Resolution)",
|
151 |
-
"Hero's Journey (Call -> Adventure -> Return)",
|
152 |
-
"Five Act (Exposition -> Rising Action -> Climax -> Falling Action -> Resolution)"
|
153 |
-
],
|
154 |
-
value="Three Act (Setup -> Confrontation -> Resolution)"
|
155 |
-
)
|
156 |
-
model_choice = gr.Dropdown(
|
157 |
-
label="Model",
|
158 |
-
choices=[
|
159 |
-
"mistralai/Mixtral-8x7B-Instruct-v0.1",
|
160 |
-
"mistralai/Mistral-7B-Instruct-v0.2"
|
161 |
-
],
|
162 |
-
value="mistralai/Mixtral-8x7B-Instruct-v0.1"
|
163 |
-
)
|
164 |
-
num_scenes = gr.Slider(
|
165 |
-
label="Number of Scenes",
|
166 |
-
minimum=3,
|
167 |
-
maximum=7,
|
168 |
-
value=5,
|
169 |
-
step=1
|
170 |
-
)
|
171 |
-
words_per_scene = gr.Slider(
|
172 |
-
label="Words per Scene",
|
173 |
-
minimum=20,
|
174 |
-
maximum=100,
|
175 |
-
value=50,
|
176 |
-
step=10
|
177 |
-
)
|
178 |
-
generate_btn = gr.Button("Generate Story")
|
179 |
-
|
180 |
-
with gr.Row():
|
181 |
-
with gr.Column():
|
182 |
story_output = gr.Textbox(
|
183 |
label="Generated Story",
|
184 |
lines=10,
|
185 |
interactive=False
|
186 |
)
|
187 |
-
|
188 |
-
|
189 |
-
|
190 |
-
|
191 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
192 |
)
|
193 |
|
194 |
-
|
195 |
-
|
196 |
-
|
197 |
-
|
198 |
-
|
199 |
-
|
200 |
-
|
201 |
-
|
202 |
-
|
203 |
-
|
204 |
-
outputs=[
|
205 |
-
story_output,
|
206 |
-
audio_output
|
207 |
-
]
|
208 |
-
)
|
|
|
1 |
import gradio as gr
|
2 |
import random
|
|
|
3 |
from datetime import datetime
|
4 |
import tempfile
|
5 |
import os
|
|
|
7 |
import asyncio
|
8 |
import warnings
|
9 |
from gradio_client import Client
|
|
|
10 |
import pytz
|
11 |
import re
|
12 |
+
import json
|
13 |
|
14 |
warnings.filterwarnings('ignore')
|
15 |
|
16 |
+
# Initialize client outside of reload block
|
17 |
+
if gr.NO_RELOAD:
|
18 |
+
ARXIV_CLIENT = Client("awacke1/Arxiv-Paper-Search-And-QA-RAG-Pattern")
|
19 |
+
|
20 |
+
def generate_story(prompt, model_choice):
|
21 |
+
"""Generate story using specified model"""
|
22 |
try:
|
23 |
+
if ARXIV_CLIENT is None:
|
24 |
+
return "Error: Story generation service is not available."
|
25 |
+
|
26 |
+
result = ARXIV_CLIENT.predict(
|
27 |
+
prompt=prompt,
|
28 |
+
llm_model_picked=model_choice,
|
29 |
+
stream_outputs=True,
|
30 |
+
api_name="/ask_llm"
|
31 |
+
)
|
32 |
+
return result
|
33 |
except Exception as e:
|
34 |
+
return f"Error generating story: {str(e)}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
35 |
|
36 |
async def generate_speech(text, voice="en-US-AriaNeural"):
|
37 |
+
"""Generate speech from text"""
|
38 |
try:
|
39 |
communicate = edge_tts.Communicate(text, voice)
|
40 |
with tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") as tmp_file:
|
|
|
45 |
print(f"Error in text2speech: {str(e)}")
|
46 |
return None
|
47 |
|
48 |
+
def process_story_and_audio(prompt, model_choice):
|
49 |
+
"""Process story and generate audio"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
50 |
try:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
51 |
# Generate story
|
52 |
+
story = generate_story(prompt, model_choice)
|
53 |
if story.startswith("Error"):
|
54 |
return story, None
|
55 |
+
|
56 |
+
# Generate audio
|
57 |
audio_path = asyncio.run(generate_speech(story))
|
58 |
|
59 |
return story, audio_path
|
|
|
60 |
except Exception as e:
|
61 |
+
return f"Error: {str(e)}", None
|
|
|
62 |
|
63 |
+
# Define the Gradio interface
|
64 |
+
def create_app():
|
65 |
+
with gr.Blocks(title="AI Story Generator") as demo:
|
66 |
+
gr.Markdown("""
|
67 |
+
# 🎭 AI Story Generator & Narrator
|
68 |
+
Generate creative stories and listen to them!
|
69 |
+
""")
|
70 |
+
|
71 |
+
with gr.Row():
|
72 |
+
with gr.Column():
|
73 |
+
prompt_input = gr.Textbox(
|
74 |
+
label="Story Concept",
|
75 |
+
placeholder="Enter your story idea...",
|
76 |
+
lines=3
|
77 |
+
)
|
78 |
+
model_choice = gr.Dropdown(
|
79 |
+
label="Model",
|
80 |
+
choices=[
|
81 |
+
"mistralai/Mixtral-8x7B-Instruct-v0.1",
|
82 |
+
"mistralai/Mistral-7B-Instruct-v0.2"
|
83 |
+
],
|
84 |
+
value="mistralai/Mixtral-8x7B-Instruct-v0.1"
|
85 |
+
)
|
86 |
+
generate_btn = gr.Button("Generate Story")
|
87 |
+
|
88 |
+
with gr.Row():
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
89 |
story_output = gr.Textbox(
|
90 |
label="Generated Story",
|
91 |
lines=10,
|
92 |
interactive=False
|
93 |
)
|
94 |
+
|
95 |
+
with gr.Row():
|
96 |
+
audio_output = gr.Audio(
|
97 |
+
label="Story Narration",
|
98 |
+
type="filepath"
|
99 |
+
)
|
100 |
+
|
101 |
+
generate_btn.click(
|
102 |
+
fn=process_story_and_audio,
|
103 |
+
inputs=[prompt_input, model_choice],
|
104 |
+
outputs=[story_output, audio_output]
|
105 |
)
|
106 |
|
107 |
+
return demo
|
108 |
+
|
109 |
+
# Launch the app
|
110 |
+
if __name__ == "__main__":
|
111 |
+
demo = create_app()
|
112 |
+
demo.launch(
|
113 |
+
server_name="0.0.0.0",
|
114 |
+
server_port=7860,
|
115 |
+
share=True
|
116 |
+
)
|
|
|
|
|
|
|
|
|
|