import base64 import io import os import re import requests from urllib.parse import quote from PIL import Image from g4f.client import Client from g4f.Provider import RetryProvider, PollinationsAI, Airforce, ReplicateHome, BlackboxCreateAgent from g4f.Provider.hf_space.BlackForestLabsFlux1Schnell import BlackForestLabsFlux1Schnell from g4f.Provider.hf_space.VoodoohopFlux1Schnell import VoodoohopFlux1Schnell 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, category, summary): print("Generating image...") import time start = time.time() try: try: try: 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, NSFW, NUDE, vulgar, negative, unsuitable, inappropriate, offensive, revealing, sexual, explicit", prompt = f"Generate accurate image representing the {category} concept: ```{title.strip()}: {summary.strip()}```" client = Client() img_data = client.images.generate( provider=RetryProvider( providers=[ReplicateHome, Airforce], shuffle=True, single_provider_retry=True, max_retries=3, ), model="sdxl", prompt=prompt, negative_prompt=negative, response_format="b64_json", width=1024, height=576, ).data[0].b64_json print(f"Image generated in {time.time() - start:.2f} seconds") if img_data: return f"data:image/png;base64,{img_data}" return None except Exception as e: print(f"Error generating image: {e}") 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, NSFW, NUDE, vulgar, negative, unsuitable, inappropriate, offensive, revealing, sexual, explicit", prompt = f"Generate accurate image representing the {category} concept: ```{title.strip()}: {summary.strip()}```" client = Client() img_data = client.images.generate( provider=RetryProvider( providers=[Airforce, PollinationsAI, BlackboxCreateAgent], shuffle=True, single_provider_retry=True, max_retries=3, ), model="flux", prompt=prompt, negative_prompt=negative, response_format="b64_json", width=1024, height=576, ).data[0].b64_json print(f"Image generated in {time.time() - start:.2f} seconds") if img_data: return f"data:image/png;base64,{img_data}" return None except Exception as e: print(f"Error generating image: {e}") 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, NSFW, NUDE, vulgar, negative, unsuitable, inappropriate, offensive, revealing, sexual, explicit", prompt = f"Generate accurate image representing the {category} concept: ```{title.strip()}: {summary.strip()}```" client = Client() img_data = client.images.generate( provider=RetryProvider( providers=[BlackForestLabsFlux1Schnell, VoodoohopFlux1Schnell], shuffle=True, single_provider_retry=True, max_retries=3, ), model="flux-schnell", prompt=prompt, negative_prompt=negative, response_format="b64_json", width=1024, height=576, ).data[0].b64_json print(f"Image generated in {time.time() - start:.2f} seconds") if img_data: return f"data:image/png;base64,{img_data}" return None except Exception as e: print(f"Error generating image: {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 fetch_image(title, category, summary): title = r"{}".format(title) category = r"{}".format(category) summary = extract_summary(summary) image_url = "https://i.ibb.co/TBJqggw/Image-Not-Found.jpg" try: data_uri = generate_image(title, category, summary) if data_uri: base64_image = fix_base64_padding(data_uri.split(",")[1]) if base64_image: if verify_image(base64.b64decode(base64_image, validate=True)): image_url = f"data:image/png;base64,{base64_image}" 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 = "Exposition: Enumerative Geometry and Tree-Level Gromov-Witten Invariants" category = "Mathematics" summary = "The text discusses the Kontsevich-Manin formula for enumerating degree d rational curves via Gromov-Witten invariants. It details the calculation of these invariants using moduli spaces of stable maps and explores their implications in enumerative geometry." image_url = fetch_image(title, category, summary) print(image_url)