Spaces:
Paused
Paused
| from fastapi import FastAPI | |
| from fastapi.responses import Response | |
| from PIL import Image, ImageDraw, ImageFont | |
| import io | |
| import textwrap | |
| app = FastAPI() | |
| def home(): | |
| return { | |
| "creator": "Muhammad Farel", | |
| "endpoint": "/ustadz?text=halo" | |
| } | |
| def ustadz(text: str = "Contoh Soalan"): | |
| img = Image.open("template.jpg").convert("RGB") | |
| draw = ImageDraw.Draw(img) | |
| width, height = img.size | |
| # area kotak putih (sesuaikan kalau perlu) | |
| box_x1 = 200 | |
| box_y1 = 150 | |
| box_x2 = width - 200 | |
| box_y2 = 450 | |
| box_width = box_x2 - box_x1 | |
| box_height = box_y2 - box_y1 | |
| # cari font terbesar yang muat | |
| font_size = 80 | |
| while font_size > 20: | |
| font = ImageFont.truetype("DejaVuSans-Bold.ttf", font_size) | |
| lines = textwrap.wrap(text, width=25) | |
| total_height = 0 | |
| for line in lines: | |
| bbox = draw.textbbox((0,0), line, font=font) | |
| total_height += bbox[3] - bbox[1] + 10 | |
| if total_height <= box_height: | |
| break | |
| font_size -= 2 | |
| # posisi tengah vertikal | |
| y = box_y1 + (box_height - total_height) / 2 | |
| for line in lines: | |
| bbox = draw.textbbox((0,0), line, font=font) | |
| text_width = bbox[2] - bbox[0] | |
| x = box_x1 + (box_width - text_width) / 2 | |
| draw.text((x,y), line, fill="black", font=font) | |
| y += (bbox[3] - bbox[1]) + 10 | |
| buffer = io.BytesIO() | |
| img.save(buffer, format="PNG") | |
| return Response(buffer.getvalue(), media_type="image/png") |