Soham0708 commited on
Commit
1993589
·
verified ·
1 Parent(s): 3991060

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +7 -79
app.py CHANGED
@@ -4,8 +4,7 @@ from PIL import Image
4
  import json
5
  import random
6
  from pydantic import BaseModel
7
- from fastapi import FastAPI
8
- from jinja2 import Environment, FileSystemLoader
9
  import io
10
  from fastapi.responses import StreamingResponse
11
  app = FastAPI()
@@ -14,7 +13,7 @@ class HtmlInput(BaseModel):
14
  message: str
15
 
16
 
17
- async def convert_html_to_image(html, output_file, width=612, height=800, device_scale_factor=2):
18
  try:
19
  browser = await launch({
20
  'headless': True,
@@ -31,12 +30,6 @@ async def convert_html_to_image(html, output_file, width=612, height=800, device
31
  print(f"Error in convert_html_to_image: {e}")
32
  raise
33
 
34
- # Function to tilt the content randomly
35
- def tilt_content(html_content):
36
- tilt_angle = random.randint(-3, 2) # Adjust the range of tilting angle as needed
37
- tilted_content = f'<div style="transform: rotate({tilt_angle}deg);">{html_content}</div>'
38
- return tilted_content
39
-
40
  def apply_random_css(html_content):
41
  selected_css = random.choice([".txORqLQ { font-size: 13px; font-weight: bold; fill: #000080; color:#000080; }",
42
  ".txORqLQ { font-size: 12px; font-weight: bold; fill: #000080; color:#000080; }",
@@ -46,24 +39,7 @@ def apply_random_css(html_content):
46
  offset_content = f'<style>{selected_css}</style>' + offset_content
47
  return offset_content
48
 
49
- def apply_random_css_positioning(html_content):
50
- selected_css = random.choice([".address { position: relative;bottom: 48.6rem;left: 16.8rem;width: 11rem; margin-top:0.3rem}",
51
- ".address { position: relative;bottom: 47.8rem;left: 10.9rem;width: 30rem; margin-top:0.3rem}"
52
- ])
53
- offset_content=html_content
54
- offset_content = f'<style>{selected_css}</style>' + offset_content
55
- return offset_content
56
-
57
- def apply_position_offset(html_content):
58
- # Random offsets in x and y directions
59
- offset_x = random.randint(-20, 20) # Adjust the range of x offset as needed
60
- offset_y = random.randint(-20, 20) # Adjust the range of y offset as needed
61
-
62
- # Apply the offsets to the content
63
- offset_content = f'<div style="position: relative; left: {offset_x}px; top: {offset_y}px;">{html_content}</div>'
64
- return offset_content
65
-
66
- async def optimize_image(input_file, output_file, target_size_kb=200):
67
  # Open the image using PIL
68
  with Image.open(input_file) as img:
69
  # Calculate the initial quality to achieve the target size
@@ -79,61 +55,13 @@ async def optimize_image(input_file, output_file, target_size_kb=200):
79
  os.replace(temp_output_file, output_file)
80
 
81
  async def mainFunction(html_content:str):
82
- print("in main function")
83
- # Create img folder if not exists
84
- if not os.path.exists('img'):
85
- os.makedirs('img')
86
- if not os.path.exists('json'):
87
- os.makedirs('json')
88
-
89
- # Write the HTML string to the file
90
- html_file = io.StringIO(html_content)
91
- print("html file created")
92
- template_loader = FileSystemLoader(searchpath=".")
93
- template_env = Environment(loader=template_loader)
94
- template = template_env.from_string(html_file.getvalue())
95
- print("Template rendered successfully")
96
-
97
- # Load JSON data from files
98
- with open("modified_data.json", "r", encoding="utf-8") as universal_file:
99
- universal_json_data = json.load(universal_file)
100
-
101
-
102
- # Define the start number
103
- start_number = 17800
104
-
105
- # Loop over each record in the universal JSON
106
- for index, record in enumerate(universal_json_data):
107
- # Increment index by start_number
108
- index += start_number
109
-
110
- # Generate json file
111
-
112
- # Load the template
113
-
114
- json_output_file = os.path.join('json', f"{index:05d}.json")
115
- with open(json_output_file, "w", encoding="utf-8") as json_file:
116
- json.dump(record, json_file, indent=4, ensure_ascii=False)
117
- html_output = template.render(record)
118
- html_output= apply_random_css(html_output)
119
- html_output=apply_random_css_positioning(html_output)
120
-
121
-
122
- # Apply random position offset
123
- # html_output = apply_position_offset(html_output)
124
-
125
- # Tilt the content randomly
126
- # html_output = tilt_content(html_output)
127
-
128
-
129
- # Convert HTML to image
130
- output_image_file = os.path.join('img', f"{index:05d}.jpg")
131
- captured_image_path = await convert_html_to_image(html_output, output_image_file)
132
 
133
  # Optimize the image to be less than 200KB
134
- await optimize_image(captured_image_path, output_image_file)
135
 
136
- return output_image_file
137
 
138
  # Run the asynchronous main function
139
  @app.post("/convert-html-to-image/")
 
4
  import json
5
  import random
6
  from pydantic import BaseModel
7
+ from fastapi import FastAPI, HTTPException
 
8
  import io
9
  from fastapi.responses import StreamingResponse
10
  app = FastAPI()
 
13
  message: str
14
 
15
 
16
+ async def convert_html_to_image(html, output_file, width=650, height=800, device_scale_factor=2):
17
  try:
18
  browser = await launch({
19
  'headless': True,
 
30
  print(f"Error in convert_html_to_image: {e}")
31
  raise
32
 
 
 
 
 
 
 
33
  def apply_random_css(html_content):
34
  selected_css = random.choice([".txORqLQ { font-size: 13px; font-weight: bold; fill: #000080; color:#000080; }",
35
  ".txORqLQ { font-size: 12px; font-weight: bold; fill: #000080; color:#000080; }",
 
39
  offset_content = f'<style>{selected_css}</style>' + offset_content
40
  return offset_content
41
 
42
+ async def optimize_image(input_file, output_file, target_size_kb=500):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
  # Open the image using PIL
44
  with Image.open(input_file) as img:
45
  # Calculate the initial quality to achieve the target size
 
55
  os.replace(temp_output_file, output_file)
56
 
57
  async def mainFunction(html_content:str):
58
+ output_image_file = "image.jpg"
59
+ captured_image_path = await convert_html_to_image(html_content, output_image_file)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60
 
61
  # Optimize the image to be less than 200KB
62
+ await optimize_image(captured_image_path, output_image_file)
63
 
64
+ return output_image_file
65
 
66
  # Run the asynchronous main function
67
  @app.post("/convert-html-to-image/")