|
from fastapi import FastAPI, HTTPException |
|
from fastapi.middleware.cors import CORSMiddleware |
|
from pydantic import BaseModel |
|
import os |
|
import time |
|
import uuid |
|
from generate_image import generate_image |
|
from fastapi.staticfiles import StaticFiles |
|
|
|
app = FastAPI() |
|
|
|
app.mount("/tmp", StaticFiles(directory="tmp"), name="static") |
|
host=os.environ.get("HOST", "https://99i-t2c.hf.space") |
|
|
|
origins = [ |
|
"*" |
|
] |
|
|
|
app.add_middleware( |
|
CORSMiddleware, |
|
allow_origins=origins, |
|
allow_credentials=True, |
|
allow_methods=["*"], |
|
allow_headers=["*"], |
|
) |
|
|
|
|
|
class Markdown(BaseModel): |
|
markdown: str |
|
@app.get("/") |
|
def hello(): |
|
return "hello world" |
|
|
|
@app.post("/t2c") |
|
async def generate_image_endpoint(markdown: Markdown): |
|
|
|
image_filename = 'tmp/'+str(uuid.uuid4()) + ".png" |
|
|
|
generate_image(markdown.markdown, image_filename) |
|
|
|
return {"url": f"{host}/{image_filename}"} |
|
|
|
|
|
def clean_expired_images(): |
|
expiration_time = int(os.environ.get("EXPIRATION_TIME", "3600")) |
|
current_time = time.time() |
|
for filename in os.listdir("tmp"): |
|
file_path = os.path.join("tmp", filename) |
|
if current_time - os.path.getmtime(file_path) > expiration_time: |
|
os.remove(file_path) |
|
|
|
|
|
@app.get("/ci") |
|
async def clean_images_endpoint(): |
|
|
|
clean_expired_images() |
|
return {"message": "Images cleaned"} |
|
|