awacke1 commited on
Commit
a74315c
ยท
verified ยท
1 Parent(s): a0ebdf1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +61 -71
app.py CHANGED
@@ -12,64 +12,53 @@ import json
12
  import pandas as pd
13
  from pathlib import Path
14
  from gradio_client import Client
15
- import hashlib
16
 
17
  warnings.filterwarnings('ignore')
18
 
19
- # Initialize story starters
20
  STORY_STARTERS = [
21
  ['Adventure', 'In a hidden temple deep in the Amazon...'],
22
  ['Mystery', 'The detective found an unusual note...'],
23
  ['Romance', 'Two strangers meet on a rainy evening...'],
24
  ['Sci-Fi', 'The space station received an unexpected signal...'],
25
- ['Fantasy', 'A magical portal appeared in the garden...']
 
 
 
 
 
26
  ]
27
 
28
  # Initialize client outside of interface definition
29
  arxiv_client = None
30
 
31
- def sanitize_filename(text, max_length=50):
32
- """Create a safe filename from text"""
33
- # Get first line or first few words
34
- first_line = text.split('\n')[0].strip()
35
- # Remove special characters and spaces
36
- safe_name = re.sub(r'[^\w\s-]', '', first_line)
37
- safe_name = re.sub(r'[-\s]+', '-', safe_name).strip('-')
38
- # Truncate to max length while keeping words intact
39
- if len(safe_name) > max_length:
40
- safe_name = safe_name[:max_length].rsplit('-', 1)[0]
41
- return safe_name.lower()
42
-
43
- def generate_unique_filename(base_name, timestamp, extension):
44
- """Generate a unique filename with timestamp and hash"""
45
- # Create a hash of the base name to ensure uniqueness
46
- name_hash = hashlib.md5(base_name.encode()).hexdigest()[:6]
47
- return f"{timestamp}_{base_name}_{name_hash}{extension}"
48
 
49
  def save_story(story, audio_path):
50
- """Save story and audio to gallery with improved naming"""
51
  try:
52
  # Create gallery directory if it doesn't exist
53
  gallery_dir = Path("gallery")
54
  gallery_dir.mkdir(exist_ok=True)
55
 
56
- # Generate timestamp and safe filename base
57
  timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
58
- safe_name = sanitize_filename(story)
59
-
60
- # Generate unique filenames
61
- story_filename = generate_unique_filename(safe_name, timestamp, ".md")
62
- audio_filename = generate_unique_filename(safe_name, timestamp, ".mp3")
63
 
64
  # Save story text as markdown
65
- story_path = gallery_dir / story_filename
66
  with open(story_path, "w") as f:
67
- f.write(f"# {safe_name.replace('-', ' ').title()}\n\n{story}")
68
 
69
- # Copy audio file to gallery with new name
70
  new_audio_path = None
71
  if audio_path:
72
- new_audio_path = gallery_dir / audio_filename
73
  os.system(f"cp {audio_path} {str(new_audio_path)}")
74
 
75
  return str(story_path), str(new_audio_path) if new_audio_path else None
@@ -77,48 +66,35 @@ def save_story(story, audio_path):
77
  print(f"Error saving to gallery: {str(e)}")
78
  return None, None
79
 
80
- def format_gallery_entry(timestamp, preview, story_path, audio_path):
81
- """Format gallery entry as markdown with audio controls"""
82
- story_link = f"[{preview}]({story_path})"
83
- if audio_path:
84
- audio_html = f'<audio controls><source src="{audio_path}" type="audio/mp3">Your browser does not support the audio element.</audio>'
85
- return f"{timestamp}: {story_link}\n{audio_html}"
86
- return f"{timestamp}: {story_link}"
87
-
88
  def load_gallery():
89
- """Load all stories and audio from gallery with markdown formatting"""
90
  try:
91
  gallery_dir = Path("gallery")
92
  if not gallery_dir.exists():
93
  return []
94
 
95
  files = []
96
- for story_file in sorted(gallery_dir.glob("*.md"), reverse=True):
97
- # Extract timestamp from filename
98
- timestamp = story_file.stem.split('_')[0]
99
-
100
- # Read story content
101
- with open(story_file) as f:
102
- story_text = f.read()
103
- # Extract preview from content (skip markdown header)
104
- preview = story_text.split('\n\n', 1)[1][:100] + "..."
105
 
106
  # Find matching audio file
107
- audio_file = gallery_dir / f"{story_file.stem}.mp3"
 
 
108
 
109
- # Format as markdown with audio controls
110
- formatted_entry = format_gallery_entry(
111
- timestamp,
112
- preview,
113
- str(story_file),
114
- str(audio_file) if audio_file.exists() else None
115
- )
116
 
117
  files.append([
118
  timestamp,
119
- formatted_entry,
120
  str(story_file),
121
- str(audio_file) if audio_file.exists() else None
122
  ])
123
 
124
  return files
@@ -126,7 +102,7 @@ def load_gallery():
126
  print(f"Error loading gallery: {str(e)}")
127
  return []
128
 
129
- # Rest of your existing functions remain the same
130
  def generate_story(prompt, model_choice):
131
  """Generate story using specified model"""
132
  try:
@@ -174,7 +150,19 @@ def process_story_and_audio(prompt, model_choice):
174
  except Exception as e:
175
  return f"Error: {str(e)}", None, None
176
 
177
- # Create the Gradio interface
 
 
 
 
 
 
 
 
 
 
 
 
178
  with gr.Blocks(title="AI Story Generator") as demo:
179
  gr.Markdown("""
180
  # ๐ŸŽญ AI Story Generator & Narrator
@@ -223,16 +211,12 @@ with gr.Blocks(title="AI Story Generator") as demo:
223
  interactive=False
224
  )
225
 
226
- gr.Markdown("### ๐ŸŽฌ Story Gallery")
227
- gallery = gr.HTML(value="")
228
-
229
- def update_gallery():
230
- gallery_entries = load_gallery()
231
- if not gallery_entries:
232
- return "<p>No stories in gallery yet.</p>"
233
- return "<br>".join(entry[1] for entry in gallery_entries)
234
-
235
- demo.load(update_gallery, outputs=[gallery])
236
 
237
  # Event handlers
238
  def update_prompt(evt: gr.SelectData):
@@ -245,6 +229,12 @@ with gr.Blocks(title="AI Story Generator") as demo:
245
  inputs=[prompt_input, model_choice],
246
  outputs=[story_output, audio_output, gallery]
247
  )
 
 
 
 
 
 
248
 
249
  if __name__ == "__main__":
250
  demo.launch()
 
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
 
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
 
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:
 
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
 
211
  interactive=False
212
  )
213
 
214
+ gr.Markdown("### ๐ŸŽฌ Gallery")
215
+ gallery = gr.Dataframe(
216
+ value=load_gallery(),
217
+ headers=["Timestamp", "Preview", "Story Path", "Audio Path"],
218
+ interactive=False
219
+ )
 
 
 
 
220
 
221
  # Event handlers
222
  def update_prompt(evt: gr.SelectData):
 
229
  inputs=[prompt_input, model_choice],
230
  outputs=[story_output, audio_output, gallery]
231
  )
232
+
233
+ gallery.select(
234
+ fn=play_gallery_audio,
235
+ inputs=[gallery],
236
+ outputs=[audio_output]
237
+ )
238
 
239
  if __name__ == "__main__":
240
  demo.launch()