Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,133 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
from pyppeteer import launch
|
3 |
+
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 |
+
|
10 |
+
app = FastAPI()
|
11 |
+
|
12 |
+
class HtmlInput(BaseModel):
|
13 |
+
message: str
|
14 |
+
|
15 |
+
|
16 |
+
|
17 |
+
async def convert_html_to_image(html, output_file, width=612, height=800, device_scale_factor=2):
|
18 |
+
browser = await launch()
|
19 |
+
page = await browser.newPage()
|
20 |
+
await page.setViewport({'width': width, 'height': height, 'deviceScaleFactor': device_scale_factor})
|
21 |
+
await page.setContent(html)
|
22 |
+
# Capture only the viewport without extra white space
|
23 |
+
await page.screenshot({'path': output_file})
|
24 |
+
await browser.close()
|
25 |
+
return output_file # Return the path of the captured image
|
26 |
+
|
27 |
+
# Function to tilt the content randomly
|
28 |
+
def tilt_content(html_content):
|
29 |
+
tilt_angle = random.randint(-3, 2) # Adjust the range of tilting angle as needed
|
30 |
+
tilted_content = f'<div style="transform: rotate({tilt_angle}deg);">{html_content}</div>'
|
31 |
+
return tilted_content
|
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; }",
|
36 |
+
".txORqLQ { font: bold 10px 'Courier New',Courier,monospace; }",
|
37 |
+
".txORqLQ { font: bold 10.5px 'Courier New',Courier,monospace; }"])
|
38 |
+
offset_content=html_content
|
39 |
+
offset_content = f'<style>{selected_css}</style>' + offset_content
|
40 |
+
return offset_content
|
41 |
+
|
42 |
+
def apply_random_css_positioning(html_content):
|
43 |
+
selected_css = random.choice([".address { position: relative;bottom: 48.6rem;left: 16.8rem;width: 11rem; margin-top:0.3rem}",
|
44 |
+
".address { position: relative;bottom: 47.8rem;left: 10.9rem;width: 30rem; margin-top:0.3rem}"
|
45 |
+
])
|
46 |
+
offset_content=html_content
|
47 |
+
offset_content = f'<style>{selected_css}</style>' + offset_content
|
48 |
+
return offset_content
|
49 |
+
|
50 |
+
def apply_position_offset(html_content):
|
51 |
+
# Random offsets in x and y directions
|
52 |
+
offset_x = random.randint(-20, 20) # Adjust the range of x offset as needed
|
53 |
+
offset_y = random.randint(-20, 20) # Adjust the range of y offset as needed
|
54 |
+
|
55 |
+
# Apply the offsets to the content
|
56 |
+
offset_content = f'<div style="position: relative; left: {offset_x}px; top: {offset_y}px;">{html_content}</div>'
|
57 |
+
return offset_content
|
58 |
+
|
59 |
+
async def optimize_image(input_file, output_file, target_size_kb=200):
|
60 |
+
# Open the image using PIL
|
61 |
+
with Image.open(input_file) as img:
|
62 |
+
# Calculate the initial quality to achieve the target size
|
63 |
+
quality = 95
|
64 |
+
temp_output_file = output_file + ".temp.jpg"
|
65 |
+
img.save(temp_output_file, format='JPEG', quality=quality, optimize=True)
|
66 |
+
while os.path.getsize(temp_output_file) > target_size_kb * 1024 and quality > 0:
|
67 |
+
# Reduce the quality and save to temporary file
|
68 |
+
quality -= 5
|
69 |
+
img.save(temp_output_file, format='JPEG', quality=quality, optimize=True)
|
70 |
+
|
71 |
+
# Save the optimized image to the output file
|
72 |
+
os.replace(temp_output_file, output_file)
|
73 |
+
|
74 |
+
async def mainFunction(html_content:str):
|
75 |
+
# Create img folder if not exists
|
76 |
+
if not os.path.exists('img'):
|
77 |
+
os.makedirs('img')
|
78 |
+
if not os.path.exists('json'):
|
79 |
+
os.makedirs('json')
|
80 |
+
|
81 |
+
filename = 'sample.html'
|
82 |
+
|
83 |
+
# Write the HTML string to the file
|
84 |
+
with open(filename, 'w',encoding='utf-8') as file:
|
85 |
+
file.write(html_content)
|
86 |
+
|
87 |
+
template_loader = FileSystemLoader(searchpath=".")
|
88 |
+
template_env = Environment(loader=template_loader)
|
89 |
+
template = template_env.get_template(filename)
|
90 |
+
|
91 |
+
# Load JSON data from files
|
92 |
+
with open("modified_data.json", "r", encoding="utf-8") as universal_file:
|
93 |
+
universal_json_data = json.load(universal_file)
|
94 |
+
|
95 |
+
|
96 |
+
# Define the start number
|
97 |
+
start_number = 17800
|
98 |
+
|
99 |
+
# Loop over each record in the universal JSON
|
100 |
+
for index, record in enumerate(universal_json_data):
|
101 |
+
# Increment index by start_number
|
102 |
+
index += start_number
|
103 |
+
|
104 |
+
# Generate json file
|
105 |
+
|
106 |
+
# Load the template
|
107 |
+
|
108 |
+
json_output_file = os.path.join('json', f"{index:05d}.json")
|
109 |
+
with open(json_output_file, "w", encoding="utf-8") as json_file:
|
110 |
+
json.dump(record, json_file, indent=4, ensure_ascii=False)
|
111 |
+
html_output = template.render(record)
|
112 |
+
html_output= apply_random_css(html_output)
|
113 |
+
html_output=apply_random_css_positioning(html_output)
|
114 |
+
|
115 |
+
|
116 |
+
# Apply random position offset
|
117 |
+
# html_output = apply_position_offset(html_output)
|
118 |
+
|
119 |
+
# Tilt the content randomly
|
120 |
+
# html_output = tilt_content(html_output)
|
121 |
+
|
122 |
+
|
123 |
+
# Convert HTML to image
|
124 |
+
output_image_file = os.path.join('img', f"{index:05d}.jpg")
|
125 |
+
captured_image_path = await convert_html_to_image(html_output, output_image_file)
|
126 |
+
|
127 |
+
# Optimize the image to be less than 200KB
|
128 |
+
await optimize_image(captured_image_path, output_image_file)
|
129 |
+
|
130 |
+
# Run the asynchronous main function
|
131 |
+
@app.post("/convert-html-to-image/")
|
132 |
+
async def convert_html_to_image_endpoint(html_content:HtmlInput):
|
133 |
+
await mainFunction(html_content.message)
|