changes to app.py
Browse files
app.py
CHANGED
|
@@ -16,7 +16,7 @@ import fitz
|
|
| 16 |
from PIL import Image
|
| 17 |
import pytesseract
|
| 18 |
from sentence_transformers import SentenceTransformer
|
| 19 |
-
from ctransformers import
|
| 20 |
|
| 21 |
# --- THIS IS THE FIX FOR TESSERACT ---
|
| 22 |
# Explicitly tell pytesseract where to find the Tesseract OCR engine.
|
|
@@ -38,14 +38,18 @@ app.add_middleware(
|
|
| 38 |
# --- Load Optimized Models ---
|
| 39 |
try:
|
| 40 |
logger.info("Loading optimized AI models...")
|
|
|
|
| 41 |
# Using a smaller, but still powerful, BGE model
|
| 42 |
embedding_model = SentenceTransformer('BAAI/bge-base-en-v1.5')
|
| 43 |
|
| 44 |
-
#
|
| 45 |
-
llm =
|
| 46 |
-
"TheBloke/TinyLlama-1.1B-Chat-v1.0-GGUF",
|
| 47 |
-
model_file="tinyllama-1.1b-chat-v1.0.Q4_K_M.gguf"
|
|
|
|
|
|
|
| 48 |
)
|
|
|
|
| 49 |
logger.info("AI models loaded successfully.")
|
| 50 |
except Exception as e:
|
| 51 |
logger.critical(f"Fatal error: Could not load AI models. {e}")
|
|
@@ -55,43 +59,62 @@ except Exception as e:
|
|
| 55 |
SESSION_DATA = {}
|
| 56 |
|
| 57 |
# --- 2. DATA MODELS ---
|
| 58 |
-
class QueryRequest(BaseModel):
|
| 59 |
-
|
| 60 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 61 |
|
| 62 |
# --- 3. HELPER FUNCTIONS ---
|
| 63 |
def parse_pdf(content: bytes) -> str:
|
| 64 |
-
doc = fitz.open(stream=content, filetype="pdf")
|
|
|
|
| 65 |
|
| 66 |
def parse_image(content: bytes) -> str:
|
| 67 |
-
image = Image.open(io.BytesIO(content))
|
|
|
|
| 68 |
|
| 69 |
# --- 4. API ENDPOINTS ---
|
| 70 |
|
| 71 |
@app.get("/")
|
| 72 |
-
def read_root():
|
|
|
|
| 73 |
|
| 74 |
@app.post("/upload", response_model=UploadResponse)
|
| 75 |
async def upload_file(file: UploadFile = File(...)):
|
| 76 |
-
if not embedding_model:
|
|
|
|
| 77 |
|
| 78 |
session_id = str(uuid.uuid4())
|
| 79 |
content = await file.read()
|
| 80 |
content_type = file.content_type
|
| 81 |
|
| 82 |
-
if content_type == "application/pdf":
|
| 83 |
-
|
| 84 |
-
elif
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 88 |
|
| 89 |
text_chunks = semantic_chunker(text, embedding_model)
|
| 90 |
-
if not text_chunks:
|
|
|
|
| 91 |
|
| 92 |
embeddings = embedding_model.encode(text_chunks, convert_to_numpy=True)
|
| 93 |
serialized_index = create_faiss_index(embeddings)
|
| 94 |
-
if not serialized_index:
|
|
|
|
| 95 |
|
| 96 |
SESSION_DATA[session_id] = {"chunks": text_chunks, "index": serialized_index}
|
| 97 |
logger.info(f"Session {session_id} created with {len(text_chunks)} chunks.")
|
|
@@ -110,7 +133,8 @@ async def query_session(session_id: str, request: QueryRequest):
|
|
| 110 |
question_embedding = embedding_model.encode([query_with_prefix], convert_to_numpy=True).astype('float32')
|
| 111 |
|
| 112 |
index = deserialize_faiss_index(session["index"])
|
| 113 |
-
if not index:
|
|
|
|
| 114 |
|
| 115 |
k = min(5, index.ntotal)
|
| 116 |
distances, indices = index.search(question_embedding, k)
|
|
@@ -135,4 +159,4 @@ Question: {request.question}<|im_end|>
|
|
| 135 |
stop=["<|im_end|>"]
|
| 136 |
)
|
| 137 |
|
| 138 |
-
return {"answer": answer.strip(), "context": context}
|
|
|
|
| 16 |
from PIL import Image
|
| 17 |
import pytesseract
|
| 18 |
from sentence_transformers import SentenceTransformer
|
| 19 |
+
from ctransformers import AutoModelForCausalLM # ✅ FIXED import
|
| 20 |
|
| 21 |
# --- THIS IS THE FIX FOR TESSERACT ---
|
| 22 |
# Explicitly tell pytesseract where to find the Tesseract OCR engine.
|
|
|
|
| 38 |
# --- Load Optimized Models ---
|
| 39 |
try:
|
| 40 |
logger.info("Loading optimized AI models...")
|
| 41 |
+
|
| 42 |
# Using a smaller, but still powerful, BGE model
|
| 43 |
embedding_model = SentenceTransformer('BAAI/bge-base-en-v1.5')
|
| 44 |
|
| 45 |
+
# Load TinyLlama in GGUF format using ctransformers
|
| 46 |
+
llm = AutoModelForCausalLM.from_pretrained(
|
| 47 |
+
"TheBloke/TinyLlama-1.1B-Chat-v1.0-GGUF",
|
| 48 |
+
model_file="tinyllama-1.1b-chat-v1.0.Q4_K_M.gguf",
|
| 49 |
+
model_type="llama", # Tell ctransformers the model family
|
| 50 |
+
gpu_layers=0 # For CPU-only environment
|
| 51 |
)
|
| 52 |
+
|
| 53 |
logger.info("AI models loaded successfully.")
|
| 54 |
except Exception as e:
|
| 55 |
logger.critical(f"Fatal error: Could not load AI models. {e}")
|
|
|
|
| 59 |
SESSION_DATA = {}
|
| 60 |
|
| 61 |
# --- 2. DATA MODELS ---
|
| 62 |
+
class QueryRequest(BaseModel):
|
| 63 |
+
question: str
|
| 64 |
+
|
| 65 |
+
class UploadResponse(BaseModel):
|
| 66 |
+
session_id: str
|
| 67 |
+
filename: str
|
| 68 |
+
chunks_created: int
|
| 69 |
+
|
| 70 |
+
class QueryResponse(BaseModel):
|
| 71 |
+
answer: str
|
| 72 |
+
context: str
|
| 73 |
|
| 74 |
# --- 3. HELPER FUNCTIONS ---
|
| 75 |
def parse_pdf(content: bytes) -> str:
|
| 76 |
+
doc = fitz.open(stream=content, filetype="pdf")
|
| 77 |
+
return "".join(page.get_text() for page in doc)
|
| 78 |
|
| 79 |
def parse_image(content: bytes) -> str:
|
| 80 |
+
image = Image.open(io.BytesIO(content))
|
| 81 |
+
return pytesseract.image_to_string(image)
|
| 82 |
|
| 83 |
# --- 4. API ENDPOINTS ---
|
| 84 |
|
| 85 |
@app.get("/")
|
| 86 |
+
def read_root():
|
| 87 |
+
return {"status": "ok", "message": "Welcome to the Optimized Universal Data AI"}
|
| 88 |
|
| 89 |
@app.post("/upload", response_model=UploadResponse)
|
| 90 |
async def upload_file(file: UploadFile = File(...)):
|
| 91 |
+
if not embedding_model:
|
| 92 |
+
raise HTTPException(status_code=503, detail="Embedding model not available.")
|
| 93 |
|
| 94 |
session_id = str(uuid.uuid4())
|
| 95 |
content = await file.read()
|
| 96 |
content_type = file.content_type
|
| 97 |
|
| 98 |
+
if content_type == "application/pdf":
|
| 99 |
+
text = parse_pdf(content)
|
| 100 |
+
elif content_type and content_type.startswith("image/"):
|
| 101 |
+
text = parse_image(content)
|
| 102 |
+
elif file.filename.endswith(('.txt', '.md')):
|
| 103 |
+
text = content.decode("utf-8")
|
| 104 |
+
else:
|
| 105 |
+
raise HTTPException(status_code=400, detail=f"Unsupported file type: {content_type}")
|
| 106 |
+
|
| 107 |
+
if not text.strip():
|
| 108 |
+
raise HTTPException(status_code=400, detail="No text could be extracted.")
|
| 109 |
|
| 110 |
text_chunks = semantic_chunker(text, embedding_model)
|
| 111 |
+
if not text_chunks:
|
| 112 |
+
raise HTTPException(status_code=400, detail="Document too short to be processed.")
|
| 113 |
|
| 114 |
embeddings = embedding_model.encode(text_chunks, convert_to_numpy=True)
|
| 115 |
serialized_index = create_faiss_index(embeddings)
|
| 116 |
+
if not serialized_index:
|
| 117 |
+
raise HTTPException(status_code=500, detail="Failed to create document index.")
|
| 118 |
|
| 119 |
SESSION_DATA[session_id] = {"chunks": text_chunks, "index": serialized_index}
|
| 120 |
logger.info(f"Session {session_id} created with {len(text_chunks)} chunks.")
|
|
|
|
| 133 |
question_embedding = embedding_model.encode([query_with_prefix], convert_to_numpy=True).astype('float32')
|
| 134 |
|
| 135 |
index = deserialize_faiss_index(session["index"])
|
| 136 |
+
if not index:
|
| 137 |
+
raise HTTPException(status_code=500, detail="Could not load session index.")
|
| 138 |
|
| 139 |
k = min(5, index.ntotal)
|
| 140 |
distances, indices = index.search(question_embedding, k)
|
|
|
|
| 159 |
stop=["<|im_end|>"]
|
| 160 |
)
|
| 161 |
|
| 162 |
+
return {"answer": answer.strip(), "context": context}
|