Sanket17 commited on
Commit
9c2adb5
·
verified ·
1 Parent(s): b9c43e0

Update src/brand.py

Browse files
Files changed (1) hide show
  1. src/brand.py +47 -182
src/brand.py CHANGED
@@ -2,26 +2,19 @@ import base64
2
  import os
3
  import sys
4
  import time
 
5
  from playwright.sync_api import sync_playwright
6
  from PIL import Image
7
- import pandas as pd
8
-
9
- def save_html_file(file_name, html_content):
10
- with open(file_name, 'w') as file:
11
- file.write(html_content)
12
 
13
- def encode_image_to_base64(image_path):
14
- with open(image_path, "rb") as image_file:
15
- return base64.b64encode(image_file.read()).decode('utf-8')
 
 
 
16
 
17
- # Allow user to upload images for logo and product images
18
- logo_image_path = r"src/templates_images/Component 3.png"
19
- cola_image_path = r"src/templates_images/Frame 52.png"
20
- # Encode images to base64
21
- logo_base64 = encode_image_to_base64(logo_image_path)
22
- cola_base64 = encode_image_to_base64(cola_image_path)
23
  def save_html_file(file_name, html_content):
24
- with open(file_name, 'w') as file:
25
  file.write(html_content)
26
 
27
  def encode_image_to_base64(image_path):
@@ -29,11 +22,44 @@ def encode_image_to_base64(image_path):
29
  with open(image_path, "rb") as img_file:
30
  return base64.b64encode(img_file.read()).decode("utf-8")
31
  except FileNotFoundError:
32
- print(f"Image not found: {image_path}")
33
  return ""
34
  except Exception as e:
35
- print(f"Error encoding image {image_path}: {e}")
36
  return ""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
  # Function to generate HTML for Social Media Marketing
38
  # Function to generate HTML for Brand Marketing
39
  def generate_brand_marketing_html(product_image_base64_1, competitor_image_base64_1, product_image_base64_2, competitor_image_base64_2, donts_html, suggestions_html, company_name):
@@ -254,169 +280,8 @@ def generate_brand_marketing_html(product_image_base64_1, competitor_image_base6
254
 
255
  """
256
 
257
- # Function to parse "Product_output_cleaned.txt" for Don'ts and Suggestions specific to Brand Marketing
258
- def parse_cleaned_file_brand_marketing(file_path):
259
- with open(file_path, "r") as file:
260
- content = file.read()
261
-
262
- sections = content.split("==================================================")
263
- for section in sections:
264
- lines = section.strip().split("\n")
265
- if lines and "Brand Marketing" in lines[0]:
266
- donts = []
267
- suggestions = []
268
- mode = None
269
- for line in lines[1:]:
270
- if line.startswith("Don'ts:"):
271
- mode = "donts"
272
- elif line.startswith("Suggestions:"):
273
- mode = "suggestions"
274
- elif mode == "donts" and line.startswith("-"):
275
- donts.append(line.lstrip("- "))
276
- elif mode == "suggestions" and line.startswith("-"):
277
- suggestions.append(line.lstrip("- "))
278
- return "<br>".join(donts), "<br>".join(suggestions)
279
-
280
- return "", ""
281
-
282
- # Function to process Brand Marketing and generate HTML
283
- def process_brand_marketing(data, base_image_dir, output_file, cleaned_file_path, company_name):
284
- # Filter for Brand Marketing category
285
- brand_data = data[data["Category"] == "Brand Marketing"]
286
-
287
- if brand_data.empty:
288
- print("No Brand Marketing data found in the provided Excel file.")
289
- return
290
-
291
- # Parse Don'ts and Suggestions
292
- donts_html, suggestions_html = parse_cleaned_file_brand_marketing(cleaned_file_path)
293
-
294
- # Ensure there are at least two rows
295
- if len(brand_data) < 2:
296
- print("Not enough rows for two product and competitor image comparisons.")
297
- return
298
-
299
- # Get the first two records (assuming these are needed)
300
- brand_row_1 = brand_data.iloc[0]
301
- brand_row_2 = brand_data.iloc[1]
302
-
303
- product_image_path_1 = os.path.join(base_image_dir, brand_row_1["Product_Image_Name"])
304
- competitor_image_path_1 = os.path.join(base_image_dir, brand_row_1["Competitor_Image_Name"])
305
-
306
- product_image_path_2 = os.path.join(base_image_dir, brand_row_2["Product_Image_Name"])
307
- competitor_image_path_2 = os.path.join(base_image_dir, brand_row_2["Competitor_Image_Name"])
308
-
309
- # Encode images to Base64
310
- product_image_base64_1 = encode_image_to_base64(product_image_path_1)
311
- competitor_image_base64_1 = encode_image_to_base64(competitor_image_path_1)
312
-
313
- product_image_base64_2 = encode_image_to_base64(product_image_path_2)
314
- competitor_image_base64_2 = encode_image_to_base64(competitor_image_path_2)
315
-
316
- # Generate HTML content
317
- html_content = generate_brand_marketing_html(
318
- product_image_base64_1,
319
- competitor_image_base64_1,
320
- product_image_base64_2,
321
- competitor_image_base64_2,
322
- donts_html,
323
- suggestions_html,
324
- company_name
325
- )
326
-
327
- # Save the HTML file
328
- with open(output_file, "w", encoding="utf-8") as f:
329
- f.write(html_content)
330
-
331
- print(f"HTML file for Brand Marketing has been saved as: {output_file}")
332
-
333
- # Main script for Content Marketing
334
- if __name__ == "__main__":
335
- if len(sys.argv) > 1:
336
- company_name = sys.argv[1] # The second argument passed will be the company_name
337
- else:
338
- company_name = "Default_Company" # Default value if no argument is passed
339
- # Load the Excel file
340
- file_path = "Output_File/excel/top_3_sd_results.xlsx" # Replace with the path to your Excel file
341
- data = pd.read_excel(file_path)
342
-
343
- base_image_dir = "" # Replace with the actual directory where your images are stored
344
-
345
- # Path to the cleaned file with Don'ts and Suggestions
346
- cleaned_file_path = "data/output_generated_file/Product_output_cleaned.txt" # Replace with the path to your cleaned file
347
-
348
- # Output HTML file
349
- output_file = "src/templates/brand_marketing.html"
350
-
351
- # Generate HTML for Content Marketing
352
- process_brand_marketing(data, base_image_dir, output_file, cleaned_file_path, company_name)
353
-
354
- # Force UTF-8 encoding for terminal output
355
- sys.stdout.reconfigure(encoding='utf-8')
356
-
357
- def capture_screenshot_with_playwright(html_file_path, screenshot_path):
358
- """
359
- Capture a full-page screenshot of the HTML file directly using Playwright.
360
- """
361
- try:
362
- # Launch Playwright in headless mode
363
- with sync_playwright() as p:
364
- browser = p.chromium.launch(headless=True)
365
- page = browser.new_page()
366
-
367
- # Open the HTML file in the browser
368
- page.goto(f"file:///{os.path.abspath(html_file_path)}")
369
-
370
- # Capture the full-page screenshot
371
- page.screenshot(path=screenshot_path, full_page=True)
372
- print(f"Screenshot saved: {screenshot_path}")
373
-
374
- browser.close()
375
-
376
- except Exception as e:
377
- print(f"Error capturing screenshot: {e}")
378
-
379
- import os
380
- from PIL import Image
381
-
382
- def convert_png_to_pdf(png_path, company_name):
383
- """
384
- Convert a PNG image into a PDF strictly named as 'company_name brand marketing.pdf'
385
- in a cloud-friendly directory.
386
- """
387
- try:
388
- # Use a safer output directory (e.g., /home/user or /tmp)
389
- output_folder = "/tmp/template_PDF"
390
- os.makedirs(output_folder, exist_ok=True)
391
-
392
- # Create the PDF file name as 'company_name brand marketing.pdf'
393
- pdf_path = os.path.join(output_folder, f"{company_name} brand marketing.pdf")
394
-
395
- # Convert the PNG to PDF
396
- img = Image.open(png_path)
397
- img.convert('RGB').save(pdf_path, "PDF")
398
-
399
- print(f"PDF saved: {pdf_path}")
400
- return pdf_path # Return the file path for verification
401
- except Exception as e:
402
- print(f"Error converting PNG to PDF: {e}")
403
- return None
404
-
405
-
406
- if __name__ == "__main__":
407
- # Paths for demonstration
408
- html_file_path = "src/templates/brand_marketing.html"
409
-
410
- # Screenshot saved in the folder: data/reports/template_ss
411
- screenshot_folder = "data/reports/template_ss"
412
- os.makedirs(screenshot_folder, exist_ok=True)
413
- screenshot_path = os.path.join(screenshot_folder, "brand_marketing_screenshot.png")
414
-
415
- # Ensure Playwright browsers are installed
416
- os.system("playwright install")
417
-
418
- # Capture screenshot
419
- capture_screenshot_with_playwright(html_file_path, screenshot_path)
420
 
421
- # Convert screenshot to PDF with the company name strictly as the filename
422
- convert_png_to_pdf(screenshot_path, company_name)
 
 
2
  import os
3
  import sys
4
  import time
5
+ import pandas as pd
6
  from playwright.sync_api import sync_playwright
7
  from PIL import Image
 
 
 
 
 
8
 
9
+ # ✅ Define temp folder for Hugging Face Spaces
10
+ TEMP_FOLDER = "/tmp"
11
+ HTML_FILE = os.path.join(TEMP_FOLDER, "brand_marketing.html")
12
+ SCREENSHOT_FILE = os.path.join(TEMP_FOLDER, "brand_marketing.png")
13
+ PDF_FOLDER = os.path.join(TEMP_FOLDER, "template_PDF")
14
+ os.makedirs(PDF_FOLDER, exist_ok=True) # Ensure folder exists
15
 
 
 
 
 
 
 
16
  def save_html_file(file_name, html_content):
17
+ with open(file_name, "w", encoding="utf-8") as file:
18
  file.write(html_content)
19
 
20
  def encode_image_to_base64(image_path):
 
22
  with open(image_path, "rb") as img_file:
23
  return base64.b64encode(img_file.read()).decode("utf-8")
24
  except FileNotFoundError:
25
+ print(f"⚠️ Image not found: {image_path}")
26
  return ""
27
  except Exception as e:
28
+ print(f"⚠️ Error encoding image {image_path}: {e}")
29
  return ""
30
+
31
+ def capture_screenshot():
32
+ """Capture a screenshot using Playwright."""
33
+ os.system("playwright install --with-deps") # Ensure Playwright is installed
34
+
35
+ # Delete existing screenshot
36
+ if os.path.exists(SCREENSHOT_FILE):
37
+ os.remove(SCREENSHOT_FILE)
38
+
39
+ with sync_playwright() as p:
40
+ browser = p.chromium.launch(headless=True)
41
+ page = browser.new_page()
42
+ page.goto(f"file://{HTML_FILE}")
43
+ page.screenshot(path=SCREENSHOT_FILE, full_page=True)
44
+ browser.close()
45
+ print(f"✅ Screenshot saved: {SCREENSHOT_FILE}")
46
+
47
+ def convert_to_pdf():
48
+ """Convert the screenshot to a PDF file."""
49
+ try:
50
+ PDF_FILE = os.path.join(PDF_FOLDER, "brand_marketing.pdf")
51
+ img = Image.open(SCREENSHOT_FILE)
52
+ img.convert("RGB").save(PDF_FILE, "PDF")
53
+ print(f"✅ PDF saved: {PDF_FILE}")
54
+ except Exception as e:
55
+ print(f"❌ Error converting PNG to PDF: {e}")
56
+
57
+ if __name__ == "__main__":
58
+ # Ensure previous HTML/Screenshot are removed
59
+ if os.path.exists(HTML_FILE):
60
+ os.remove(HTML_FILE)
61
+ if os.path.exists(SCREENSHOT_FILE):
62
+ os.remove(SCREENSHOT_FILE)
63
  # Function to generate HTML for Social Media Marketing
64
  # Function to generate HTML for Brand Marketing
65
  def generate_brand_marketing_html(product_image_base64_1, competitor_image_base64_1, product_image_base64_2, competitor_image_base64_2, donts_html, suggestions_html, company_name):
 
280
 
281
  """
282
 
283
+ save_html_file(HTML_FILE, html_content)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
284
 
285
+ # Capture Screenshot and Convert to PDF
286
+ capture_screenshot()
287
+ convert_to_pdf()