RichardVR commited on
Commit
d4b351c
·
verified ·
1 Parent(s): 6b830c4

Create workflow_logic.py

Browse files
Files changed (1) hide show
  1. workflow_logic.py +556 -0
workflow_logic.py ADDED
@@ -0,0 +1,556 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import requests
3
+ import time
4
+ import json
5
+ from openai import OpenAI # Ensure you have openai installed (pip install openai)
6
+
7
+ # --- Configuration & Environment Variables ---
8
+ # Make sure these are set as Hugging Face Space secrets!
9
+ OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
10
+ HEYGEN_API_KEY = os.getenv("HEYGEN_API_KEY")
11
+ BLOTATO_API_KEY = os.getenv("BLOTATO_API_KEY")
12
+
13
+ # Heygen specific setup (as defined in n8n's "Setup Heygen" node)
14
+ HEYGEN_AVATAR_ID = os.getenv("HEYGEN_AVATAR_ID", "c67f3f55c5fd49d080e19a2ea9666e77") # Use env or default
15
+ HEYGEN_VOICE_ID = os.getenv("HEYGEN_VOICE_ID", "e515d746526f448fa533afddc97e4933") # Use env or default
16
+ HEYGEN_BACKGROUND_VIDEO_URL = os.getenv("HEYGEN_BACKGROUND_VIDEO_URL", "https://database.blotato.io/storage/v1/object/public/public_media/4ddd33eb-e811-4ab5-93e1-2cd0b7e8fb3f/videogen2-render-e6b398a2-5859-4a77-88ef-2345bcefdc98.mp4") # Use env or default
17
+
18
+ # Blotato specific account IDs (from "Prepare for Publish" node)
19
+ # It's better to get these from environment variables if they change per user/deployment
20
+ BLOTATO_INSTAGRAM_ID = os.getenv("BLOTATO_INSTAGRAM_ID", "")
21
+ BLOTATO_YOUTUBE_ID = os.getenv("BLOTATO_YOUTUBE_ID", "5174")
22
+ BLOTATO_TIKTOK_ID = os.getenv("BLOTATO_TIKTOK_ID", "")
23
+ BLOTATO_FACEBOOK_ID = os.getenv("BLOTATO_FACEBOOK_ID", "")
24
+ BLOTATO_FACEBOOK_PAGE_ID = os.getenv("BLOTATO_FACEBOOK_PAGE_ID", "")
25
+ BLOTATO_THREADS_ID = os.getenv("BLOTATO_THREADS_ID", "")
26
+ BLOTATO_TWITTER_ID = os.getenv("BLOTATO_TWITTER_ID", "")
27
+ BLOTATO_LINKEDIN_ID = os.getenv("BLOTATO_LINKEDIN_ID", "")
28
+ BLOTATO_PINTEREST_ID = os.getenv("BLOTATO_PINTEREST_ID", "")
29
+ BLOTATO_PINTEREST_BOARD_ID = os.getenv("BLOTATO_PINTEREST_BOARD_ID", "")
30
+ BLOTATO_BLUESKY_ID = os.getenv("BLOTATO_BLUESKY_ID", "")
31
+
32
+ # Initialize OpenAI client
33
+ client = OpenAI(api_key=OPENAI_API_KEY)
34
+
35
+ # --- Helper Functions for Hacker News (Replacing n8n's Hacker News Tool) ---
36
+ def fetch_hn_top_stories():
37
+ """Fetches top story IDs from Hacker News."""
38
+ print("Fetching top Hacker News stories...")
39
+ try:
40
+ response = requests.get("https://hacker-news.firebaseio.com/v0/topstories.json")
41
+ response.raise_for_status()
42
+ return response.json()
43
+ except requests.exceptions.RequestException as e:
44
+ print(f"Error fetching top stories: {e}")
45
+ return []
46
+
47
+ def fetch_hn_item(item_id):
48
+ """Fetches details for a single Hacker News item (story or comment)."""
49
+ try:
50
+ response = requests.get(f"https://hacker-news.firebaseio.com/v0/item/{item_id}.json")
51
+ response.raise_for_status()
52
+ return response.json()
53
+ except requests.exceptions.RequestException as e:
54
+ print(f"Error fetching item {item_id}: {e}")
55
+ return None
56
+
57
+ def search_hn_for_ai_llm_stories(num_stories=10):
58
+ """Fetches top stories and filters for AI/LLM related content."""
59
+ top_story_ids = fetch_hn_top_stories()
60
+ ai_llm_stories = []
61
+ for i, story_id in enumerate(top_story_ids):
62
+ if len(ai_llm_stories) >= num_stories:
63
+ break
64
+ story = fetch_hn_item(story_id)
65
+ if story and 'title' in story and isinstance(story['title'], str):
66
+ if "AI" in story['title'].upper() or "LLM" in story['title'].upper():
67
+ ai_llm_stories.append(story)
68
+ print(f"Processed {i+1}/{len(top_story_ids)} top stories...")
69
+ return ai_llm_stories
70
+
71
+ def get_hn_article_and_comments(story_id):
72
+ """Fetches a Hacker News article and its comments."""
73
+ article = fetch_hn_item(story_id)
74
+ comments_data = []
75
+ if article and 'kids' in article:
76
+ print(f"Fetching comments for story {story_id}...")
77
+ for comment_id in article['kids']:
78
+ comment = fetch_hn_item(comment_id)
79
+ if comment and 'text' in comment:
80
+ comments_data.append(comment['text'])
81
+ return {"article": article, "comments": comments_data}
82
+
83
+ # --- OpenAI Functions (Replacing n8n's OpenAI and Write Script/Caption nodes) ---
84
+
85
+ def generate_ai_avatar_script(hn_data):
86
+ """
87
+ Generates a 30-second monologue script for an AI avatar video based on HN data.
88
+ Replicates the 'AI Agent' prompt.
89
+ """
90
+ print("Generating AI avatar script...")
91
+ if not OPENAI_API_KEY:
92
+ raise ValueError("OPENAI_API_KEY not set for script generation.")
93
+
94
+ # Format the Hacker News data for the prompt
95
+ article_title = hn_data['article'].get('title', 'No title available')
96
+ article_url = hn_data['article'].get('url', 'No URL available')
97
+ article_text = f"Title: {article_title}\nURL: {article_url}\n"
98
+ if hn_data['article'].get('text'):
99
+ article_text += f"Content: {hn_data['article']['text']}\n"
100
+ article_text += "\nComments:\n" + "\n".join(hn_data['comments'][:10]) # Limit comments for brevity
101
+
102
+ prompt = f"""
103
+ # INSTRUCTIONS
104
+
105
+ Perform the following tasks, in order:
106
+
107
+ 1. Fetch the top 10 stories from Hacker News from the past 24 hours related to AI or LLMs.
108
+ 2. Select the top story that is most likely to go viral on social media.
109
+ 3. Fetch the article and Hacker News comments.
110
+ 4. Create a 30-second monologue script for an AI avatar video, following these guidelines:
111
+ - The script should be approximately 30 seconds when spoken aloud.
112
+ - Include lots of details and statistics from the article.
113
+ - Use 6th grade reading level.
114
+ - Balanced viewpoint.
115
+ - Script should be in single paragraph
116
+
117
+ 5. Update the script's first 2 sentences to use sensational viral hooks that grab the viewer's attention and spark curiosity. The 3rd sentence should start diving into the article's details.
118
+
119
+ 6. Replace the last sentence with: "Hit follow to stay ahead in AI!"
120
+
121
+ # OUTPUT FORMAT
122
+
123
+ ONLY output the exact video script. Do not output anything else. NEVER include intermediate thoughts, notes, or formatting.
124
+
125
+ # INPUT
126
+ Use the following information sources:
127
+ <sources>
128
+ {article_text}
129
+ </sources>
130
+ """
131
+ try:
132
+ completion = client.chat.completions.create(
133
+ model="gpt-4o-mini", # From n8n config for "Write Script" / "AI Agent"
134
+ messages=[
135
+ {"role": "user", "content": prompt}
136
+ ],
137
+ temperature=0.7 # A reasonable default, adjust if needed
138
+ )
139
+ return completion.choices[0].message.content.strip()
140
+ except Exception as e:
141
+ print(f"Error generating AI avatar script: {e}")
142
+ return "Failed to generate script."
143
+
144
+ def generate_long_caption(script_content):
145
+ """
146
+ Generates a long caption based on the video script, replicating 'Write Long Caption' node.
147
+ """
148
+ print("Generating long caption...")
149
+ if not OPENAI_API_KEY:
150
+ raise ValueError("OPENAI_API_KEY not set for long caption generation.")
151
+
152
+ prompt = f"""
153
+ =# EXAMPLE
154
+
155
+ <example>
156
+ Many people have recently asked me about ask engine optimization, which is all about optimizing your website and existing content, so it can be pulled into ChatGPT and other generative AI tools. Consider that generative AI tools tend to be more conversational in nature and have a Q&A type format, so search engines will want to pull in snippets that concisely answer a user’s question.- what is ask engine optimization in the age of AI?- How does traditional SEO compare to ask engine optimization today?- top tips and tricks to get started with ask engine optimization?
157
+
158
+ #ai #askengineoptimization #chatgpts #seo #aitools #digitalmarketing
159
+ </example>
160
+
161
+ # CONTEXT
162
+
163
+ Infer the topic from the sources provided.
164
+
165
+ # WRITING STYLE
166
+
167
+ Here’s how you always write:
168
+
169
+ <writing_style>
170
+
171
+ - Your writing style is spartan and informative.
172
+ - Use clear, simple language.
173
+ - Employ short, impactful sentences.
174
+ - Use active voice; avoid passive voice.
175
+ - Focus on practical, actionable insights.
176
+ - Incorporate data or statistics to support claims when possible.
177
+ - Use \"\"\"\"\"\"\"\"you\"\"\"\"\"\"\"\" and \"\"\"\"\"\"\"\"your\"\"\"\"\"\"\"\" to directly address the reader.
178
+ - Avoid metaphors and clichés.
179
+ - Avoid generalizations.
180
+ - Do not include common setup language in any sentence, including: in conclusion, in closing, etc.
181
+ - Do not output warnings or notes—just the output requested.
182
+ - Do not use hashtags.
183
+ - Do not use semicolons.
184
+ - Do not use emojis.
185
+ - Do not use asterisks.
186
+ - Do NOT use these words:
187
+ \"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"can, may, just, that, very, really, literally, actually, certainly, probably, basically, could, maybe, delve, embark, enlightening, esteemed, shed light, craft, crafting, imagine, realm, game-changer, unlock, discover, skyrocket, abyss, you're not alone, in a world where, revolutionize, disruptive, utilize, utilizing, dive deep, tapestry, illuminate, unveil, pivotal, enrich, intricate, elucidate, hence, furthermore, realm, however, harness, exciting, groundbreaking, cutting-edge, remarkable, it. remains to be seen, glimpse into, navigating, landscape, stark, testament, in summary, in conclusion, moreover, boost, bustling, opened up, powerful, inquiries, ever-evolving\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"
188
+ </writing_style>
189
+
190
+ # PLANNING
191
+
192
+ Your goal is to write a 50-word video caption based on the provided source.
193
+
194
+ 1. Analyze the provided sources thoroughly.
195
+ 2. Study the <example> post carefully. You will be asked to replicate their:
196
+ - Overall structure.
197
+ - Tone and voice.
198
+ - Formatting (including line breaks and spacing).
199
+ - Length (aim for a similarly detailed post).
200
+ - Absence of emojis.
201
+ - Use of hashtags.
202
+ - Emotional resonance.
203
+
204
+ # OUTPUT
205
+ Follow the GUIDELINES below to write the post. Use your analysis from step 1 and step 2. Use the provided sources as the foundation for your post, expanding on it significantly while maintaining the style and structure of the examples provided from step 2. You MUST use information from the provided sources. Make sure you adhere to your <writing_style>.
206
+
207
+ <guidelines>
208
+ The description should be structured as follows:
209
+ 1. Start with 1 paragraph summarizing the source
210
+ 2. Newline, followed by 3 bullet points of questions that a viewer might ask on a search engine about the source
211
+ 3. Newline, followed by these hashtags: #ai #artificialintelligence #ainews #sabrinaramonov #aiavatar
212
+ </guidelines>
213
+
214
+ Take a deep breath and take it step-by-step!
215
+
216
+ # INPUT
217
+ Use the following information sources:
218
+ <sources>
219
+ {script_content}
220
+ </sources>
221
+ """
222
+ try:
223
+ completion = client.chat.completions.create(
224
+ model="gpt-4o", # From n8n config
225
+ messages=[
226
+ {"role": "user", "content": prompt}
227
+ ],
228
+ temperature=0.7 # A reasonable default
229
+ )
230
+ return completion.choices[0].message.content.strip()
231
+ except Exception as e:
232
+ print(f"Error generating long caption: {e}")
233
+ return "Failed to generate long caption."
234
+
235
+ def generate_short_caption(long_caption_content):
236
+ """
237
+ Generates a short caption based on the long caption, replicating 'Write Short Caption' node.
238
+ """
239
+ print("Generating short caption...")
240
+ if not OPENAI_API_KEY:
241
+ raise ValueError("OPENAI_API_KEY not set for short caption generation.")
242
+
243
+ prompt = f"""
244
+ =Write a spartan 2-sentence caption summarizing the video content, use 6th grade language, balanced neutral perspective, no emojis:
245
+
246
+ <content>
247
+ {long_caption_content}
248
+ </content>
249
+ """
250
+ try:
251
+ completion = client.chat.completions.create(
252
+ model="gpt-4o", # From n8n config
253
+ messages=[
254
+ {"role": "user", "content": prompt}
255
+ ],
256
+ temperature=0.7 # A reasonable default
257
+ )
258
+ return completion.choices[0].message.content.strip()
259
+ except Exception as e:
260
+ print(f"Error generating short caption: {e}")
261
+ return "Failed to generate short caption."
262
+
263
+ # --- Heygen API Interactions ---
264
+
265
+ def create_avatar_video(script_text):
266
+ """Replicates 'Create Avatar Video' node."""
267
+ print("Calling Heygen API to create avatar video...")
268
+ if not HEYGEN_API_KEY:
269
+ raise ValueError("HEYGEN_API_KEY not set for Heygen video creation.")
270
+
271
+ headers = {
272
+ "X-Api-Key": HEYGEN_API_KEY,
273
+ "Content-Type": "application/json"
274
+ }
275
+ payload = {
276
+ "video_inputs": [
277
+ {
278
+ "character": {
279
+ "type": "avatar",
280
+ "avatar_id": HEYGEN_AVATAR_ID,
281
+ "avatar_style": "normal",
282
+ "scale": 1.0,
283
+ "offset": {"x": 0.0, "y": 0.0},
284
+ "matting": True
285
+ },
286
+ "voice": {
287
+ "type": "text",
288
+ "input_text": script_text,
289
+ "voice_id": HEYGEN_VOICE_ID,
290
+ "speed": 1.1,
291
+ "pitch": 50,
292
+ "emotion": "Excited"
293
+ },
294
+ "background": {
295
+ "type": "video",
296
+ "url": HEYGEN_BACKGROUND_VIDEO_URL,
297
+ "play_style": "loop",
298
+ "fit": "cover"
299
+ }
300
+ }
301
+ ],
302
+ "dimension": {"width": 720, "height": 1280},
303
+ "aspect_ratio": "9:16",
304
+ "caption": False,
305
+ "title": "n8n TEST AVATAR"
306
+ }
307
+ try:
308
+ response = requests.post("https://api.heygen.com/v2/video/generate", headers=headers, json=payload)
309
+ response.raise_for_status()
310
+ return response.json()
311
+ except requests.exceptions.RequestException as e:
312
+ print(f"Error creating Heygen video: {e}")
313
+ raise
314
+
315
+ def get_avatar_video_status(video_id):
316
+ """Replicates 'Get Avatar Video' node."""
317
+ print(f"Checking Heygen video status for video_id: {video_id}...")
318
+ if not HEYGEN_API_KEY:
319
+ raise ValueError("HEYGEN_API_KEY not set for Heygen video status check.")
320
+
321
+ headers = {
322
+ "X-Api-Key": HEYGEN_API_KEY
323
+ }
324
+ params = {"video_id": video_id}
325
+ try:
326
+ response = requests.get("https://api.heygen.com/v1/video_status.get", headers=headers, params=params)
327
+ response.raise_for_status()
328
+ return response.json()
329
+ except requests.exceptions.RequestException as e:
330
+ print(f"Error getting Heygen video status: {e}")
331
+ raise
332
+
333
+ # --- Blotato API Interactions ---
334
+
335
+ def upload_to_blotato(media_url, is_image=False):
336
+ """Replicates 'Upload to Blotato' and 'Upload to Blotato - Image' nodes."""
337
+ print(f"Uploading media to Blotato: {media_url}...")
338
+ if not BLOTATO_API_KEY:
339
+ raise ValueError("BLOTATO_API_KEY not set for Blotato upload.")
340
+
341
+ headers = {
342
+ "blotato-api-key": BLOTATO_API_KEY,
343
+ "Content-Type": "application/json"
344
+ }
345
+ payload = {"url": media_url}
346
+ try:
347
+ response = requests.post("https://backend.blotato.com/v2/media", headers=headers, json=payload)
348
+ response.raise_for_status()
349
+ return response.json()
350
+ except requests.exceptions.RequestException as e:
351
+ print(f"Error uploading to Blotato: {e}")
352
+ raise
353
+
354
+ def publish_to_blotato(
355
+ platform,
356
+ media_url,
357
+ account_id,
358
+ text_content,
359
+ facebook_page_id=None, # Only for Facebook
360
+ youtube_title=None, # Only for YouTube
361
+ pinterest_board_id=None, # Only for Pinterest
362
+ pinterest_link=None # Only for Pinterest
363
+ ):
364
+ """
365
+ Replicates various '[Platform] Publish via Blotato' nodes.
366
+ Combines logic for different platforms.
367
+ """
368
+ print(f"Publishing to Blotato ({platform})...")
369
+ if not BLOTATO_API_KEY:
370
+ raise ValueError("BLOTATO_API_KEY not set for Blotato publishing.")
371
+
372
+ headers = {
373
+ "blotato-api-key": BLOTATO_API_KEY,
374
+ "Content-Type": "application/json"
375
+ }
376
+
377
+ post_data = {
378
+ "post": {
379
+ "target": {"targetType": platform},
380
+ "content": {
381
+ "text": text_content,
382
+ "platform": platform,
383
+ "mediaUrls": [media_url] if media_url else []
384
+ },
385
+ "accountId": account_id
386
+ }
387
+ }
388
+
389
+ # Add platform-specific target parameters
390
+ if platform == "facebook" and facebook_page_id:
391
+ post_data["post"]["target"]["pageId"] = facebook_page_id
392
+ elif platform == "youtube":
393
+ post_data["post"]["target"]["title"] = youtube_title or "Generated Video"
394
+ post_data["post"]["target"]["privacyStatus"] = "public"
395
+ post_data["post"]["target"]["shouldNotifySubscribers"] = True
396
+ elif platform == "tiktok":
397
+ # These are fixed in the n8n node, can be added here
398
+ post_data["post"]["target"].update({
399
+ "isYourBrand": False, "disabledDuet": False, "privacyLevel": "PUBLIC_TO_EVERYONE",
400
+ "isAiGenerated": False, "disabledStitch": False, "disabledComments": False,
401
+ "isBrandedContent": False
402
+ })
403
+ elif platform == "pinterest" and pinterest_board_id:
404
+ post_data["post"]["target"]["boardId"] = pinterest_board_id
405
+ post_data["post"]["target"]["link"] = pinterest_link or "https://www.tiktok.com/@sabrina_ramonov"
406
+ elif platform == "bluesky":
407
+ # Bluesky node in n8n had empty mediaUrls, implying image/video not supported or disabled.
408
+ # Following that for now.
409
+ post_data["post"]["content"]["mediaUrls"] = []
410
+
411
+
412
+ try:
413
+ response = requests.post("https://backend.blotato.com/v2/posts", headers=headers, json=post_data)
414
+ response.raise_for_status()
415
+ print(f"Successfully published to {platform}.")
416
+ return response.json()
417
+ except requests.exceptions.RequestException as e:
418
+ print(f"Error publishing to {platform}: {e}")
419
+ # Continue even if one platform fails
420
+ return {"status": "failed", "error": str(e)}
421
+
422
+ # --- Main Workflow Execution Function ---
423
+
424
+ def run_daily_ai_video_workflow():
425
+ """
426
+ Executes the entire workflow, simulating the n8n flow.
427
+ """
428
+ print("--- Starting Daily AI Video Workflow ---")
429
+ results = {}
430
+
431
+ try:
432
+ # 1. AI Agent (combining Fetch HN Front Page, Fetch HN Article, and Write Script logic)
433
+ # This is simplified; a real Langchain agent would dynamically decide which tools to use.
434
+ # Here, we hardcode the flow as per the n8n workflow.
435
+ ai_llm_stories = search_hn_for_ai_llm_stories(num_stories=10)
436
+ if not ai_llm_stories:
437
+ print("No AI/LLM stories found on Hacker News front page.")
438
+ return {"status": "failed", "message": "No relevant Hacker News stories."}
439
+
440
+ # For simplicity, pick the first one that matches
441
+ selected_story = ai_llm_stories[0]
442
+ hn_data = get_hn_article_and_comments(selected_story['id'])
443
+ if not hn_data['article']:
444
+ print(f"Could not fetch details for selected HN story {selected_story['id']}.")
445
+ return {"status": "failed", "message": "Could not fetch HN article details."}
446
+
447
+ ai_avatar_script = generate_ai_avatar_script(hn_data)
448
+ if ai_avatar_script == "Failed to generate script.":
449
+ return {"status": "failed", "message": "AI script generation failed."}
450
+ results['ai_avatar_script'] = ai_avatar_script
451
+ print(f"Generated AI Avatar Script:\n{ai_avatar_script}\n")
452
+
453
+ # 2. Write Long Caption
454
+ final_text_long = generate_long_caption(ai_avatar_script)
455
+ results['final_text_long'] = final_text_long
456
+ print(f"Generated Long Caption:\n{final_text_long}\n")
457
+
458
+ # 3. Write Short Caption
459
+ final_text_short = generate_short_caption(final_text_long)
460
+ results['final_text_short'] = final_text_short
461
+ print(f"Generated Short Caption:\n{final_text_short}\n")
462
+
463
+ # 4. Create Avatar Video (Heygen)
464
+ create_video_response = create_avatar_video(ai_avatar_script)
465
+ video_id = create_video_response['data']['video_id']
466
+ results['heygen_video_id'] = video_id
467
+ print(f"Heygen Video ID: {video_id}")
468
+
469
+ # 5. Wait
470
+ # The n8n node has an 8-minute wait. In a real scenario, you'd poll for status.
471
+ # For a simple deployment, a fixed wait might be acceptable, but polling is robust.
472
+ print("Waiting 8 minutes for Heygen video to process...")
473
+ time.sleep(8 * 60) # 8 minutes
474
+
475
+ # 6. Get Avatar Video Status
476
+ video_status_response = get_avatar_video_status(video_id)
477
+ video_url = video_status_response['data']['video_url']
478
+ results['heygen_video_url'] = video_url
479
+ print(f"Heygen Video URL: {video_url}")
480
+
481
+ if not video_url:
482
+ print("Heygen video URL not available after waiting. Cannot proceed with publishing.")
483
+ return {"status": "failed", "message": "Heygen video URL not retrieved."}
484
+
485
+ # 7. Prepare for Publish (variables gathered earlier or from workflow outputs)
486
+ # This step is handled by variables in Python.
487
+
488
+ # 8. Upload to Blotato (Video)
489
+ blotato_upload_response = upload_to_blotato(video_url)
490
+ blotato_media_url = blotato_upload_response['url'] # Blotato returns a URL for the uploaded media
491
+ results['blotato_video_url'] = blotato_media_url
492
+ print(f"Blotato Uploaded Video URL: {blotato_media_url}")
493
+
494
+ # 9. Publish to Social Media via Blotato
495
+ # Note: Some nodes were disabled in your n8n workflow. I'll include them here
496
+ # but you might want to uncomment/enable them as needed.
497
+
498
+ # [Youtube] Publish via Blotato (Active in n8n)
499
+ publish_to_blotato(
500
+ "youtube", blotato_media_url, BLOTATO_YOUTUBE_ID, final_text_long,
501
+ youtube_title="TEST VIDEO" # As per n8n config
502
+ )
503
+
504
+ # The following are DISABLED in the provided n8n workflow.
505
+ # Uncomment and provide correct BLOTATO_ACCOUNT_IDs if you enable them.
506
+
507
+ # [Instagram] Publish via Blotato
508
+ # publish_to_blotato("instagram", blotato_media_url, BLOTATO_INSTAGRAM_ID, final_text_long)
509
+
510
+ # [Facebook] Publish via Blotato
511
+ # publish_to_blotato("facebook", blotato_media_url, BLOTATO_FACEBOOK_ID, final_text_long, facebook_page_id=BLOTATO_FACEBOOK_PAGE_ID)
512
+
513
+ # [Threads] Publish via Blotato
514
+ # publish_to_blotato("threads", blotato_media_url, BLOTATO_THREADS_ID, final_text_short)
515
+
516
+ # [Linkedin] Publish via Blotato
517
+ # publish_to_blotato("linkedin", blotato_media_url, BLOTATO_LINKEDIN_ID, final_text_long)
518
+
519
+ # [Twitter] Publish via Blotato
520
+ # publish_to_blotato("twitter", blotato_media_url, BLOTATO_TWITTER_ID, final_text_short)
521
+
522
+ # [Tiktok] Publish via Blotato
523
+ # publish_to_blotato("tiktok", blotato_media_url, BLOTATO_TIKTOK_ID, final_text_long)
524
+
525
+ # [Bluesky] Publish via Blotato (Media URL is empty in n8n, following that)
526
+ # publish_to_blotato("bluesky", None, BLOTATO_BLUESKY_ID, final_text_short)
527
+
528
+ # 10. OpenAI (Image generation) + Upload to Blotato (Image) + Pinterest Publish
529
+ # These were also DISABLED in n8n, but showing how they'd be integrated.
530
+ # This would require actual image generation from OpenAI (DALL-E) and its URL.
531
+ # For now, this part remains conceptual as it's disabled in the source workflow.
532
+ # if False: # Only run if you enable this part
533
+ # print("Attempting image generation and Pinterest publish...")
534
+ # # Example: Generate image (you'd need to adapt for OpenAI's image generation API)
535
+ # # image_response = client.images.generate(model="dall-e-3", prompt=final_text_long, n=1, size="1024x1024")
536
+ # # generated_image_url = image_response.data[0].url
537
+ # # blotato_image_upload_response = upload_to_blotato(generated_image_url, is_image=True)
538
+ # # blotato_uploaded_image_url = blotato_image_upload_response['url']
539
+ # # publish_to_blotato("pinterest", blotato_uploaded_image_url, BLOTATO_PINTEREST_ID, final_text_short, pinterest_board_id=BLOTATO_PINTEREST_BOARD_ID, pinterest_link="https://www.tiktok.com/@sabrina_ramonov")
540
+
541
+
542
+ except Exception as e:
543
+ print(f"Workflow execution failed: {e}")
544
+ return {"status": "failed", "message": str(e), "results": results}
545
+
546
+ print("--- Workflow Completed Successfully ---")
547
+ return {"status": "success", "message": "Workflow executed successfully!", "results": results}
548
+
549
+ if __name__ == "__main__":
550
+ # Example of how to run locally for testing (after setting environment variables)
551
+ # python-dotenv can be used for local development: pip install python-dotenv
552
+ # from dotenv import load_dotenv
553
+ # load_dotenv() # Loads variables from a .env file if present
554
+
555
+ # This will run the workflow directly when the script is executed
556
+ run_daily_ai_video_workflow()