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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import random
|
3 |
+
from datetime import datetime
|
4 |
+
import tempfile
|
5 |
+
import os
|
6 |
+
import edge_tts
|
7 |
+
import asyncio
|
8 |
+
import warnings
|
9 |
+
import pytz
|
10 |
+
import re
|
11 |
+
import json
|
12 |
+
import pandas as pd
|
13 |
+
from pathlib import Path
|
14 |
+
from gradio_client import Client
|
15 |
+
|
16 |
+
warnings.filterwarnings('ignore')
|
17 |
+
|
18 |
+
# Initialize story starters with added comedy section
|
19 |
+
STORY_STARTERS = [
|
20 |
+
['Adventure', 'In a hidden temple deep in the Amazon...'],
|
21 |
+
['Mystery', 'The detective found an unusual note...'],
|
22 |
+
['Romance', 'Two strangers meet on a rainy evening...'],
|
23 |
+
['Sci-Fi', 'The space station received an unexpected signal...'],
|
24 |
+
['Fantasy', 'A magical portal appeared in the garden...'],
|
25 |
+
['Comedy-Sitcom', 'The new roommate arrived with seven emotional support animals...'],
|
26 |
+
['Comedy-Workplace', 'The office printer started sending mysterious messages...'],
|
27 |
+
['Comedy-Family', 'Grandma decided to become a social media influencer...'],
|
28 |
+
['Comedy-Supernatural', 'The ghost haunting the house was absolutely terrible at scaring people...'],
|
29 |
+
['Comedy-Travel', 'The GPS insisted on giving directions in interpretive dance descriptions...']
|
30 |
+
]
|
31 |
+
|
32 |
+
# Initialize client outside of interface definition
|
33 |
+
arxiv_client = None
|
34 |
+
|
35 |
+
def init_client():
|
36 |
+
global arxiv_client
|
37 |
+
if arxiv_client is None:
|
38 |
+
arxiv_client = Client("awacke1/Arxiv-Paper-Search-And-QA-RAG-Pattern")
|
39 |
+
return arxiv_client
|
40 |
+
|
41 |
+
def save_story(story, audio_path):
|
42 |
+
"""Save story and audio to gallery with markdown formatting"""
|
43 |
+
try:
|
44 |
+
# Create gallery directory if it doesn't exist
|
45 |
+
gallery_dir = Path("gallery")
|
46 |
+
gallery_dir.mkdir(exist_ok=True)
|
47 |
+
|
48 |
+
# Generate timestamp and sanitize first line for filename
|
49 |
+
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
50 |
+
first_line = story.split('\n')[0].strip()
|
51 |
+
safe_name = re.sub(r'[^\w\s-]', '', first_line)[:50] # First 50 chars, sanitized
|
52 |
+
|
53 |
+
# Save story text as markdown
|
54 |
+
story_path = gallery_dir / f"story_{timestamp}_{safe_name}.md"
|
55 |
+
with open(story_path, "w") as f:
|
56 |
+
f.write(f"# {first_line}\n\n{story}")
|
57 |
+
|
58 |
+
# Copy audio file to gallery with matching name
|
59 |
+
new_audio_path = None
|
60 |
+
if audio_path:
|
61 |
+
new_audio_path = gallery_dir / f"audio_{timestamp}_{safe_name}.mp3"
|
62 |
+
os.system(f"cp {audio_path} {str(new_audio_path)}")
|
63 |
+
|
64 |
+
return str(story_path), str(new_audio_path) if new_audio_path else None
|
65 |
+
except Exception as e:
|
66 |
+
print(f"Error saving to gallery: {str(e)}")
|
67 |
+
return None, None
|
68 |
+
|
69 |
+
def load_gallery():
|
70 |
+
"""Load all stories and audio from gallery with markdown support"""
|
71 |
+
try:
|
72 |
+
gallery_dir = Path("gallery")
|
73 |
+
if not gallery_dir.exists():
|
74 |
+
return []
|
75 |
+
|
76 |
+
files = []
|
77 |
+
for story_file in sorted(gallery_dir.glob("story_*.md"), reverse=True):
|
78 |
+
# Extract timestamp and name from filename
|
79 |
+
parts = story_file.stem.split('_', 2)
|
80 |
+
timestamp = f"{parts[1]}"
|
81 |
+
|
82 |
+
# Find matching audio file
|
83 |
+
audio_pattern = f"audio_{timestamp}_*.mp3"
|
84 |
+
audio_files = list(gallery_dir.glob(audio_pattern))
|
85 |
+
audio_file = audio_files[0] if audio_files else None
|
86 |
+
|
87 |
+
# Read story content and get preview
|
88 |
+
with open(story_file) as f:
|
89 |
+
content = f.read()
|
90 |
+
# Skip markdown header and get preview
|
91 |
+
preview = content.split('\n\n', 1)[1][:100] + "..."
|
92 |
+
|
93 |
+
files.append([
|
94 |
+
timestamp,
|
95 |
+
f"[{preview}]({str(story_file)})", # Markdown link to story
|
96 |
+
str(story_file),
|
97 |
+
str(audio_file) if audio_file else None
|
98 |
+
])
|
99 |
+
|
100 |
+
return files
|
101 |
+
except Exception as e:
|
102 |
+
print(f"Error loading gallery: {str(e)}")
|
103 |
+
return []
|
104 |
+
|
105 |
+
# Keep all other functions unchanged
|
106 |
+
def generate_story(prompt, model_choice):
|
107 |
+
"""Generate story using specified model"""
|
108 |
+
try:
|
109 |
+
client = init_client()
|
110 |
+
if client is None:
|
111 |
+
return "Error: Story generation service is not available."
|
112 |
+
|
113 |
+
result = client.predict(
|
114 |
+
prompt=prompt,
|
115 |
+
llm_model_picked=model_choice,
|
116 |
+
stream_outputs=True,
|
117 |
+
api_name="/ask_llm"
|
118 |
+
)
|
119 |
+
return result
|
120 |
+
except Exception as e:
|
121 |
+
return f"Error generating story: {str(e)}"
|
122 |
+
|
123 |
+
async def generate_speech(text, voice="en-US-AriaNeural"):
|
124 |
+
"""Generate speech from text"""
|
125 |
+
try:
|
126 |
+
communicate = edge_tts.Communicate(text, voice)
|
127 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") as tmp_file:
|
128 |
+
tmp_path = tmp_file.name
|
129 |
+
await communicate.save(tmp_path)
|
130 |
+
return tmp_path
|
131 |
+
except Exception as e:
|
132 |
+
print(f"Error in text2speech: {str(e)}")
|
133 |
+
return None
|
134 |
+
|
135 |
+
def process_story_and_audio(prompt, model_choice):
|
136 |
+
"""Process story, generate audio, and save to gallery"""
|
137 |
+
try:
|
138 |
+
# Generate story
|
139 |
+
story = generate_story(prompt, model_choice)
|
140 |
+
if isinstance(story, str) and story.startswith("Error"):
|
141 |
+
return story, None, None
|
142 |
+
|
143 |
+
# Generate audio
|
144 |
+
audio_path = asyncio.run(generate_speech(story))
|
145 |
+
|
146 |
+
# Save to gallery
|
147 |
+
story_path, saved_audio_path = save_story(story, audio_path)
|
148 |
+
|
149 |
+
return story, audio_path, load_gallery()
|
150 |
+
except Exception as e:
|
151 |
+
return f"Error: {str(e)}", None, None
|
152 |
+
|
153 |
+
def play_gallery_audio(evt: gr.SelectData, gallery_data):
|
154 |
+
"""Play audio from gallery selection"""
|
155 |
+
try:
|
156 |
+
selected_row = gallery_data[evt.index[0]]
|
157 |
+
audio_path = selected_row[3] # Audio path is the fourth element
|
158 |
+
if audio_path and os.path.exists(audio_path):
|
159 |
+
return audio_path
|
160 |
+
return None
|
161 |
+
except Exception as e:
|
162 |
+
print(f"Error playing gallery audio: {str(e)}")
|
163 |
+
return None
|
164 |
+
|
165 |
+
# Create the Gradio interface (keep unchanged)
|
166 |
+
with gr.Blocks(title="AI Story Generator") as demo:
|
167 |
+
gr.Markdown("""
|
168 |
+
# ๐ญ AI Story Generator & Narrator
|
169 |
+
Generate creative stories, listen to them, and build your gallery!
|
170 |
+
""")
|
171 |
+
|
172 |
+
with gr.Row():
|
173 |
+
with gr.Column(scale=3):
|
174 |
+
with gr.Row():
|
175 |
+
prompt_input = gr.Textbox(
|
176 |
+
label="Story Concept",
|
177 |
+
placeholder="Enter your story idea...",
|
178 |
+
lines=3
|
179 |
+
)
|
180 |
+
|
181 |
+
with gr.Row():
|
182 |
+
model_choice = gr.Dropdown(
|
183 |
+
label="Model",
|
184 |
+
choices=[
|
185 |
+
"mistralai/Mixtral-8x7B-Instruct-v0.1",
|
186 |
+
"mistralai/Mistral-7B-Instruct-v0.2"
|
187 |
+
],
|
188 |
+
value="mistralai/Mixtral-8x7B-Instruct-v0.1"
|
189 |
+
)
|
190 |
+
generate_btn = gr.Button("Generate Story")
|
191 |
+
|
192 |
+
with gr.Row():
|
193 |
+
story_output = gr.Textbox(
|
194 |
+
label="Generated Story",
|
195 |
+
lines=10,
|
196 |
+
interactive=False
|
197 |
+
)
|
198 |
+
|
199 |
+
with gr.Row():
|
200 |
+
audio_output = gr.Audio(
|
201 |
+
label="Story Narration",
|
202 |
+
type="filepath"
|
203 |
+
)
|
204 |
+
|
205 |
+
# Sidebar with Story Starters and Gallery
|
206 |
+
with gr.Column(scale=1):
|
207 |
+
gr.Markdown("### ๐ Story Starters")
|
208 |
+
|
209 |
+
gr.Markdown("# ๐ฏ ๐๐ฒ๐๐ฝ๐ป๐ช๐ต ๐ธ๐ฏ ๐๐๐น๐ฎ๐ป๐ฝ๐ผ โก")
|
210 |
+
gr.Markdown("**Abstract**: https://arxiv.org/abs/2401.04088")
|
211 |
+
|
212 |
+
gr.Markdown("# ๐ ๐ฌ๐ผ ๐ช๐ป๐ง๐ฒ๐ฟ: ๐ฎ๐ฐ๐ฌ๐ญ.๐ฌ๐ฐ๐ฌ๐ด๐ด ๐ซ")
|
213 |
+
gr.Markdown("**arxiv**: https://arxiv.org/pdf/2401.04088")
|
214 |
+
|
215 |
+
|
216 |
+
story_starters = gr.Dataframe(
|
217 |
+
value=STORY_STARTERS,
|
218 |
+
headers=["Category", "Starter"],
|
219 |
+
interactive=False
|
220 |
+
)
|
221 |
+
|
222 |
+
gr.Markdown("### ๐ฌ Gallery")
|
223 |
+
gallery = gr.Dataframe(
|
224 |
+
value=load_gallery(),
|
225 |
+
headers=["Timestamp", "Preview", "Story Path", "Audio Path"],
|
226 |
+
interactive=False
|
227 |
+
)
|
228 |
+
|
229 |
+
# Event handlers
|
230 |
+
def update_prompt(evt: gr.SelectData):
|
231 |
+
return STORY_STARTERS[evt.index[0]][1]
|
232 |
+
|
233 |
+
story_starters.select(update_prompt, None, prompt_input)
|
234 |
+
|
235 |
+
generate_btn.click(
|
236 |
+
fn=process_story_and_audio,
|
237 |
+
inputs=[prompt_input, model_choice],
|
238 |
+
outputs=[story_output, audio_output, gallery]
|
239 |
+
)
|
240 |
+
|
241 |
+
gallery.select(
|
242 |
+
fn=play_gallery_audio,
|
243 |
+
inputs=[gallery],
|
244 |
+
outputs=[audio_output]
|
245 |
+
)
|
246 |
+
|
247 |
+
if __name__ == "__main__":
|
248 |
+
demo.launch()
|