cryogenic22 commited on
Commit
085e2ba
Β·
verified Β·
1 Parent(s): 2ee7c81

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +48 -37
app.py CHANGED
@@ -14,6 +14,7 @@ import random
14
  logging.basicConfig(level=logging.INFO)
15
  logger = logging.getLogger(__name__)
16
 
 
17
  def log_message(message, type="info"):
18
  """Add a message to the session state logs with timestamp"""
19
  if 'process_logs' not in st.session_state:
@@ -25,9 +26,10 @@ def log_message(message, type="info"):
25
  "type": type
26
  })
27
 
 
28
  class SpiritualThemes:
29
  """Diverse spiritual themes for content generation"""
30
-
31
  TRADITIONS = {
32
  "Eastern": [
33
  "Buddhism", "Hinduism", "Taoism", "Zen", "Vedanta",
@@ -46,7 +48,7 @@ class SpiritualThemes:
46
  "Integrative Spirituality", "Secular Wisdom"
47
  ]
48
  }
49
-
50
  THEMES = [
51
  "Inner Peace", "Mindfulness", "Compassion", "Wisdom",
52
  "Self-Discovery", "Unity", "Balance", "Transformation",
@@ -54,7 +56,7 @@ class SpiritualThemes:
54
  "Love", "Harmony", "Truth", "Liberation", "Service",
55
  "Connection", "Growth", "Awareness"
56
  ]
57
-
58
  QUOTE_STYLES = [
59
  "contemplative", "inspirational", "philosophical",
60
  "practical wisdom", "mystical insight", "ancient teaching",
@@ -62,6 +64,7 @@ class SpiritualThemes:
62
  "meditation guidance"
63
  ]
64
 
 
65
  class ContentGenerator:
66
  def __init__(self, openai_api_key, replicate_api_key):
67
  self.llm = OpenAI(api_key=openai_api_key, temperature=0.7)
@@ -74,7 +77,7 @@ class ContentGenerator:
74
  traditions = SpiritualThemes.TRADITIONS[tradition_category]
75
  themes = random.sample(SpiritualThemes.THEMES, 2)
76
  style = random.choice(SpiritualThemes.QUOTE_STYLES)
77
-
78
  return f"""Focus on {tradition_category} wisdom, particularly from {', '.join(traditions)}.
79
  Explore themes of {themes[0]} and {themes[1]} in a {style} style.
80
  Ensure the quote is profound yet accessible for social media."""
@@ -117,9 +120,9 @@ class ContentGenerator:
117
  """Generate a new spiritual quote with enhanced variety"""
118
  try:
119
  log_message("🎯 Starting quote generation process")
120
-
121
  prompt_variation = self._generate_prompt_variation()
122
-
123
  quote_curator = Agent(
124
  role='Quote Curator',
125
  goal='Generate diverse and profound spiritual quotes',
@@ -134,13 +137,13 @@ class ContentGenerator:
134
  task = Task(
135
  description=f"""Generate a spiritual quote following these criteria:
136
  {prompt_variation}
137
-
138
  Requirements:
139
  1. Ensure quote authenticity and proper attribution
140
  2. Balance depth with accessibility
141
  3. Keep length appropriate for Instagram
142
  4. Include cultural context if relevant
143
-
144
  Return ONLY a JSON object in this exact format, with no additional text:
145
  {{
146
  "quote": "The actual quote text",
@@ -149,12 +152,12 @@ class ContentGenerator:
149
  "theme": "The main theme"
150
  }}""",
151
  expected_output="""Plain JSON object with no markdown formatting:
152
- {
153
  "quote": "The quote text",
154
  "author": "Author name",
155
  "tradition": "Spiritual tradition",
156
  "theme": "Main theme"
157
- }""",
158
  agent=quote_curator
159
  )
160
 
@@ -167,7 +170,7 @@ class ContentGenerator:
167
  result = crew.kickoff()
168
  log_message("✨ Quote generation completed successfully")
169
  return self._parse_quote_result(result)
170
-
171
  except Exception as e:
172
  log_message(f"❌ Quote generation failed: {str(e)}", "error")
173
  return self._get_fallback_quote()
@@ -177,24 +180,24 @@ class ContentGenerator:
177
  try:
178
  log_message(f"Raw result type: {type(result)}")
179
  log_message(f"Raw result content: {result}")
180
-
181
  # Handle CrewOutput object
182
  if hasattr(result, 'result'):
183
  result_str = str(result.result)
184
  else:
185
  result_str = str(result)
186
-
187
  log_message(f"Processing result string: {result_str}")
188
-
189
  # Clean the string and extract JSON
190
  result_str = result_str.strip()
191
  if result_str.startswith("```json"):
192
  result_str = result_str[7:-3] # Remove ```json and ``` markers
193
-
194
  # Parse the JSON
195
  parsed_json = json.loads(result_str)
196
  log_message(f"Parsed JSON: {parsed_json}")
197
-
198
  return {
199
  "text": parsed_json.get('quote', ''),
200
  "author": parsed_json.get('author', ''),
@@ -211,7 +214,7 @@ class ContentGenerator:
211
  """Generate an image using OpenAI DALL-E with enhanced prompts"""
212
  try:
213
  log_message("🎨 Starting image generation")
214
-
215
  style_prompts = {
216
  "Buddhism": "zen minimalism, misty mountains, lotus flowers",
217
  "Hinduism": "mandala patterns, sacred geometry, vibrant cosmos",
@@ -222,9 +225,9 @@ class ContentGenerator:
222
  "Indigenous": "natural elements, earth tones, tribal patterns",
223
  "default": "serene minimalism, sacred geometry, natural elements"
224
  }
225
-
226
  style = style_prompts.get(tradition, style_prompts["default"])
227
-
228
  prompt = f"""Create a spiritual and contemplative image inspired by this theme: '{theme}'
229
  Style inspiration: {style}
230
  Mood: serene, inspiring, contemplative
@@ -253,10 +256,10 @@ class ContentGenerator:
253
  """Generate background music using MusicGen"""
254
  try:
255
  log_message("🎡 Starting audio generation")
256
-
257
  tradition_prompts = music_prompts.get(tradition, music_prompts["default"])
258
  prompt = tradition_prompts.get(theme, tradition_prompts["default"])
259
-
260
  # Get the audio file URL
261
  output = self.replicate_client.run(
262
  "meta/musicgen:671ac645ce5e552cc63a54a2bbff63fcf798043055d2dac5fc9e36a837eedcfb",
@@ -268,7 +271,7 @@ class ContentGenerator:
268
  "duration": 15
269
  }
270
  )
271
-
272
  # Convert FileOutput to URL if needed
273
  if hasattr(output, 'url'):
274
  audio_url = output.url
@@ -276,27 +279,28 @@ class ContentGenerator:
276
  audio_url = output
277
  else:
278
  audio_url = str(output)
279
-
280
  log_message("✨ Audio generated successfully")
281
  return audio_url
282
  except Exception as e:
283
  log_message(f"❌ Audio generation failed: {str(e)}", "error")
284
  raise
285
 
286
- def display_debug_logs():
 
287
  """Display debug logs with enhanced visualization"""
288
  st.markdown("### πŸ” Process Logs")
289
-
290
  # Create tabs for different log views
291
  log_tabs = st.tabs(["All Logs", "Errors Only", "Timeline"])
292
-
293
  with log_tabs[0]:
294
  for log in st.session_state.process_logs:
295
  if log["type"] == "error":
296
  st.error(f"{log['timestamp']} - {log['message']}")
297
  else:
298
  st.info(f"{log['timestamp']} - {log['message']}")
299
-
300
  with log_tabs[1]:
301
  errors = [log for log in st.session_state.process_logs if log["type"] == "error"]
302
  if errors:
@@ -304,14 +308,15 @@ class ContentGenerator:
304
  st.error(f"{error['timestamp']} - {error['message']}")
305
  else:
306
  st.success("No errors found! πŸŽ‰")
307
-
308
  with log_tabs[2]:
309
  st.markdown("#### Generation Timeline")
310
  for log in st.session_state.process_logs:
311
  with st.expander(f"{log['timestamp']} - {log['message'][:50]}...", expanded=False):
312
  st.text(log['message'])
313
 
314
- def generate_hashtags(tradition, theme):
 
315
  """Generate relevant hashtags"""
316
  base_tags = ["#spirituality", "#mindfulness", "#wisdom", "#inspiration", "#meditation"]
317
  tradition_tags = {
@@ -327,10 +332,11 @@ class ContentGenerator:
327
  "Wisdom": ["#wisdom", "#truth", "#knowledge", "#insight"],
328
  "Transformation": ["#transform", "#change", "#evolution", "#journey"]
329
  }
330
-
331
  custom_tags = tradition_tags.get(tradition, []) + theme_tags.get(theme, [])
332
  return list(set(base_tags + custom_tags))[:15]
333
 
 
334
  def main():
335
  st.set_page_config(
336
  page_title="Spiritual Content Generator",
@@ -361,7 +367,7 @@ def main():
361
 
362
  with tab1:
363
  st.title("πŸ•‰οΈ Spiritual Content Generator")
364
-
365
  if st.button("Generate New Content", key="generate_button"):
366
  try:
367
  with st.spinner("Initializing content generation..."):
@@ -369,13 +375,13 @@ def main():
369
  st.secrets["OPENAI_API_KEY"],
370
  st.secrets["REPLICATE_API_TOKEN"]
371
  )
372
-
373
  # Generate quote
374
  with st.status("Generating spiritual quote...") as status:
375
  quote_data = generator.generate_quote()
376
  st.session_state.generated_content = quote_data
377
  status.update(label="Quote generated successfully!", state="complete")
378
-
379
  # Generate image
380
  with st.status("Creating visual representation...") as status:
381
  image_url = generator.generate_image(
@@ -385,7 +391,7 @@ def main():
385
  )
386
  st.session_state.generated_image = image_url
387
  status.update(label="Image generated successfully!", state="complete")
388
-
389
  # Generate audio
390
  with st.status("Composing background music...") as status:
391
  audio_url = generator.generate_audio(
@@ -394,7 +400,7 @@ def main():
394
  )
395
  st.session_state.generated_audio = audio_url
396
  status.update(label="Audio generated successfully!", state="complete")
397
-
398
  st.success("✨ All content generated successfully!")
399
 
400
  except Exception as e:
@@ -405,7 +411,12 @@ def main():
405
  st.subheader("Generated Content Details")
406
  st.json(st.session_state.generated_content)
407
 
408
- with col2:
 
 
 
 
 
409
  # Audio preview
410
  st.subheader("🎡 Background Music")
411
  if st.session_state.generated_audio:
@@ -415,7 +426,7 @@ def main():
415
  if audio_response.status_code == 200:
416
  # Create audio player
417
  st.audio(audio_response.content, format='audio/mp3')
418
-
419
  # Download button for audio
420
  st.download_button(
421
  "πŸ“₯ Download Audio",
 
14
  logging.basicConfig(level=logging.INFO)
15
  logger = logging.getLogger(__name__)
16
 
17
+
18
  def log_message(message, type="info"):
19
  """Add a message to the session state logs with timestamp"""
20
  if 'process_logs' not in st.session_state:
 
26
  "type": type
27
  })
28
 
29
+
30
  class SpiritualThemes:
31
  """Diverse spiritual themes for content generation"""
32
+
33
  TRADITIONS = {
34
  "Eastern": [
35
  "Buddhism", "Hinduism", "Taoism", "Zen", "Vedanta",
 
48
  "Integrative Spirituality", "Secular Wisdom"
49
  ]
50
  }
51
+
52
  THEMES = [
53
  "Inner Peace", "Mindfulness", "Compassion", "Wisdom",
54
  "Self-Discovery", "Unity", "Balance", "Transformation",
 
56
  "Love", "Harmony", "Truth", "Liberation", "Service",
57
  "Connection", "Growth", "Awareness"
58
  ]
59
+
60
  QUOTE_STYLES = [
61
  "contemplative", "inspirational", "philosophical",
62
  "practical wisdom", "mystical insight", "ancient teaching",
 
64
  "meditation guidance"
65
  ]
66
 
67
+
68
  class ContentGenerator:
69
  def __init__(self, openai_api_key, replicate_api_key):
70
  self.llm = OpenAI(api_key=openai_api_key, temperature=0.7)
 
77
  traditions = SpiritualThemes.TRADITIONS[tradition_category]
78
  themes = random.sample(SpiritualThemes.THEMES, 2)
79
  style = random.choice(SpiritualThemes.QUOTE_STYLES)
80
+
81
  return f"""Focus on {tradition_category} wisdom, particularly from {', '.join(traditions)}.
82
  Explore themes of {themes[0]} and {themes[1]} in a {style} style.
83
  Ensure the quote is profound yet accessible for social media."""
 
120
  """Generate a new spiritual quote with enhanced variety"""
121
  try:
122
  log_message("🎯 Starting quote generation process")
123
+
124
  prompt_variation = self._generate_prompt_variation()
125
+
126
  quote_curator = Agent(
127
  role='Quote Curator',
128
  goal='Generate diverse and profound spiritual quotes',
 
137
  task = Task(
138
  description=f"""Generate a spiritual quote following these criteria:
139
  {prompt_variation}
140
+
141
  Requirements:
142
  1. Ensure quote authenticity and proper attribution
143
  2. Balance depth with accessibility
144
  3. Keep length appropriate for Instagram
145
  4. Include cultural context if relevant
146
+
147
  Return ONLY a JSON object in this exact format, with no additional text:
148
  {{
149
  "quote": "The actual quote text",
 
152
  "theme": "The main theme"
153
  }}""",
154
  expected_output="""Plain JSON object with no markdown formatting:
155
+ {{
156
  "quote": "The quote text",
157
  "author": "Author name",
158
  "tradition": "Spiritual tradition",
159
  "theme": "Main theme"
160
+ }}""",
161
  agent=quote_curator
162
  )
163
 
 
170
  result = crew.kickoff()
171
  log_message("✨ Quote generation completed successfully")
172
  return self._parse_quote_result(result)
173
+
174
  except Exception as e:
175
  log_message(f"❌ Quote generation failed: {str(e)}", "error")
176
  return self._get_fallback_quote()
 
180
  try:
181
  log_message(f"Raw result type: {type(result)}")
182
  log_message(f"Raw result content: {result}")
183
+
184
  # Handle CrewOutput object
185
  if hasattr(result, 'result'):
186
  result_str = str(result.result)
187
  else:
188
  result_str = str(result)
189
+
190
  log_message(f"Processing result string: {result_str}")
191
+
192
  # Clean the string and extract JSON
193
  result_str = result_str.strip()
194
  if result_str.startswith("```json"):
195
  result_str = result_str[7:-3] # Remove ```json and ``` markers
196
+
197
  # Parse the JSON
198
  parsed_json = json.loads(result_str)
199
  log_message(f"Parsed JSON: {parsed_json}")
200
+
201
  return {
202
  "text": parsed_json.get('quote', ''),
203
  "author": parsed_json.get('author', ''),
 
214
  """Generate an image using OpenAI DALL-E with enhanced prompts"""
215
  try:
216
  log_message("🎨 Starting image generation")
217
+
218
  style_prompts = {
219
  "Buddhism": "zen minimalism, misty mountains, lotus flowers",
220
  "Hinduism": "mandala patterns, sacred geometry, vibrant cosmos",
 
225
  "Indigenous": "natural elements, earth tones, tribal patterns",
226
  "default": "serene minimalism, sacred geometry, natural elements"
227
  }
228
+
229
  style = style_prompts.get(tradition, style_prompts["default"])
230
+
231
  prompt = f"""Create a spiritual and contemplative image inspired by this theme: '{theme}'
232
  Style inspiration: {style}
233
  Mood: serene, inspiring, contemplative
 
256
  """Generate background music using MusicGen"""
257
  try:
258
  log_message("🎡 Starting audio generation")
259
+
260
  tradition_prompts = music_prompts.get(tradition, music_prompts["default"])
261
  prompt = tradition_prompts.get(theme, tradition_prompts["default"])
262
+
263
  # Get the audio file URL
264
  output = self.replicate_client.run(
265
  "meta/musicgen:671ac645ce5e552cc63a54a2bbff63fcf798043055d2dac5fc9e36a837eedcfb",
 
271
  "duration": 15
272
  }
273
  )
274
+
275
  # Convert FileOutput to URL if needed
276
  if hasattr(output, 'url'):
277
  audio_url = output.url
 
279
  audio_url = output
280
  else:
281
  audio_url = str(output)
282
+
283
  log_message("✨ Audio generated successfully")
284
  return audio_url
285
  except Exception as e:
286
  log_message(f"❌ Audio generation failed: {str(e)}", "error")
287
  raise
288
 
289
+
290
+ def display_debug_logs():
291
  """Display debug logs with enhanced visualization"""
292
  st.markdown("### πŸ” Process Logs")
293
+
294
  # Create tabs for different log views
295
  log_tabs = st.tabs(["All Logs", "Errors Only", "Timeline"])
296
+
297
  with log_tabs[0]:
298
  for log in st.session_state.process_logs:
299
  if log["type"] == "error":
300
  st.error(f"{log['timestamp']} - {log['message']}")
301
  else:
302
  st.info(f"{log['timestamp']} - {log['message']}")
303
+
304
  with log_tabs[1]:
305
  errors = [log for log in st.session_state.process_logs if log["type"] == "error"]
306
  if errors:
 
308
  st.error(f"{error['timestamp']} - {error['message']}")
309
  else:
310
  st.success("No errors found! πŸŽ‰")
311
+
312
  with log_tabs[2]:
313
  st.markdown("#### Generation Timeline")
314
  for log in st.session_state.process_logs:
315
  with st.expander(f"{log['timestamp']} - {log['message'][:50]}...", expanded=False):
316
  st.text(log['message'])
317
 
318
+
319
+ def generate_hashtags(tradition, theme):
320
  """Generate relevant hashtags"""
321
  base_tags = ["#spirituality", "#mindfulness", "#wisdom", "#inspiration", "#meditation"]
322
  tradition_tags = {
 
332
  "Wisdom": ["#wisdom", "#truth", "#knowledge", "#insight"],
333
  "Transformation": ["#transform", "#change", "#evolution", "#journey"]
334
  }
335
+
336
  custom_tags = tradition_tags.get(tradition, []) + theme_tags.get(theme, [])
337
  return list(set(base_tags + custom_tags))[:15]
338
 
339
+
340
  def main():
341
  st.set_page_config(
342
  page_title="Spiritual Content Generator",
 
367
 
368
  with tab1:
369
  st.title("πŸ•‰οΈ Spiritual Content Generator")
370
+
371
  if st.button("Generate New Content", key="generate_button"):
372
  try:
373
  with st.spinner("Initializing content generation..."):
 
375
  st.secrets["OPENAI_API_KEY"],
376
  st.secrets["REPLICATE_API_TOKEN"]
377
  )
378
+
379
  # Generate quote
380
  with st.status("Generating spiritual quote...") as status:
381
  quote_data = generator.generate_quote()
382
  st.session_state.generated_content = quote_data
383
  status.update(label="Quote generated successfully!", state="complete")
384
+
385
  # Generate image
386
  with st.status("Creating visual representation...") as status:
387
  image_url = generator.generate_image(
 
391
  )
392
  st.session_state.generated_image = image_url
393
  status.update(label="Image generated successfully!", state="complete")
394
+
395
  # Generate audio
396
  with st.status("Composing background music...") as status:
397
  audio_url = generator.generate_audio(
 
400
  )
401
  st.session_state.generated_audio = audio_url
402
  status.update(label="Audio generated successfully!", state="complete")
403
+
404
  st.success("✨ All content generated successfully!")
405
 
406
  except Exception as e:
 
411
  st.subheader("Generated Content Details")
412
  st.json(st.session_state.generated_content)
413
 
414
+ with tab2: # This was corrected from 'col2'
415
+ # Image preview (this was missing)
416
+ st.subheader("πŸ–ΌοΈ Generated Image")
417
+ if st.session_state.generated_image:
418
+ st.image(st.session_state.generated_image, caption="Generated Image")
419
+
420
  # Audio preview
421
  st.subheader("🎡 Background Music")
422
  if st.session_state.generated_audio:
 
426
  if audio_response.status_code == 200:
427
  # Create audio player
428
  st.audio(audio_response.content, format='audio/mp3')
429
+
430
  # Download button for audio
431
  st.download_button(
432
  "πŸ“₯ Download Audio",