Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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, HTTPException
|
8 |
+
from jinja2 import Environment, FileSystemLoader
|
9 |
+
import io
|
10 |
+
from fastapi.responses import StreamingResponse
|
11 |
+
app = FastAPI()
|
12 |
+
|
13 |
+
class HtmlInput(BaseModel):
|
14 |
+
message: str
|
15 |
+
|
16 |
+
|
17 |
+
async def convert_html_to_image(html, output_file, width=650, height=800, device_scale_factor=2):
|
18 |
+
try:
|
19 |
+
browser = await launch({
|
20 |
+
'headless': True,
|
21 |
+
'args': ['--no-sandbox', '--disable-setuid-sandbox'],
|
22 |
+
'timeout': 60000 # Increase timeout if needed
|
23 |
+
})
|
24 |
+
page = await browser.newPage()
|
25 |
+
await page.setViewport({'width': width, 'height': height, 'deviceScaleFactor': device_scale_factor})
|
26 |
+
await page.setContent(html)
|
27 |
+
await page.screenshot({'path': output_file})
|
28 |
+
await browser.close()
|
29 |
+
return output_file # Return the path of the captured image
|
30 |
+
except Exception as e:
|
31 |
+
print(f"Error in convert_html_to_image: {e}")
|
32 |
+
raise
|
33 |
+
|
34 |
+
async def optimize_image(input_file, output_file, target_size_kb=700):
|
35 |
+
# Open the image using PIL
|
36 |
+
with Image.open(input_file) as img:
|
37 |
+
# Calculate the initial quality to achieve the target size
|
38 |
+
quality = 95
|
39 |
+
temp_output_file = output_file + ".temp.jpg"
|
40 |
+
img.save(temp_output_file, format='JPEG', quality=quality, optimize=True)
|
41 |
+
while os.path.getsize(temp_output_file) > target_size_kb * 1024 and quality > 0:
|
42 |
+
# Reduce the quality and save to temporary file
|
43 |
+
quality -= 5
|
44 |
+
img.save(temp_output_file, format='JPEG', quality=quality, optimize=True)
|
45 |
+
|
46 |
+
# Save the optimized image to the output file
|
47 |
+
os.replace(temp_output_file, output_file)
|
48 |
+
|
49 |
+
async def mainFunction(html_content:str):
|
50 |
+
output_image_file = "image.jpg"
|
51 |
+
captured_image_path = await convert_html_to_image(html_content, output_image_file)
|
52 |
+
|
53 |
+
# Optimize the image to be less than 200KB
|
54 |
+
await optimize_image(captured_image_path, output_image_file)
|
55 |
+
|
56 |
+
return output_image_file
|
57 |
+
|
58 |
+
# Run the asynchronous main function
|
59 |
+
@app.post("/convert-html-to-image/")
|
60 |
+
async def convert_html_to_image_endpoint(html_content:HtmlInput):
|
61 |
+
image_path = await mainFunction(html_content.message)
|
62 |
+
|
63 |
+
# Check if image was generated
|
64 |
+
if not image_path or not os.path.exists(image_path):
|
65 |
+
raise HTTPException(status_code=500, detail="Image generation failed.")
|
66 |
+
|
67 |
+
# Open the image file for streaming
|
68 |
+
with open(image_path, "rb") as img_file:
|
69 |
+
buffer = io.BytesIO(img_file.read())
|
70 |
+
|
71 |
+
buffer.seek(0)
|
72 |
+
|
73 |
+
# Return the image as a downloadable file
|
74 |
+
return StreamingResponse(buffer, media_type="image/jpeg", headers={
|
75 |
+
"Content-Disposition": f"attachment; filename={os.path.basename(image_path)}"
|
76 |
+
})
|