Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import io
|
| 3 |
+
import base64
|
| 4 |
+
import tempfile
|
| 5 |
+
import streamlit as st
|
| 6 |
+
import requests
|
| 7 |
+
from PIL import Image
|
| 8 |
+
from pdf2image import convert_from_path
|
| 9 |
+
from openai import OpenAI
|
| 10 |
+
|
| 11 |
+
# Load API key from Hugging Face secret
|
| 12 |
+
API_KEY = os.getenv("API_KEY")
|
| 13 |
+
if not API_KEY:
|
| 14 |
+
st.error("β API_KEY not found. Please add it to your Space secrets.")
|
| 15 |
+
st.stop()
|
| 16 |
+
|
| 17 |
+
CLIENT_BASE = "https://api.aimlapi.com/v1"
|
| 18 |
+
|
| 19 |
+
st.title("π PDF OCR with GPTβ4o Vision (AIMLAPI)")
|
| 20 |
+
st.markdown("Upload a PDF file, extract text using GPTβ4o Vision, and download the result as `.txt`.")
|
| 21 |
+
|
| 22 |
+
def pdf_to_images(pdf_path):
|
| 23 |
+
try:
|
| 24 |
+
return convert_from_path(pdf_path, dpi=200, fmt="PNG")
|
| 25 |
+
except Exception as e:
|
| 26 |
+
st.error(f"β PDF conversion error: {e}")
|
| 27 |
+
return None
|
| 28 |
+
|
| 29 |
+
def image_to_base64(img):
|
| 30 |
+
buffer = io.BytesIO()
|
| 31 |
+
img.save(buffer, format="PNG")
|
| 32 |
+
return base64.b64encode(buffer.getvalue()).decode("utf-8")
|
| 33 |
+
|
| 34 |
+
def ocr_gpt4o(images):
|
| 35 |
+
client = OpenAI(base_url=CLIENT_BASE, api_key=API_KEY)
|
| 36 |
+
extracted_pages = []
|
| 37 |
+
for i, image in enumerate(images, 1):
|
| 38 |
+
st.write(f"π Processing page {i}/{len(images)} (OpenAI client)...")
|
| 39 |
+
b64 = image_to_base64(image)
|
| 40 |
+
try:
|
| 41 |
+
response = client.chat.completions.create(
|
| 42 |
+
model="gpt-4o",
|
| 43 |
+
messages=[
|
| 44 |
+
{
|
| 45 |
+
"role": "user",
|
| 46 |
+
"content": [
|
| 47 |
+
{
|
| 48 |
+
"type": "text",
|
| 49 |
+
"text": "Extract all text from this image. Preserve formatting. Return only the extracted text."
|
| 50 |
+
},
|
| 51 |
+
{
|
| 52 |
+
"type": "image_url",
|
| 53 |
+
"image_url": {
|
| 54 |
+
"url": f"data:image/png;base64,{b64}"
|
| 55 |
+
}
|
| 56 |
+
}
|
| 57 |
+
]
|
| 58 |
+
}
|
| 59 |
+
],
|
| 60 |
+
max_tokens=4000,
|
| 61 |
+
temperature=0
|
| 62 |
+
)
|
| 63 |
+
content = response.choices[0].message.content
|
| 64 |
+
extracted_pages.append(f"--- Page {i} ---\n{content}")
|
| 65 |
+
except Exception as e:
|
| 66 |
+
st.warning(f"β οΈ Error on page {i}: {e}")
|
| 67 |
+
extracted_pages.append(f"--- Page {i} ---\n[ERROR]")
|
| 68 |
+
return "\n\n".join(extracted_pages)
|
| 69 |
+
|
| 70 |
+
def ocr_direct(images):
|
| 71 |
+
url = "https://api.aimlapi.com/chat/completions"
|
| 72 |
+
headers = {"Authorization": f"Bearer {API_KEY}", "Content-Type": "application/json"}
|
| 73 |
+
extracted_pages = []
|
| 74 |
+
for i, image in enumerate(images, 1):
|
| 75 |
+
st.write(f"π Processing page {i}/{len(images)} (requests fallback)...")
|
| 76 |
+
b64 = image_to_base64(image)
|
| 77 |
+
payload = {
|
| 78 |
+
"model": "gpt-4o",
|
| 79 |
+
"messages": [
|
| 80 |
+
{
|
| 81 |
+
"role": "user",
|
| 82 |
+
"content": [
|
| 83 |
+
{"type": "text", "text": "Extract all text from this image. Preserve formatting. Return only the extracted text."},
|
| 84 |
+
{"type": "image_url", "image_url": {"url": f"data:image/png;base64,{b64}"}}
|
| 85 |
+
]
|
| 86 |
+
}
|
| 87 |
+
],
|
| 88 |
+
"max_tokens": 4000,
|
| 89 |
+
"temperature": 0
|
| 90 |
+
}
|
| 91 |
+
try:
|
| 92 |
+
response = requests.post(url, headers=headers, json=payload)
|
| 93 |
+
if response.status_code == 200:
|
| 94 |
+
content = response.json()["choices"][0]["message"]["content"]
|
| 95 |
+
extracted_pages.append(f"--- Page {i} ---\n{content}")
|
| 96 |
+
else:
|
| 97 |
+
st.warning(f"β οΈ API error on page {i}: {response.status_code}")
|
| 98 |
+
extracted_pages.append(f"--- Page {i} ---\n[ERROR]")
|
| 99 |
+
except Exception as e:
|
| 100 |
+
st.warning(f"β οΈ Exception on page {i}: {e}")
|
| 101 |
+
extracted_pages.append(f"--- Page {i} ---\n[ERROR]")
|
| 102 |
+
return "\n\n".join(extracted_pages)
|
| 103 |
+
|
| 104 |
+
uploaded = st.file_uploader("π Upload a PDF file", type=["pdf"])
|
| 105 |
+
if uploaded:
|
| 106 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as tmp_file:
|
| 107 |
+
tmp_file.write(uploaded.read())
|
| 108 |
+
pdf_path = tmp_file.name
|
| 109 |
+
|
| 110 |
+
st.info("π₯ Converting PDF to images...")
|
| 111 |
+
images = pdf_to_images(pdf_path)
|
| 112 |
+
|
| 113 |
+
if images:
|
| 114 |
+
extracted_text = None
|
| 115 |
+
|
| 116 |
+
# First try with OpenAI client
|
| 117 |
+
try:
|
| 118 |
+
extracted_text = ocr_gpt4o(images)
|
| 119 |
+
except Exception as e:
|
| 120 |
+
st.warning(f"β οΈ Client method failed: {e}")
|
| 121 |
+
st.info("π Falling back to requests method...")
|
| 122 |
+
extracted_text = ocr_direct(images)
|
| 123 |
+
|
| 124 |
+
if extracted_text:
|
| 125 |
+
st.success("β
OCR completed successfully!")
|
| 126 |
+
st.text_area("π Extracted Text", extracted_text, height=300)
|
| 127 |
+
output_name = os.path.splitext(uploaded.name)[0] + ".txt"
|
| 128 |
+
st.download_button("πΎ Download Extracted Text", extracted_text, file_name=output_name, mime="text/plain")
|
| 129 |
+
else:
|
| 130 |
+
st.error("β OCR failed on all methods.")
|