Spaces:
Paused
Paused
from fastapi import FastAPI | |
from fastapi.responses import JSONResponse | |
from fastapi.middleware.cors import CORSMiddleware | |
import fitz # PyMuPDF | |
import requests | |
import shutil | |
import os | |
from fastapi import FastAPI, File, UploadFile | |
from uuid import uuid4 | |
app = FastAPI() | |
origins = ["*"] | |
app.add_middleware( | |
CORSMiddleware, | |
allow_origins=origins, | |
allow_credentials=True, | |
allow_methods=["*"], | |
allow_headers=["*"], | |
) | |
UPLOAD_DIR = "uploads" | |
IMAGES_DIR = "images" | |
TELEGRAPH_UPLOAD_URL = "https://telegra.ph/upload" | |
os.makedirs(UPLOAD_DIR, exist_ok=True) | |
os.makedirs(IMAGES_DIR, exist_ok=True) | |
def check_status(): | |
return {"status": "API is working"} | |
def upload_pdf(file: UploadFile = File(...)): | |
file_path = os.path.join(UPLOAD_DIR, f"{uuid4()}.pdf") | |
with open(file_path, "wb") as buffer: | |
shutil.copyfileobj(file.file, buffer) | |
image_links = convert_pdf_to_images(file_path) | |
return {"images": image_links} | |
def convert_pdf_to_images(pdf_path): | |
doc = fitz.open(pdf_path) | |
image_links = [] | |
for i, page in enumerate(doc): | |
image_path = os.path.join(IMAGES_DIR, f"{uuid4()}.png") | |
pix = page.get_pixmap() | |
pix.save(image_path) | |
telegraph_url = upload_to_telegraph(image_path) | |
if telegraph_url: | |
image_links.append(telegraph_url) | |
os.remove(image_path) # Cleanup after upload | |
os.remove(pdf_path) # Cleanup uploaded PDF | |
return image_links | |
def upload_to_telegraph(image_path): | |
with open(image_path, "rb") as img_file: | |
response = requests.post(TELEGRAPH_UPLOAD_URL, files={"file": img_file}) | |
if response.status_code == 200 and isinstance(response.json(), list): | |
return "https://telegra.ph" + response.json()[0]["src"] | |
return None | |
if __name__ == "__main__": | |
import uvicorn | |
uvicorn.run(app, host="0.0.0.0", port=7860, log_level="info", reload=True) | |