ReXploreBackend / image.py
raannakasturi's picture
Update image.py
5c6de9a verified
raw
history blame
4.4 kB
import base64
import io
import os
import re
import requests
from urllib.parse import quote
from PIL import Image
def extract_summary(text):
text = text.replace("#", "").strip().lower()
match = re.search(r"summary(.*?)highlights", text, re.DOTALL)
if match:
return match.group(1).strip()
return text
def fix_base64_padding(data):
missing_padding = len(data) % 4
if missing_padding:
data += "=" * (4 - missing_padding)
return data
def generate_image(title, summary):
try:
extracted_summary = extract_summary(summary)
negative="low quality, blurry, pixelated, bad anatomy, bad hands, three hands, three legs, bad arms, missing legs, missing arms, poorly drawn face, poorly rendered hands, bad face, fused face, cloned face, worst face, three crus, extra crus, fused crus, worst feet, three feet, fused feet, fused thigh, three thigh, extra thigh, worst thigh, missing fingers, extra fingers, ugly fingers, long fingers, bad composition, horn, extra eyes, huge eyes, 2girl, amputation, disconnected limbs, cartoon, cg, 3d, unreal, animate, cgi, render, artwork, illustration, 3d render, cinema 4d, artstation, octane render, mutated body parts, painting, oil painting, 2d, sketch, bad photography, bad photo, deviant art, aberrations, abstract, anime, black and white, collapsed, conjoined, creative, drawing, extra windows, harsh lighting, jpeg artifacts, low saturation, monochrome, multiple levels, overexposed, oversaturated, photoshop, rotten, surreal, twisted, UI, underexposed, unnatural, unreal engine, unrealistic, video game, deformed body features",
image_api_endpoint = "image.pollinations.ai"
params = f"negative={quote(str(negative))}&seed=2342342340&width=1024&height=576&nologo=True&private=False&model=turbo&enhance=True"
data_header = {"Content-Type": "application/json"}
prompt = quote(f"{title.strip()}: {extracted_summary.strip()}")
image_url = f"https://{image_api_endpoint}/prompt/{prompt}?{params}"
img_data = requests.get(image_url, headers=data_header, timeout=60).content
if img_data:
base64_encoded = base64.b64encode(img_data).decode("utf-8")
return f"data:image/png;base64,{base64_encoded}"
return None
except Exception as e:
print(f"An error occurred during image generation: {e}")
return None
def verify_image(image_data):
try:
image_stream = io.BytesIO(image_data)
img = Image.open(image_stream)
img.verify()
return True
except Exception as e:
print(f"Error verifying image: {e}")
return False
def upload_image(data_uri, api_key):
image_url = "https://i.ibb.co/TBJqggw/Image-Not-Found.jpg"
try:
base64_image = fix_base64_padding(data_uri.split(",")[1])
url = f"https://api.imgbb.com/1/upload?key={api_key}"
response = requests.post(url, data={"image": base64_image}, timeout=60).json()
if response.get("status") == 200:
image_url = response["data"]["display_url"]
else:
print(f"Error uploading image: {response}")
image_url = "https://i.ibb.co/TBJqggw/Image-Not-Found.jpg"
except Exception as e:
print(f"Error uploading image: {e}")
image_url = "https://i.ibb.co/TBJqggw/Image-Not-Found.jpg"
finally:
return image_url
def fetch_image(title, summary, api_key):
image_url = "https://i.ibb.co/TBJqggw/Image-Not-Found.jpg"
try:
data_uri = generate_image(title, summary)
if data_uri:
base64_image = fix_base64_padding(data_uri.split(",")[1])
image_data = base64.b64decode(base64_image)
if verify_image(image_data):
image_url = upload_image(data_uri, api_key)
else:
image_url = "https://i.ibb.co/TBJqggw/Image-Not-Found.jpg"
except Exception as e:
print(f"Error fetching image: {e}")
image_url = "https://i.ibb.co/TBJqggw/Image-Not-Found.jpg"
finally:
if os.path.exists("image.png"):
os.remove("image.png")
return image_url
if __name__ == "__main__":
title = "A beautiful sunset over the mountains"
summary = "A beautiful sunset over the mountains with vibrant colors and a clear sky."
print(fetch_image(title, summary, "aa38b04047587c609f5c7e22f9d840f0"))