cryogenic22 commited on
Commit
99794e5
Β·
verified Β·
1 Parent(s): 1db5789

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +97 -97
app.py CHANGED
@@ -10,11 +10,23 @@ from openai import OpenAI as OpenAIClient
10
  import logging
11
  import requests
12
  import replicate
 
13
 
14
  # Set up logging
15
  logging.basicConfig(level=logging.INFO)
16
  logger = logging.getLogger(__name__)
17
 
 
 
 
 
 
 
 
 
 
 
 
18
  class SearchTool:
19
  def __init__(self):
20
  self.name = "web_search"
@@ -24,10 +36,12 @@ class SearchTool:
24
  def func(self, query: str) -> str:
25
  """Execute the search"""
26
  try:
 
27
  result = self.search.run(query)
 
28
  return result
29
  except Exception as e:
30
- logger.error(f"Search error: {str(e)}")
31
  return f"Error performing search: {str(e)}"
32
 
33
  class ContentGenerator:
@@ -40,6 +54,8 @@ class ContentGenerator:
40
  def generate_quote(self):
41
  """Generate a new spiritual quote using CrewAI"""
42
  try:
 
 
43
  quote_curator = Agent(
44
  role='Quote Curator',
45
  goal='Generate and validate spiritual quotes',
@@ -47,11 +63,12 @@ class ContentGenerator:
47
  tools=[self.search_tool],
48
  llm=self.llm,
49
  verbose=True
 
50
  )
51
 
52
  task = Task(
53
  description="""Generate a profound spiritual quote following these criteria:
54
- 1. Should be from any major spiritual tradition (Buddhism, Hinduism, Taoism, etc.)
55
  2. Must be meaningful and inspiring
56
  3. Include accurate author attribution and tradition
57
  4. Ensure it's authentic and verifiable
@@ -72,12 +89,14 @@ class ContentGenerator:
72
  verbose=True
73
  )
74
 
 
75
  result = crew.kickoff()
76
- logger.info(f"Generated quote result: {result}")
 
77
  return self._parse_quote_result(result)
78
 
79
  except Exception as e:
80
- logger.error(f"Quote generation failed: {str(e)}")
81
  raise
82
 
83
  def _parse_quote_result(self, result):
@@ -85,19 +104,22 @@ class ContentGenerator:
85
  try:
86
  if isinstance(result, str):
87
  result = json.loads(result)
88
- return {
89
  "text": result.get('quote', ''),
90
  "author": result.get('author', ''),
91
  "tradition": result.get('tradition', ''),
92
  "generated_at": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
93
  }
 
 
94
  except Exception as e:
95
- logger.error(f"Error parsing quote result: {str(e)}")
96
  raise
97
 
98
  def generate_image(self, quote, tradition):
99
  """Generate an image using OpenAI DALL-E"""
100
  try:
 
101
  prompt = f"""Create a serene and spiritual image that represents this quote: '{quote}'
102
  From {tradition} tradition.
103
  Style: Minimalistic, inspirational, Instagram-worthy.
@@ -105,6 +127,7 @@ class ContentGenerator:
105
  Colors: Peaceful and harmonious tones.
106
  The image should be suitable for social media and should not include any text."""
107
 
 
108
  response = self.openai_client.images.generate(
109
  model="dall-e-3",
110
  prompt=prompt,
@@ -112,14 +135,16 @@ class ContentGenerator:
112
  quality="standard",
113
  n=1
114
  )
 
115
  return response.data[0].url
116
  except Exception as e:
117
- logger.error(f"Image generation failed: {str(e)}")
118
  raise
119
 
120
  def generate_audio(self, tradition):
121
  """Generate background music using MusicGen"""
122
  try:
 
123
  prompts = {
124
  "Hinduism": "Indian meditation music with soft flute and gentle tabla, peaceful and calming",
125
  "Buddhism": "Tibetan singing bowls with gentle bells and deep resonance, meditative atmosphere",
@@ -128,7 +153,9 @@ class ContentGenerator:
128
  }
129
 
130
  prompt = prompts.get(tradition, prompts["default"])
 
131
 
 
132
  output = self.replicate_client.run(
133
  "meta/musicgen:7be0f12c54a8d0d0d720305c1e6ea10c48d5f0a3afce48478341a0fe682a8787",
134
  input={
@@ -138,12 +165,16 @@ class ContentGenerator:
138
  "output_format": "mp3"
139
  }
140
  )
141
- return output if output else None
 
 
 
 
 
142
  except Exception as e:
143
- logger.error(f"Audio generation failed: {str(e)}")
144
  raise
145
 
146
- # [Rest of the code remains the same...]
147
  def generate_hashtags(tradition):
148
  """Generate relevant hashtags"""
149
  base_tags = ["#spirituality", "#mindfulness", "#wisdom", "#inspiration", "#meditation"]
@@ -155,6 +186,34 @@ def generate_hashtags(tradition):
155
  }
156
  return base_tags + tradition_tags.get(tradition, tradition_tags["default"])
157
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
158
  def main():
159
  st.set_page_config(
160
  page_title="Spiritual Content Generator",
@@ -163,6 +222,8 @@ def main():
163
  )
164
 
165
  # Initialize session state
 
 
166
  if 'generated_content' not in st.session_state:
167
  st.session_state.generated_content = None
168
  if 'generated_image' not in st.session_state:
@@ -179,129 +240,68 @@ def main():
179
  st.stop()
180
 
181
  # Tabs
182
- tab1, tab2 = st.tabs(["Generate Content", "Instagram Preview"])
183
 
184
  with tab1:
185
  st.title("πŸ•‰οΈ Spiritual Content Generator")
186
 
187
  if st.button("Generate New Content", key="generate_button"):
188
  try:
189
- with st.spinner("Generating content..."):
190
  generator = ContentGenerator(
191
  st.secrets["OPENAI_API_KEY"],
192
  st.secrets["REPLICATE_API_TOKEN"]
193
  )
194
 
195
  # Generate quote
196
- with st.status("Generating quote...") as status:
197
  quote_data = generator.generate_quote()
198
  st.session_state.generated_content = quote_data
199
- status.update(label="Quote generated!", state="complete")
200
 
201
  # Generate image
202
- with st.status("Generating image...") as status:
203
  image_url = generator.generate_image(
204
  quote_data["text"],
205
  quote_data["tradition"]
206
  )
207
  st.session_state.generated_image = image_url
208
- status.update(label="Image generated!", state="complete")
209
 
210
  # Generate audio
211
- with st.status("Generating audio...") as status:
212
  audio_url = generator.generate_audio(quote_data["tradition"])
213
  st.session_state.generated_audio = audio_url
214
- status.update(label="Audio generated!", state="complete")
215
 
216
- st.success("All content generated successfully!")
217
 
218
  except Exception as e:
219
  st.error(f"Error during generation: {str(e)}")
220
 
221
  # Display generated content
222
  if st.session_state.generated_content:
 
223
  st.json(st.session_state.generated_content)
224
 
225
  with tab2:
226
- st.title("Instagram Preview")
227
-
228
- if all([st.session_state.generated_content,
229
- st.session_state.generated_image,
230
- st.session_state.generated_audio]):
231
-
232
- col1, col2 = st.columns([2, 1])
233
-
234
- with col1:
235
- # Display generated image with quote overlay
236
- st.image(st.session_state.generated_image, use_column_width=True)
237
-
238
- # Quote overlay
239
- quote = st.session_state.generated_content
240
- st.markdown(f"""
241
- <div style='
242
- background-color: rgba(255,255,255,0.8);
243
- padding: 20px;
244
- border-radius: 10px;
245
- margin: 10px 0;
246
- text-align: center;
247
- '>
248
- <h2>{quote['text']}</h2>
249
- <p>- {quote['author']}</p>
250
- </div>
251
- """, unsafe_allow_html=True)
252
 
253
- with col2:
254
- # Audio preview
255
- st.subheader("🎡 Background Music")
256
- if st.session_state.generated_audio:
257
- st.audio(st.session_state.generated_audio, format='audio/mp3')
258
-
259
- # Caption
260
- st.subheader("πŸ“ Caption")
261
- hashtags = generate_hashtags(quote['tradition'])
262
- caption = f"""✨ Wisdom from {quote['tradition']} ✨
263
-
264
- "{quote['text']}"
265
- - {quote['author']}
266
-
267
- {' '.join(hashtags)}"""
268
-
269
- st.text_area("Instagram Caption", caption, height=200)
270
-
271
- # Download buttons
272
- col1, col2 = st.columns(2)
273
- with col1:
274
- if st.session_state.generated_image:
275
- image_data = requests.get(st.session_state.generated_image).content
276
- st.download_button(
277
- "πŸ“₯ Download Image",
278
- data=image_data,
279
- file_name="spiritual_quote.jpg",
280
- mime="image/jpeg"
281
- )
282
-
283
- with col2:
284
- if st.session_state.generated_audio:
285
- audio_data = requests.get(st.session_state.generated_audio).content
286
- st.download_button(
287
- "πŸ“₯ Download Audio",
288
- data=audio_data,
289
- file_name="background_music.mp3",
290
- mime="audio/mp3"
291
- )
292
-
293
- # Posting tips
294
- st.markdown("""
295
- ### πŸ“± Posting Tips
296
- 1. Download the image and audio
297
- 2. Copy the generated caption
298
- 3. Best posting times: 8-10 AM or 6-8 PM
299
- 4. Engage with your audience about the quote's meaning
300
- 5. Consider creating a Reel with the image and background music
301
- """)
302
-
303
- else:
304
- st.info("Generate content first to see the Instagram preview")
305
 
306
  if __name__ == "__main__":
307
  main()
 
10
  import logging
11
  import requests
12
  import replicate
13
+ import time
14
 
15
  # Set up logging
16
  logging.basicConfig(level=logging.INFO)
17
  logger = logging.getLogger(__name__)
18
 
19
+ def log_message(message, type="info"):
20
+ """Add a message to the session state logs with timestamp"""
21
+ if 'process_logs' not in st.session_state:
22
+ st.session_state.process_logs = []
23
+ timestamp = datetime.now().strftime("%H:%M:%S")
24
+ st.session_state.process_logs.append({
25
+ "timestamp": timestamp,
26
+ "message": message,
27
+ "type": type
28
+ })
29
+
30
  class SearchTool:
31
  def __init__(self):
32
  self.name = "web_search"
 
36
  def func(self, query: str) -> str:
37
  """Execute the search"""
38
  try:
39
+ log_message(f"πŸ” Searching for: {query}")
40
  result = self.search.run(query)
41
+ log_message(f"βœ“ Search completed")
42
  return result
43
  except Exception as e:
44
+ log_message(f"❌ Search error: {str(e)}", "error")
45
  return f"Error performing search: {str(e)}"
46
 
47
  class ContentGenerator:
 
54
  def generate_quote(self):
55
  """Generate a new spiritual quote using CrewAI"""
56
  try:
57
+ log_message("🎯 Starting quote generation process")
58
+
59
  quote_curator = Agent(
60
  role='Quote Curator',
61
  goal='Generate and validate spiritual quotes',
 
63
  tools=[self.search_tool],
64
  llm=self.llm,
65
  verbose=True
66
+ max_iterations=3
67
  )
68
 
69
  task = Task(
70
  description="""Generate a profound spiritual quote following these criteria:
71
+ 1. Should be from any major spiritual tradition (Buddhism, Hinduism, Taoism, stoicism, sufism etc.)
72
  2. Must be meaningful and inspiring
73
  3. Include accurate author attribution and tradition
74
  4. Ensure it's authentic and verifiable
 
89
  verbose=True
90
  )
91
 
92
+ log_message("πŸ€– Agent starting task...")
93
  result = crew.kickoff()
94
+ log_message("✨ Quote generation completed successfully")
95
+
96
  return self._parse_quote_result(result)
97
 
98
  except Exception as e:
99
+ log_message(f"❌ Quote generation failed: {str(e)}", "error")
100
  raise
101
 
102
  def _parse_quote_result(self, result):
 
104
  try:
105
  if isinstance(result, str):
106
  result = json.loads(result)
107
+ parsed_result = {
108
  "text": result.get('quote', ''),
109
  "author": result.get('author', ''),
110
  "tradition": result.get('tradition', ''),
111
  "generated_at": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
112
  }
113
+ log_message(f"πŸ“ Generated quote: '{parsed_result['text']}' - {parsed_result['author']}")
114
+ return parsed_result
115
  except Exception as e:
116
+ log_message(f"❌ Error parsing quote result: {str(e)}", "error")
117
  raise
118
 
119
  def generate_image(self, quote, tradition):
120
  """Generate an image using OpenAI DALL-E"""
121
  try:
122
+ log_message("🎨 Starting image generation")
123
  prompt = f"""Create a serene and spiritual image that represents this quote: '{quote}'
124
  From {tradition} tradition.
125
  Style: Minimalistic, inspirational, Instagram-worthy.
 
127
  Colors: Peaceful and harmonious tones.
128
  The image should be suitable for social media and should not include any text."""
129
 
130
+ log_message(f"πŸ“€ Sending prompt to DALL-E")
131
  response = self.openai_client.images.generate(
132
  model="dall-e-3",
133
  prompt=prompt,
 
135
  quality="standard",
136
  n=1
137
  )
138
+ log_message("✨ Image generated successfully")
139
  return response.data[0].url
140
  except Exception as e:
141
+ log_message(f"❌ Image generation failed: {str(e)}", "error")
142
  raise
143
 
144
  def generate_audio(self, tradition):
145
  """Generate background music using MusicGen"""
146
  try:
147
+ log_message("🎡 Starting audio generation")
148
  prompts = {
149
  "Hinduism": "Indian meditation music with soft flute and gentle tabla, peaceful and calming",
150
  "Buddhism": "Tibetan singing bowls with gentle bells and deep resonance, meditative atmosphere",
 
153
  }
154
 
155
  prompt = prompts.get(tradition, prompts["default"])
156
+ log_message(f"🎼 Selected music style: {tradition}")
157
 
158
+ log_message("πŸ“€ Sending prompt to MusicGen")
159
  output = self.replicate_client.run(
160
  "meta/musicgen:7be0f12c54a8d0d0d720305c1e6ea10c48d5f0a3afce48478341a0fe682a8787",
161
  input={
 
165
  "output_format": "mp3"
166
  }
167
  )
168
+
169
+ if output:
170
+ log_message("✨ Audio generated successfully")
171
+ return output
172
+ else:
173
+ raise Exception("No output received from MusicGen")
174
  except Exception as e:
175
+ log_message(f"❌ Audio generation failed: {str(e)}", "error")
176
  raise
177
 
 
178
  def generate_hashtags(tradition):
179
  """Generate relevant hashtags"""
180
  base_tags = ["#spirituality", "#mindfulness", "#wisdom", "#inspiration", "#meditation"]
 
186
  }
187
  return base_tags + tradition_tags.get(tradition, tradition_tags["default"])
188
 
189
+ def display_debug_logs():
190
+ """Display debug logs with enhanced visualization"""
191
+ st.markdown("### πŸ” Process Logs")
192
+
193
+ # Create tabs for different log views
194
+ log_tabs = st.tabs(["All Logs", "Errors Only", "Timeline View"])
195
+
196
+ with log_tabs[0]:
197
+ for log in st.session_state.process_logs:
198
+ if log["type"] == "error":
199
+ st.error(f"{log['timestamp']} - {log['message']}")
200
+ else:
201
+ st.text(f"{log['timestamp']} - {log['message']}")
202
+
203
+ with log_tabs[1]:
204
+ errors = [log for log in st.session_state.process_logs if log["type"] == "error"]
205
+ if errors:
206
+ for error in errors:
207
+ st.error(f"{error['timestamp']} - {error['message']}")
208
+ else:
209
+ st.success("No errors found! πŸŽ‰")
210
+
211
+ with log_tabs[2]:
212
+ st.markdown("#### Generation Timeline")
213
+ for log in st.session_state.process_logs:
214
+ with st.expander(f"{log['timestamp']} - {log['message'][:50]}..."):
215
+ st.text(log['message'])
216
+
217
  def main():
218
  st.set_page_config(
219
  page_title="Spiritual Content Generator",
 
222
  )
223
 
224
  # Initialize session state
225
+ if 'process_logs' not in st.session_state:
226
+ st.session_state.process_logs = []
227
  if 'generated_content' not in st.session_state:
228
  st.session_state.generated_content = None
229
  if 'generated_image' not in st.session_state:
 
240
  st.stop()
241
 
242
  # Tabs
243
+ tab1, tab2, tab3 = st.tabs(["Generate Content", "Instagram Preview", "Debug Log"])
244
 
245
  with tab1:
246
  st.title("πŸ•‰οΈ Spiritual Content Generator")
247
 
248
  if st.button("Generate New Content", key="generate_button"):
249
  try:
250
+ with st.spinner("Initializing content generation..."):
251
  generator = ContentGenerator(
252
  st.secrets["OPENAI_API_KEY"],
253
  st.secrets["REPLICATE_API_TOKEN"]
254
  )
255
 
256
  # Generate quote
257
+ with st.status("Generating spiritual quote...") as status:
258
  quote_data = generator.generate_quote()
259
  st.session_state.generated_content = quote_data
260
+ status.update(label="Quote generated successfully!", state="complete")
261
 
262
  # Generate image
263
+ with st.status("Creating visual representation...") as status:
264
  image_url = generator.generate_image(
265
  quote_data["text"],
266
  quote_data["tradition"]
267
  )
268
  st.session_state.generated_image = image_url
269
+ status.update(label="Image generated successfully!", state="complete")
270
 
271
  # Generate audio
272
+ with st.status("Composing background music...") as status:
273
  audio_url = generator.generate_audio(quote_data["tradition"])
274
  st.session_state.generated_audio = audio_url
275
+ status.update(label="Audio generated successfully!", state="complete")
276
 
277
+ st.success("✨ All content generated successfully!")
278
 
279
  except Exception as e:
280
  st.error(f"Error during generation: {str(e)}")
281
 
282
  # Display generated content
283
  if st.session_state.generated_content:
284
+ st.subheader("Generated Content Details")
285
  st.json(st.session_state.generated_content)
286
 
287
  with tab2:
288
+ # [Previous Instagram Preview tab code remains the same...]
289
+ pass
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
290
 
291
+ with tab3:
292
+ st.title("πŸ” Debug & Process Logs")
293
+
294
+ # Add refresh button for logs
295
+ col1, col2 = st.columns([4, 1])
296
+ with col2:
297
+ if st.button("πŸ”„ Refresh Logs"):
298
+ st.rerun()
299
+ if st.button("πŸ—‘οΈ Clear Logs"):
300
+ st.session_state.process_logs = []
301
+ st.rerun()
302
+
303
+ # Display logs
304
+ display_debug_logs()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
305
 
306
  if __name__ == "__main__":
307
  main()