Dash-inc commited on
Commit
74ad848
·
verified ·
1 Parent(s): 859ea89

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +102 -113
main.py CHANGED
@@ -20,63 +20,42 @@ from fastapi.responses import FileResponse
20
  from fastapi.responses import StreamingResponse
21
  from langchain_core.prompts import PromptTemplate
22
  from dotenv import load_dotenv
 
 
23
  from fastapi import Request
24
- import time
25
- from io import BytesIO
26
- import uuid
27
  import tempfile
28
- import httpx
29
- import asyncioasync def generate_image(prompt: str):
30
- url = "https://api.bfl.ml/v1/flux-pro-1.1"
31
- headers = {
32
- "accept": "application/json",
33
- "x-key": "4f69d408-4979-4812-8ad2-ec6d232c9ddf",
34
- "Content-Type": "application/json"
35
- }
36
- payload = {
37
- "prompt": prompt,
38
- "width": 1024,
39
- "height": 1024,
40
- "guidance_scale": 1,
41
- "num_inference_steps": 50,
42
- "max_sequence_length": 512,
43
- }
44
 
45
- async with httpx.AsyncClient() as client:
46
- response = await client.post(url, headers=headers, json=payload)
47
- response_data = response.json()
48
- if "id" not in response_data:
49
- raise Exception("Error generating image: ID missing from response")
50
-
51
- request_id = response_data["id"]
52
-
53
- # Poll for the image result
54
- while True:
55
- await asyncio.sleep(0.5)
56
- result = await client.get(
57
- "https://api.bfl.ml/v1/get_result",
58
- headers=headers,
59
- params={"id": request_id},
60
- )
61
- result_data = result.json()
62
-
63
- if result_data["status"] == "Ready":
64
- if "result" in result_data and "sample" in result_data["result"]:
65
- image_url = result_data["result"]["sample"]
66
-
67
- # Download the image
68
- image_response = await client.get(image_url)
69
- if image_response.status_code == 200:
70
- img = Image.open(BytesIO(image_response.content))
71
- filename = f"generated_{uuid.uuid4()}.png"
72
- filepath = save_image_locally(img, filename)
73
- return filepath
74
- else:
75
- raise Exception("Failed to download the image")
76
- else:
77
- raise Exception("Expected 'sample' key not found in the result")
78
- elif result_data["status"] == "Error":
79
- raise Exception(f"Image generation failed: {result_data.get('error', 'Unknown error')}")
80
  for keyword in keywords:
81
  payload = {'source': 'google_search','query': keyword, 'domain': 'com', 'geo_location': target_country, 'locale': 'en-us', 'parse': True, 'start_page': 1, 'pages': 5, 'limit': 10, }
82
  try:
@@ -256,13 +235,14 @@ Examples:
256
  prompt = prompt_template.format(blog_post_content=content,previous_image_prompts=previous_prompts)
257
  response = llm.invoke(prompt)
258
  return response.content # Extract prompts
259
-
260
  def save_image_locally(image, filename):
261
  filepath = os.path.join(image_storage_dir, filename)
262
  image.save(filepath, format="PNG")
263
  return filepath
264
-
265
- async def generate_image(prompt: str):
 
266
  url = "https://api.bfl.ml/v1/flux-pro-1.1"
267
  headers = {
268
  "accept": "application/json",
@@ -270,7 +250,7 @@ async def generate_image(prompt: str):
270
  "Content-Type": "application/json"
271
  }
272
  payload = {
273
- "prompt": prompt,
274
  "width": 1024,
275
  "height": 1024,
276
  "guidance_scale": 1,
@@ -278,42 +258,39 @@ async def generate_image(prompt: str):
278
  "max_sequence_length": 512,
279
  }
280
 
281
- async with httpx.AsyncClient() as client:
282
- response = await client.post(url, headers=headers, json=payload)
283
- response_data = response.json()
284
- if "id" not in response_data:
285
- raise Exception("Error generating image: ID missing from response")
286
-
287
- request_id = response_data["id"]
288
-
289
- # Poll for the image result
290
- while True:
291
- await asyncio.sleep(0.5)
292
- result = await client.get(
293
- "https://api.bfl.ml/v1/get_result",
294
- headers=headers,
295
- params={"id": request_id},
296
- )
297
- result_data = result.json()
298
-
299
- if result_data["status"] == "Ready":
300
- if "result" in result_data and "sample" in result_data["result"]:
301
- image_url = result_data["result"]["sample"]
302
-
303
- # Download the image
304
- image_response = await client.get(image_url)
305
- if image_response.status_code == 200:
306
- img = Image.open(BytesIO(image_response.content))
307
- filename = f"generated_{uuid.uuid4()}.png"
308
- filepath = save_image_locally(img, filename)
309
- return filepath
310
- else:
311
- raise Exception("Failed to download the image")
312
  else:
313
- raise Exception("Expected 'sample' key not found in the result")
314
- elif result_data["status"] == "Error":
315
- raise Exception(f"Image generation failed: {result_data.get('error', 'Unknown error')}")
316
-
 
 
 
317
  def selected_category(category: dict, search_results: list) -> str:
318
  prompt_template = """
319
  Based on the given search results, select the most appropriate category for the blog post.
@@ -362,6 +339,20 @@ def fetch_google_results_for_site(keywords: List[str]) -> List[Dict[str, int]]:
362
  except requests.RequestException as e:
363
  print(f"Error fetching results: {e}")
364
  return []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
365
 
366
  def generate_linkages(blog_post: str, search_results: list, keywords: List[str]) -> dict:
367
  Internal_search_results = fetch_google_results_for_site(keywords)
@@ -402,20 +393,20 @@ def generate_linkages(blog_post: str, search_results: list, keywords: List[str])
402
 
403
  @app.post("/generate_blog/", response_model=dict)
404
  def create_blog_pipeline(blog_request: blog_request):
405
- output_dir = "/tmp/pic"
406
- if not os.path.exists(output_dir):
407
- os.makedirs(output_dir, exist_ok=True)
408
  try:
409
  word_file_path = "Generated_Blog_Post.docx"
410
  for file_path in [word_file_path]:
411
  if os.path.exists(file_path):
412
  os.remove(file_path)
413
 
414
- category = {"Parenting Stages":["Baby & Toddler Years","Preschool & Early Childhood","Big Kids (6–12 Years)","Tweens & Teens","Newborn Care","Parenting After Baby #2 (or #3!)"],"Everyday Life with Kids":["Daily Routines & Organization","Mealtime & Nutrition","Playtime & Activities","Sleep Schedules & Tips","Family Time Ideas","Special Occasions & Holidays"],"Self-Care for Moms":["Health & Wellness","Mental Health & Stress Relief","Beauty & Self-Care Tips","Hobbies & “Me Time”","Personal Growth & Goal Setting"],"Parenting Tips & Tricks":["Time-Saving Hacks","Budgeting for Families","Quick Cleaning Tips","Home Organization with Kids","School & Homework Help","Tech Tools for Parenting"],"Mom Life (Humor & Reality)":["Honest Mom Moments","Laughs & Parenting Memes","Confessions & Fails","Real Life, Real Moms","Quotes & Relatable Stories"],"Parenting Styles & Philosophies":["Gentle Parenting & Positive Discipline","Attachment Parenting","Raising Independent Kids","Balancing Structure & Freedom","Parenting Trends & Research"],"Relationships & Family Dynamics":["Co-Parenting & Communication","Sibling Relationships","Family Bonding Activities","Grandparents & Extended Family","Blended Families & Step-Parenting"],"Learning & Development":["Early Childhood Education","Fun Learning at Home","Language & Social Skills","Emotional Development","Physical & Motor Skills"],"Health & Wellness":["Child Nutrition & Health","Exercise & Play for Kids","Sleep Health","Pediatric Check-Ups","Common Illnesses & Remedies","Childproofing & Safety"],"Mompreneurs & Working Moms":["Balancing Work & Family","Remote Work Tips","Side Hustles & Passions","Time Management for Busy Moms","Self-Care for Working Moms"],"School & Education":["Preschool & Daycare Choices","School Readiness & Transitions","Homework & Study Skills","Navigating School Friendships","Involvement in School Activities"],"Lifestyle & Home":["Home Décor for Families","Sustainable & Eco-Friendly Choices","Family Finances & Budgeting","Travel & Family Adventures","Pets & Kids"],"Parenting Challenges":["Tantrums & Discipline","Social Media & Screen Time","Bullying & Peer Pressure","Dealing with Picky Eaters","Navigating Kids’ Fears"],"Creative & Fun Ideas":["DIY Projects for Kids","Kid-Friendly Crafts","Fun Recipes & Snacks","Family Games & Activities","Fun Celebrations & Birthdays"],"Modern Parenting Topics":["Raising Kids in a Digital World","Cultural & Diversity Awareness","Gender-Neutral Parenting","Parenting and Social Media"],"The Wild World of Parenting":["Tiny Bosses: Life with Toddlers","Kid Logic: Decoding the Mind of a Child","Growing Up Fast: Navigating the Tween Years"],"The Mom Zone":["Surviving the Madness, One Coffee at a Time","Keeping It Real: The Beautiful Mess of Mom Life","Dear Diary: Honest Mom Confessions"],"Mastering the Art of Family Chaos":["Organized Chaos: Tips for Running a Household","Barely Hanging On: Parenting Hacks for the Real World","Kid-Proof Your Life (If That’s Even Possible)"],"Mom Self-Care, Simplified":["Time for You: Self-Care for Busy Moms","Staying Sane (Mostly) with Self-Care on a Budget","Love Yourself: From Self-Care to Self-Love"],"Making Memories, Keeping Your Sanity":["Everyday Magic: Fun Family Traditions","Making the Ordinary Extraordinary","The Cool Mom’s Guide to Family Fun"],"Mom Hacks & Life-Saving Tricks":["Shortcuts for Sanity: Clever Parenting Hacks","The No-Fuss Guide to Getting Stuff Done","Mom Brain Solutions: Little Tricks for Big Wins"],"When Kids Are…Kids!":["Real Talk: Tantrums, Tears & Tiny Attitudes","Kid Quirks: The Weird, Wonderful World of Children","Mini People, Mega Emotions"],"Relationships and Realities":["It Takes Two: Parenting Together (Even When You Don’t Agree)","Keeping Love Alive Amid the Chaos","Keeping the Family Peace, One Day at a Time"],"The School Scene":["Homework Without the Headache","From Preschool to Preteen Drama: Surviving School Years","Winning at School (Even If They Don’t Love It)"],"Digital World for Digital Kids":["Screen Time vs. Play Time: Finding the Balance","Raising Tech-Savvy Kids in a Tech-Obsessed World","Social Media & Selfies: Teaching Digital Smarts"],"Raising the Next Generation":["The Kindness Project: Raising Empathetic Kids","How to Raise Future World-Changers","The Power of Yes and No: Teaching Choices"],"Healthier, Happier Families":["Making Meals Easy & Fun (Yes, Really!)","Health Hacks for Kids Who Hate Veggies","Small Habits for Big Health Wins"],"The Organized Chaos Hub":["Declutter Like a Pro (Yes, Even with Kids)","Home Hacks for the Ultimate Kid-Friendly Space","Mastering the Family Schedule"],"Funny Mom Survival Kit":["Parenting Memes You’ll Feel in Your Soul","Surviving Kids’ Parties with Style","Confessions of a Bedtime Warrior"],"Big Dreams & Little Goals":["Goal-Getting for Moms Who Do It All","Dare to Dream Big (Even If You’re Tired)","Mom Goals: From ‘Just Survive’ to ‘Thrive’"],"For the Love of Learning":["Learning Through Play: Fun Ideas for Little Learners","Home Learning Hacks for Smart Kids","Raising Curious Kids: Sparking Little Imaginations"],"Tales from the Trenches":["Stories from the Wild World of Parenting","Lessons Learned from the Chaos","Hilarious Mom Stories You’ll Never Believe"],"Adventures Big and Small":["Tiny Adventures: Fun for Kids of All Ages","Family Vacations & Kid-Friendly Getaways","Staycations That Feel Like the Real Deal"],"The Support Network":["For the Love of Moms: Support & Community","Village of Moms: Finding Your Support Circle","Surviving & Thriving Together"],"Creative Kids Zone":["Arts & Crafts that Won’t Break the Bank","Imagination Station: Encouraging Creative Play","Rainy Day Fun: Indoor Ideas for Any Weather"]}
415
-
416
- output_dir = "/tmp/pic"
417
- if not os.path.exists(output_dir):
418
- os.makedirs(output_dir, exist_ok=True)
 
 
 
419
 
420
 
421
  print('SEO Searching')
@@ -440,7 +431,7 @@ def create_blog_pipeline(blog_request: blog_request):
440
  image = generate_image(image_prompt)
441
 
442
  if image:
443
- title_image_path = "/tmp/pic/image.png"
444
  image.save(title_image_path)
445
  document.add_picture(title_image_path, width=Inches(6), height=Inches(6))
446
  else:
@@ -449,8 +440,6 @@ def create_blog_pipeline(blog_request: blog_request):
449
 
450
  subheadings = generate_blog_subheadings(title, search_results, selected_cat, blog_request )
451
 
452
- print('processing Subheadings for blog post')
453
-
454
  for i, subheading in enumerate(tqdm(subheadings, desc="Processing subheadings")):
455
  content = BlogPostPromptSingleSubheading(
456
  title, subheading, blog_request, search_results, selected_cat, blog_content
@@ -464,7 +453,7 @@ def create_blog_pipeline(blog_request: blog_request):
464
  previous_image_prompts += image_prompt + " , "
465
  image = generate_image(image_prompt)
466
  if image:
467
- subheading_image_path = f"/tmp/pic/image_{i}.png"
468
  image.save(subheading_image_path)
469
  document.add_picture(subheading_image_path, width=Inches(6), height=Inches(6))
470
  else:
@@ -479,18 +468,12 @@ def create_blog_pipeline(blog_request: blog_request):
479
  document.add_paragraph(formatted_linkages)
480
 
481
  document.save(word_file_path)
482
- if os.path.exists("/tmp/pic/"):
483
- shutil.rmtree("/tmp/pic/", ignore_errors=True)
484
- else:
485
- print("Directory '/tmp/pic/' does not exist. Skipping cleanup.")
486
-
487
  except Exception as e:
488
  print(f"An error occurred: {e}")
489
  return {"error": str(e)}
490
 
491
- return {"docx_path": word_file_path}
492
-
493
-
494
  # Update to include format_linkages
495
  def format_linkages(linkages: str) -> str:
496
  """
@@ -521,3 +504,9 @@ def download_file():
521
  async def root():
522
  return {"message": "API is up and running!"}
523
 
 
 
 
 
 
 
 
20
  from fastapi.responses import StreamingResponse
21
  from langchain_core.prompts import PromptTemplate
22
  from dotenv import load_dotenv
23
+ import os
24
+ import logging
25
  from fastapi import Request
 
 
 
26
  import tempfile
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
 
28
+ logging.basicConfig(level=logging.DEBUG)
29
+
30
+
31
+ load_dotenv()
32
+
33
+ app = FastAPI()
34
+
35
+ class ImagePromptRequest(BaseModel):
36
+ blog_post_content: str
37
+ previous_image_prompts: str
38
+
39
+ API_KEY = os.getenv("API_KEY")
40
+
41
+ llm = ChatGroq(
42
+ model="llama-3.3-70b-versatile",
43
+ temperature=0.3,
44
+ max_tokens=1024,
45
+ api_key=API_KEY)
46
+
47
+ class blog_request(BaseModel):
48
+ TypeOf : str
49
+ target_audience: str
50
+ tone: str
51
+ point_of_view: str
52
+ target_country: str
53
+ keywords: List[str]
54
+
55
+ def fetch_google_results(keywords: List[str], target_country: str) -> List[str]:
56
+ username=os.getenv("USERNAME")
57
+ password=os.getenv("PASSWORD")
58
+ all_results_dict = {}
 
 
 
 
59
  for keyword in keywords:
60
  payload = {'source': 'google_search','query': keyword, 'domain': 'com', 'geo_location': target_country, 'locale': 'en-us', 'parse': True, 'start_page': 1, 'pages': 5, 'limit': 10, }
61
  try:
 
235
  prompt = prompt_template.format(blog_post_content=content,previous_image_prompts=previous_prompts)
236
  response = llm.invoke(prompt)
237
  return response.content # Extract prompts
238
+
239
  def save_image_locally(image, filename):
240
  filepath = os.path.join(image_storage_dir, filename)
241
  image.save(filepath, format="PNG")
242
  return filepath
243
+
244
+ def generate_image(prompt: str):
245
+ # API call to image generation service
246
  url = "https://api.bfl.ml/v1/flux-pro-1.1"
247
  headers = {
248
  "accept": "application/json",
 
250
  "Content-Type": "application/json"
251
  }
252
  payload = {
253
+ "prompt": refined_prompt,
254
  "width": 1024,
255
  "height": 1024,
256
  "guidance_scale": 1,
 
258
  "max_sequence_length": 512,
259
  }
260
 
261
+ response = requests.post(url, headers=headers, json=payload).json()
262
+ if "id" not in response:
263
+ raise HTTPException(status_code=500, detail="Error generating image: ID missing from response")
264
+
265
+ request_id = response["id"]
266
+
267
+ # Poll for the image result
268
+ while True:
269
+ time.sleep(0.5)
270
+ result = requests.get(
271
+ "https://api.bfl.ml/v1/get_result",
272
+ headers=headers,
273
+ params={"id": request_id},
274
+ ).json()
275
+
276
+ if result["status"] == "Ready":
277
+ if "result" in result and "sample" in result["result"]:
278
+ image_url = result["result"]["sample"]
279
+
280
+ # Download the image
281
+ image_response = requests.get(image_url)
282
+ if image_response.status_code == 200:
283
+ img = Image.open(BytesIO(image_response.content))
284
+ filename = f"generated_{uuid.uuid4()}.png"
285
+ filepath = save_image_locally(img, filename)
 
 
 
 
 
 
286
  else:
287
+ raise HTTPException(status_code=500, detail="Failed to download the image")
288
+ else:
289
+ raise HTTPException(status_code=500, detail="Expected 'sample' key not found in the result")
290
+ elif result["status"] == "Error":
291
+ raise HTTPException(status_code=500, detail=f"Image generation failed: {result.get('error', 'Unknown error')}")
292
+
293
+
294
  def selected_category(category: dict, search_results: list) -> str:
295
  prompt_template = """
296
  Based on the given search results, select the most appropriate category for the blog post.
 
339
  except requests.RequestException as e:
340
  print(f"Error fetching results: {e}")
341
  return []
342
+
343
+ def decide_to_generate_image(content: str, i:int) -> bool:
344
+ max=3
345
+ prompt_template = '''
346
+ You are an advanced language model tasked with deciding if an image should be generated based on the provided blog post. Analyze the blog content and respond with "Yes" or "No" only. Generate an image only if the content is rich, high-quality, and would benefit from it. Generate a maximum of 3 images: if {i} > {max}, respond with "No".
347
+ Blog post:
348
+ {blog_post}
349
+ Output:
350
+ Yes or No
351
+ '''
352
+ prompt=prompt_template.format(blog_post=content,i=i,max=max)
353
+ response = llm.invoke(prompt)
354
+ should_generate_image = response.content
355
+ return should_generate_image
356
 
357
  def generate_linkages(blog_post: str, search_results: list, keywords: List[str]) -> dict:
358
  Internal_search_results = fetch_google_results_for_site(keywords)
 
393
 
394
  @app.post("/generate_blog/", response_model=dict)
395
  def create_blog_pipeline(blog_request: blog_request):
 
 
 
396
  try:
397
  word_file_path = "Generated_Blog_Post.docx"
398
  for file_path in [word_file_path]:
399
  if os.path.exists(file_path):
400
  os.remove(file_path)
401
 
402
+ category = {"Parenting Stages":["Baby & Toddler Years","Preschool & Early Childhood","Big Kids (6–12 Years)","Tweens & Teens","Newborn Care","Parenting After Baby #2 (or #3!)"],"Everyday Life with Kids":["Daily Routines & Organization","Mealtime & Nutrition","Playtime & Activities","Sleep Schedules & Tips","Family Time Ideas","Special Occasions & Holidays"],"Self-Care for Moms":["Health & Wellness","Mental Health & Stress Relief","Beauty & Self-Care Tips","Hobbies & “Me Time”","Personal Growth & Goal Setting"],"Parenting Tips & Tricks":["Time-Saving Hacks","Budgeting for Families","Quick Cleaning Tips","Home Organization with Kids","School & Homework Help","Tech Tools for Parenting"],"Mom Life (Humor & Reality)":["Honest Mom Moments","Laughs & Parenting Memes","Confessions & Fails","Real Life, Real Moms","Quotes & Relatable Stories"],"Parenting Styles & Philosophies":["Gentle Parenting & Positive Discipline","Attachment Parenting","Raising Independent Kids","Balancing Structure & Freedom","Parenting Trends & Research"],"Relationships & Family Dynamics":["Co-Parenting & Communication","Sibling Relationships","Family Bonding Activities","Grandparents & Extended Family","Blended Families & Step-Parenting"],"Learning & Development":["Early Childhood Education","Fun Learning at Home","Language & Social Skills","Emotional Development","Physical & Motor Skills"],"Health & Wellness":["Child Nutrition & Health","Exercise & Play for Kids","Sleep Health","Pediatric Check-Ups","Common Illnesses & Remedies","Childproofing & Safety"],"Mompreneurs & Working Moms":["Balancing Work & Family","Remote Work Tips","Side Hustles & Passions","Time Management for Busy Moms","Self-Care for Working Moms"],"School & Education":["Preschool & Daycare Choices","School Readiness & Transitions","Homework & Study Skills","Navigating School Friendships","Involvement in School Activities"],"Lifestyle & Home":["Home Décor for Families","Sustainable & Eco-Friendly Choices","Family Finances & Budgeting","Travel & Family Adventures","Pets & Kids"],"Parenting Challenges":["Tantrums & Discipline","Social Media & Screen Time","Bullying & Peer Pressure","Dealing with Picky Eaters","Navigating Kids’ Fears"],"Creative & Fun Ideas":["DIY Projects for Kids","Kid-Friendly Crafts","Fun Recipes & Snacks","Family Games & Activities","Fun Celebrations & Birthdays"],"Modern Parenting Topics":["Raising Kids in a Digital World","Cultural & Diversity Awareness","Gender-Neutral Parenting","Parenting and Social Media"],"The Wild World of Parenting":["Tiny Bosses: Life with Toddlers","Kid Logic: Decoding the Mind of a Child","Growing Up Fast: Navigating the Tween Years"],"The Mom Zone":["Surviving the Madness, One Coffee at a Time","Keeping It Real: The Beautiful Mess of Mom Life","Dear Diary: Honest Mom Confessions"],"Mastering the Art of Family Chaos":["Organized Chaos: Tips for Running a Household","Barely Hanging On: Parenting Hacks for the Real World","Kid-Proof Your Life (If That’s Even Possible)"],"Mom Self-Care, Simplified":["Time for You: Self-Care for Busy Moms","Staying Sane (Mostly) with Self-Care on a Budget","Love Yourself: From Self-Care to Self-Love"],"Making Memories, Keeping Your Sanity":["Everyday Magic: Fun Family Traditions","Making the Ordinary Extraordinary","The Cool Mom’s Guide to Family Fun"],"Mom Hacks & Life-Saving Tricks":["Shortcuts for Sanity: Clever Parenting Hacks","The No-Fuss Guide to Getting Stuff Done","Mom Brain Solutions: Little Tricks for Big Wins"],"When Kids Are…Kids!":["Real Talk: Tantrums, Tears & Tiny Attitudes","Kid Quirks: The Weird, Wonderful World of Children","Mini People, Mega Emotions"],"Relationships and Realities":["It Takes Two: Parenting Together (Even When You Don’t Agree)","Keeping Love Alive Amid the Chaos","Keeping the Family Peace, One Day at a Time"],"The School Scene":["Homework Without the Headache","From Preschool to Preteen Drama: Surviving School Years","Winning at School (Even If They Don’t Love It)"],"Digital World for Digital Kids":["Screen Time vs. Play Time: Finding the Balance","Raising Tech-Savvy Kids in a Tech-Obsessed World","Social Media & Selfies: Teaching Digital Smarts"],"Raising the Next Generation":["The Kindness Project: Raising Empathetic Kids","How to Raise Future World-Changers","The Power of Yes and No: Teaching Choices"],"Healthier, Happier Families":["Making Meals Easy & Fun (Yes, Really!)","Health Hacks for Kids Who Hate Veggies","Small Habits for Big Health Wins"],"The Organized Chaos Hub":["Declutter Like a Pro (Yes, Even with Kids)","Home Hacks for the Ultimate Kid-Friendly Space","Mastering the Family Schedule"],"Funny Mom Survival Kit":["Parenting Memes You’ll Feel in Your Soul","Surviving Kids’ Parties with Style","Confessions of a Bedtime Warrior"],"Big Dreams & Little Goals":["Goal-Getting for Moms Who Do It All","Dare to Dream Big (Even If You’re Tired)","Mom Goals: From ‘Just Survive’ to ‘Thrive’"],"For the Love of Learning":["Learning Through Play: Fun Ideas for Little Learners","Home Learning Hacks for Smart Kids","Raising Curious Kids: Sparking Little Imaginations"],"Tales from the Trenches":["Stories from the Wild World of Parenting","Lessons Learned from the Chaos","Hilarious Mom Stories You’ll Never Believe"],"Adventures Big and Small":["Tiny Adventures: Fun for Kids of All Ages","Family Vacations & Kid-Friendly Getaways","Staycations That Feel Like the Real Deal"],"The Support Network":["For the Love of Moms: Support & Community","Village of Moms: Finding Your Support Circle","Surviving & Thriving Together"],"Creative Kids Zone":["Arts & Crafts that Won’t Break the Bank","Imagination Station: Encouraging Creative Play","Rainy Day Fun: Indoor Ideas for Any Weather"]}
403
+
404
+ # Create a temporary directory inside the 'temp' folder
405
+ temp_base = "temp"
406
+ os.makedirs(temp_base, exist_ok=True) # Ensure the 'temp' base folder exists
407
+ output_dir = tempfile.mkdtemp(dir=temp_base, prefix="pic_")
408
+
409
+ print(f"Temporary directory created: {output_dir}")
410
 
411
 
412
  print('SEO Searching')
 
431
  image = generate_image(image_prompt)
432
 
433
  if image:
434
+ title_image_path = "pic/image.png"
435
  image.save(title_image_path)
436
  document.add_picture(title_image_path, width=Inches(6), height=Inches(6))
437
  else:
 
440
 
441
  subheadings = generate_blog_subheadings(title, search_results, selected_cat, blog_request )
442
 
 
 
443
  for i, subheading in enumerate(tqdm(subheadings, desc="Processing subheadings")):
444
  content = BlogPostPromptSingleSubheading(
445
  title, subheading, blog_request, search_results, selected_cat, blog_content
 
453
  previous_image_prompts += image_prompt + " , "
454
  image = generate_image(image_prompt)
455
  if image:
456
+ subheading_image_path = f"pic/image_{i}.png"
457
  image.save(subheading_image_path)
458
  document.add_picture(subheading_image_path, width=Inches(6), height=Inches(6))
459
  else:
 
468
  document.add_paragraph(formatted_linkages)
469
 
470
  document.save(word_file_path)
471
+ shutil.rmtree("pic/", ignore_errors=True)
472
+ return {"docx_path": word_file_path}
 
 
 
473
  except Exception as e:
474
  print(f"An error occurred: {e}")
475
  return {"error": str(e)}
476
 
 
 
 
477
  # Update to include format_linkages
478
  def format_linkages(linkages: str) -> str:
479
  """
 
504
  async def root():
505
  return {"message": "API is up and running!"}
506
 
507
+ @app.middleware("http")
508
+ async def log_requests(request: Request, call_next):
509
+ print(f"Incoming request: {request.method} {request.url}")
510
+ response = await call_next(request)
511
+ print(f"Response status: {response.status_code}")
512
+ return response