Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,45 +1,53 @@
|
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import FastAPI, UploadFile, File
|
| 2 |
+
from llama_cpp import Llama
|
| 3 |
+
from llama_cpp.llama_chat_format import Llava15ChatHandler
|
| 4 |
+
from pdf2image import convert_from_bytes
|
| 5 |
+
import io
|
| 6 |
+
from PIL import Image
|
| 7 |
+
|
| 8 |
+
app = FastAPI()
|
| 9 |
+
|
| 10 |
+
print("⏳ Loading Llava 1.6 Model...")
|
| 11 |
+
|
| 12 |
+
# 1. Initialize Vision Handler
|
| 13 |
+
# The Dockerfile (which ran successfully!) saved the file here:
|
| 14 |
+
chat_handler = Llava15ChatHandler(clip_model_path="/app/model/mmproj.gguf")
|
| 15 |
+
|
| 16 |
+
# 2. Initialize Model
|
| 17 |
+
llm = Llama(
|
| 18 |
+
model_path="/app/model/model.gguf",
|
| 19 |
+
chat_handler=chat_handler,
|
| 20 |
+
n_ctx=2048,
|
| 21 |
+
n_gpu_layers=0, # Force CPU
|
| 22 |
+
verbose=True
|
| 23 |
+
)
|
| 24 |
+
print("✅ Model Loaded Successfully!")
|
| 25 |
+
|
| 26 |
+
@app.post("/extract")
|
| 27 |
+
async def extract_text(file: UploadFile = File(...)):
|
| 28 |
+
# --- Image Processing ---
|
| 29 |
+
if file.filename.endswith('.pdf'):
|
| 30 |
+
pdf_bytes = await file.read()
|
| 31 |
+
images = convert_from_bytes(pdf_bytes)
|
| 32 |
+
image = images[0]
|
| 33 |
+
else:
|
| 34 |
+
image_data = await file.read()
|
| 35 |
+
image = Image.open(io.BytesIO(image_data))
|
| 36 |
+
|
| 37 |
+
temp_path = "/tmp/temp_doc.jpg"
|
| 38 |
+
image.save(temp_path)
|
| 39 |
+
|
| 40 |
+
# --- Prompt ---
|
| 41 |
+
messages = [
|
| 42 |
+
{"role": "system", "content": "You are an AI that extracts text from images."},
|
| 43 |
+
{
|
| 44 |
+
"role": "user",
|
| 45 |
+
"content": [
|
| 46 |
+
{"type": "image_url", "image_url": {"url": f"file://{temp_path}"}},
|
| 47 |
+
{"type": "text", "text": "Extract all text from this image. Output in Markdown format."}
|
| 48 |
+
]
|
| 49 |
+
}
|
| 50 |
+
]
|
| 51 |
+
|
| 52 |
+
response = llm.create_chat_completion(messages=messages, max_tokens=1500)
|
| 53 |
+
return {"filename": file.filename, "content": response["choices"][0]["message"]["content"]}
|