Spaces:
Paused
Paused
Update main.py
Browse files
main.py
CHANGED
@@ -4,7 +4,7 @@ import fitz # PyMuPDF
|
|
4 |
import logging
|
5 |
import asyncio
|
6 |
from uuid import uuid4
|
7 |
-
from fastapi import FastAPI, File, UploadFile
|
8 |
from telegram import Bot
|
9 |
from telegram.constants import ParseMode
|
10 |
from starlette.middleware.cors import CORSMiddleware
|
@@ -39,6 +39,7 @@ app.add_middleware(
|
|
39 |
def check_status():
|
40 |
return {"status": "API is working"}
|
41 |
|
|
|
42 |
@app.post("/upload")
|
43 |
async def upload_pdf(file: UploadFile = File(...)):
|
44 |
""" Upload PDF, convert to images, send to Telegram & cleanup """
|
@@ -64,66 +65,65 @@ async def upload_pdf(file: UploadFile = File(...)):
|
|
64 |
|
65 |
async def convert_pdf_to_images(pdf_path):
|
66 |
""" Converts PDF pages to images & sends them to Telegram """
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
67 |
try:
|
68 |
-
|
69 |
-
|
70 |
-
doc = await loop.run_in_executor(None, fitz.open, pdf_path)
|
71 |
-
image_links = []
|
72 |
-
|
73 |
-
for i in range(len(doc)):
|
74 |
-
page = await loop.run_in_executor(None, doc.load_page, i)
|
75 |
-
image_path = os.path.join(IMAGES_DIR, f"{uuid4()}.png")
|
76 |
-
|
77 |
-
# Get pixmap and save image
|
78 |
-
pix = await loop.run_in_executor(None, page.get_pixmap)
|
79 |
-
await loop.run_in_executor(None, pix.save, image_path)
|
80 |
-
|
81 |
-
# Send image to Telegram with page number caption
|
82 |
-
caption = f"Page {i+1}"
|
83 |
-
telegram_url = await send_image_to_telegram(image_path, caption)
|
84 |
-
|
85 |
-
if telegram_url:
|
86 |
-
image_links.append(telegram_url)
|
87 |
-
os.remove(image_path) # Cleanup only if successful
|
88 |
-
else:
|
89 |
-
logger.error(f"Failed to send page {i+1}")
|
90 |
-
if os.path.exists(image_path):
|
91 |
-
os.remove(image_path) # Cleanup failed image
|
92 |
-
|
93 |
-
await loop.run_in_executor(None, doc.close)
|
94 |
-
return image_links
|
95 |
|
96 |
-
|
97 |
-
|
98 |
-
raise
|
99 |
-
finally:
|
100 |
-
# Cleanup PDF after processing
|
101 |
-
if os.path.exists(pdf_path):
|
102 |
-
os.remove(pdf_path)
|
103 |
|
104 |
-
async def send_image_to_telegram(image_path, caption):
|
105 |
-
""" Sends an image to Telegram Bot and returns the direct image URL """
|
106 |
-
try:
|
107 |
-
with open(image_path, "rb") as img_file:
|
108 |
-
message = await bot.send_photo(
|
109 |
-
chat_id=TELEGRAM_CHAT_ID,
|
110 |
-
photo=img_file,
|
111 |
-
caption=caption
|
112 |
-
)
|
113 |
-
# Extract the direct URL of the uploaded image
|
114 |
-
image_url = message.photo[-1].file_id # Get the highest quality image ID
|
115 |
-
|
116 |
-
# Generate the direct file link
|
117 |
-
file_info = await bot.get_file(image_url)
|
118 |
-
direct_link = f"{file_info.file_path.lstrip('/')}"
|
119 |
-
|
120 |
-
|
121 |
-
return direct_link
|
122 |
except Exception as e:
|
123 |
-
logger.error(f"Error
|
124 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
125 |
|
|
|
|
|
|
|
|
|
|
|
|
|
126 |
|
127 |
if __name__ == "__main__":
|
128 |
import uvicorn
|
129 |
-
uvicorn.run(app, host="0.0.0.0", port=7860, log_level="info", reload=True)
|
|
|
4 |
import logging
|
5 |
import asyncio
|
6 |
from uuid import uuid4
|
7 |
+
from fastapi import FastAPI, File, UploadFile, Form
|
8 |
from telegram import Bot
|
9 |
from telegram.constants import ParseMode
|
10 |
from starlette.middleware.cors import CORSMiddleware
|
|
|
39 |
def check_status():
|
40 |
return {"status": "API is working"}
|
41 |
|
42 |
+
# ----- Original PDF Upload Endpoint (unchanged) -----
|
43 |
@app.post("/upload")
|
44 |
async def upload_pdf(file: UploadFile = File(...)):
|
45 |
""" Upload PDF, convert to images, send to Telegram & cleanup """
|
|
|
65 |
|
66 |
async def convert_pdf_to_images(pdf_path):
|
67 |
""" Converts PDF pages to images & sends them to Telegram """
|
68 |
+
# Use a thread executor for synchronous PDF operations
|
69 |
+
loop = asyncio.get_running_loop()
|
70 |
+
doc = await loop.run_in_executor(None, fitz.open, pdf_path)
|
71 |
+
image_links = []
|
72 |
+
|
73 |
+
for i in range(len(doc)):
|
74 |
+
page = await loop.run_in_executor(None, doc.load_page, i)
|
75 |
+
image_path = os.path.join(IMAGES_DIR, f"{uuid4()}.png")
|
76 |
+
|
77 |
+
# Get pixmap and save image
|
78 |
+
pix = await loop.run_in_executor(None, page.get_pixmap)
|
79 |
+
await loop.run_in_executor(None, pix.save, image_path)
|
80 |
+
|
81 |
+
# Send image to Telegram with page number caption
|
82 |
+
caption = f"Page {i+1}"
|
83 |
+
telegram_url = await send_image_to_telegram(image_path, caption)
|
84 |
+
image_links.append(str(telegram_url))
|
85 |
+
|
86 |
+
return image_links
|
87 |
+
# -------------------------------------------------------
|
88 |
+
|
89 |
+
# ----- New Endpoint: Image Upload with Caption -----
|
90 |
+
@app.post("/upload-image")
|
91 |
+
async def upload_image(
|
92 |
+
file: UploadFile = File(...),
|
93 |
+
caption: str = Form("Uploaded image")
|
94 |
+
):
|
95 |
+
"""
|
96 |
+
Upload an image along with a caption and send it to Telegram.
|
97 |
+
"""
|
98 |
+
file_id = str(uuid4())
|
99 |
+
extension = file.filename.split(".")[-1]
|
100 |
+
image_path = os.path.join(IMAGES_DIR, f"{file_id}.{extension}")
|
101 |
+
|
102 |
try:
|
103 |
+
with open(image_path, "wb") as buffer:
|
104 |
+
shutil.copyfileobj(file.file, buffer)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
105 |
|
106 |
+
telegram_response = await send_image_to_telegram(image_path, caption)
|
107 |
+
return {"status": "Image sent to Telegram", "telegram_response": str(telegram_response)}
|
|
|
|
|
|
|
|
|
|
|
108 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
109 |
except Exception as e:
|
110 |
+
logger.error(f"Error processing image: {e}")
|
111 |
+
if os.path.exists(image_path):
|
112 |
+
os.remove(image_path)
|
113 |
+
return {"status": "error", "message": str(e)}
|
114 |
+
# -------------------------------------------------------
|
115 |
+
|
116 |
+
def send_photo_sync(chat_id, image_file, caption):
|
117 |
+
""" Synchronous helper to send a photo via Telegram """
|
118 |
+
return bot.send_photo(chat_id=chat_id, photo=image_file, caption=caption, parse_mode=ParseMode.HTML)
|
119 |
|
120 |
+
async def send_image_to_telegram(image_path, caption):
|
121 |
+
""" Send an image to Telegram asynchronously """
|
122 |
+
loop = asyncio.get_running_loop()
|
123 |
+
with open(image_path, "rb") as image_file:
|
124 |
+
response = await loop.run_in_executor(None, send_photo_sync, TELEGRAM_CHAT_ID, image_file, caption)
|
125 |
+
return response
|
126 |
|
127 |
if __name__ == "__main__":
|
128 |
import uvicorn
|
129 |
+
uvicorn.run(app, host="0.0.0.0", port=7860, log_level="info", reload=True)
|