File size: 1,975 Bytes
745d3f1
0bd715a
745d3f1
0125000
0bd715a
 
 
 
 
 
5bf1b3e
745d3f1
5bf1b3e
 
 
eaff201
 
745d3f1
 
5bf1b3e
0bd715a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5bf1b3e
745d3f1
 
 
0733eda
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
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)

@app.get("/")
def check_status():
    return {"status": "API is working"}

@app.post("/upload")
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)