cryogenic22 commited on
Commit
3d7449a
·
verified ·
1 Parent(s): f4a803e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +211 -1
app.py CHANGED
@@ -62,7 +62,217 @@ class SpiritualThemes:
62
  "meditation guidance"
63
  ]
64
 
65
- [Previous ContentGenerator class code goes here]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66
 
67
  def display_debug_logs():
68
  """Display debug logs with enhanced visualization"""
 
62
  "meditation guidance"
63
  ]
64
 
65
+
66
+ class ContentGenerator:
67
+ def __init__(self, openai_api_key, replicate_api_key):
68
+ self.llm = OpenAI(api_key=openai_api_key, temperature=0.7)
69
+ self.openai_client = OpenAIClient(api_key=openai_api_key)
70
+ self.replicate_client = replicate.Client(api_token=replicate_api_key)
71
+
72
+ def _generate_prompt_variation(self):
73
+ """Generate varied prompts for quote generation"""
74
+ tradition_category = random.choice(list(SpiritualThemes.TRADITIONS.keys()))
75
+ traditions = SpiritualThemes.TRADITIONS[tradition_category]
76
+ themes = random.sample(SpiritualThemes.THEMES, 2)
77
+ style = random.choice(SpiritualThemes.QUOTE_STYLES)
78
+
79
+ return f"""Focus on {tradition_category} wisdom, particularly from {', '.join(traditions)}.
80
+ Explore themes of {themes[0]} and {themes[1]} in a {style} style.
81
+ Ensure the quote is profound yet accessible for social media."""
82
+
83
+ def _get_fallback_quote(self):
84
+ """Provide a fallback quote when generation fails"""
85
+ fallback_quotes = [
86
+ {
87
+ "text": "Be the change you wish to see in the world.",
88
+ "author": "Mahatma Gandhi",
89
+ "tradition": "Modern Spirituality",
90
+ "theme": "Transformation"
91
+ },
92
+ {
93
+ "text": "Peace comes from within. Do not seek it without.",
94
+ "author": "Buddha",
95
+ "tradition": "Buddhism",
96
+ "theme": "Inner Peace"
97
+ },
98
+ {
99
+ "text": "The journey of a thousand miles begins with one step.",
100
+ "author": "Lao Tzu",
101
+ "tradition": "Taoism",
102
+ "theme": "Growth"
103
+ },
104
+ {
105
+ "text": "Love is the bridge between you and everything.",
106
+ "author": "Rumi",
107
+ "tradition": "Sufi Wisdom",
108
+ "theme": "Love"
109
+ }
110
+ ]
111
+ quote = random.choice(fallback_quotes)
112
+ quote["generated_at"] = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
113
+ quote["source"] = "fallback"
114
+ log_message("ℹ️ Using fallback quote system", "info")
115
+ return quote
116
+
117
+ def generate_quote(self):
118
+ """Generate a new spiritual quote with enhanced variety"""
119
+ try:
120
+ log_message("🎯 Starting quote generation process")
121
+
122
+ prompt_variation = self._generate_prompt_variation()
123
+
124
+ quote_curator = Agent(
125
+ role='Quote Curator',
126
+ goal='Generate diverse and profound spiritual quotes',
127
+ backstory="""You are a wise curator of spiritual wisdom with extensive knowledge
128
+ of both ancient traditions and modern spiritual thought. You understand the nuances
129
+ of different spiritual and philosophical traditions, and can communicate their wisdom
130
+ in an engaging, social media-friendly way.""",
131
+ llm=self.llm,
132
+ verbose=True
133
+ )
134
+
135
+ task = Task(
136
+ description=f"""Generate a spiritual quote following these criteria:
137
+ {prompt_variation}
138
+
139
+ Requirements:
140
+ 1. Ensure quote authenticity and proper attribution
141
+ 2. Balance depth with accessibility
142
+ 3. Keep length appropriate for Instagram
143
+ 4. Include cultural context if relevant
144
+
145
+ Return in JSON format with keys:
146
+ - quote: the spiritual quote text
147
+ - author: name of the source
148
+ - tradition: specific tradition or philosophy
149
+ - theme: primary theme of the quote""",
150
+ expected_output="""A JSON object containing the quote details:
151
+ {
152
+ "quote": "The quote text",
153
+ "author": "Author name",
154
+ "tradition": "Spiritual tradition",
155
+ "theme": "Primary theme"
156
+ }""",
157
+ agent=quote_curator
158
+ )
159
+
160
+ crew = Crew(
161
+ agents=[quote_curator],
162
+ tasks=[task],
163
+ verbose=True
164
+ )
165
+
166
+ result = crew.kickoff()
167
+ log_message("✨ Quote generation completed successfully")
168
+ return self._parse_quote_result(result)
169
+
170
+ except Exception as e:
171
+ log_message(f"❌ Quote generation failed: {str(e)}", "error")
172
+ return self._get_fallback_quote()
173
+
174
+ def _parse_quote_result(self, result):
175
+ """Parse the generated quote result"""
176
+ try:
177
+ if isinstance(result, str):
178
+ result = json.loads(result)
179
+ return {
180
+ "text": result.get('quote', ''),
181
+ "author": result.get('author', ''),
182
+ "tradition": result.get('tradition', ''),
183
+ "theme": result.get('theme', ''),
184
+ "generated_at": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
185
+ }
186
+ except Exception as e:
187
+ log_message(f"❌ Error parsing quote result: {str(e)}", "error")
188
+ raise
189
+
190
+ def generate_image(self, quote, tradition, theme):
191
+ """Generate an image using OpenAI DALL-E with enhanced prompts"""
192
+ try:
193
+ log_message("🎨 Starting image generation")
194
+
195
+ style_prompts = {
196
+ "Buddhism": "zen minimalism, misty mountains, lotus flowers",
197
+ "Hinduism": "mandala patterns, sacred geometry, vibrant cosmos",
198
+ "Taoism": "flowing water, yin-yang harmony, natural elements",
199
+ "Modern Spirituality": "abstract sacred geometry, cosmic patterns",
200
+ "Christian Mysticism": "ethereal light, cathedral aesthetics",
201
+ "Sufi Wisdom": "whirling patterns, desert wisdom, geometric art",
202
+ "Indigenous": "natural elements, earth tones, tribal patterns",
203
+ "default": "serene minimalism, sacred geometry, natural elements"
204
+ }
205
+
206
+ style = style_prompts.get(tradition, style_prompts["default"])
207
+
208
+ prompt = f"""Create a spiritual and contemplative image inspired by this theme: '{theme}'
209
+ Style inspiration: {style}
210
+ Mood: serene, inspiring, contemplative
211
+ Requirements:
212
+ - Suitable for Instagram
213
+ - Leave space for text overlay
214
+ - Balanced composition
215
+ - No text or symbols
216
+ - Peaceful and harmonious colors
217
+ Make it visually striking yet subtle enough for quote overlay."""
218
+
219
+ response = self.openai_client.images.generate(
220
+ model="dall-e-3",
221
+ prompt=prompt,
222
+ size="1024x1024",
223
+ quality="standard",
224
+ n=1
225
+ )
226
+ log_message("✨ Image generated successfully")
227
+ return response.data[0].url
228
+ except Exception as e:
229
+ log_message(f"❌ Image generation failed: {str(e)}", "error")
230
+ raise
231
+
232
+ def generate_audio(self, tradition, theme):
233
+ """Generate background music using MusicGen with enhanced variety"""
234
+ try:
235
+ log_message("🎵 Starting audio generation")
236
+
237
+ music_prompts = {
238
+ "Buddhism": {
239
+ "Inner Peace": "Tibetan singing bowls with gentle bells, very peaceful",
240
+ "Mindfulness": "Zen flute with soft water sounds, mindful atmosphere",
241
+ "default": "Meditation bells with nature sounds"
242
+ },
243
+ "Hinduism": {
244
+ "Devotion": "Indian flute with soft tabla, devotional mood",
245
+ "Wisdom": "Gentle sitar with peaceful drone",
246
+ "default": "Sanskrit chants with soft instrumentation"
247
+ },
248
+ "Modern Spirituality": {
249
+ "Awareness": "Ambient synthesizer with crystal bowls",
250
+ "Growth": "Uplifting piano with gentle pads",
251
+ "default": "Modern meditation music with nature sounds"
252
+ },
253
+ "default": {
254
+ "default": "Peaceful ambient music with gentle bells"
255
+ }
256
+ }
257
+
258
+ tradition_prompts = music_prompts.get(tradition, music_prompts["default"])
259
+ prompt = tradition_prompts.get(theme, tradition_prompts["default"])
260
+
261
+ output = self.replicate_client.run(
262
+ "meta/musicgen:7be0f12c54a8d0d0d720305c1e6ea10c48d5f0a3afce48478341a0fe682a8787",
263
+ input={
264
+ "prompt": prompt,
265
+ "duration": 30,
266
+ "model_version": "melody",
267
+ "output_format": "mp3"
268
+ }
269
+ )
270
+
271
+ log_message("✨ Audio generated successfully")
272
+ return output
273
+ except Exception as e:
274
+ log_message(f"❌ Audio generation failed: {str(e)}", "error")
275
+ raise
276
 
277
  def display_debug_logs():
278
  """Display debug logs with enhanced visualization"""