Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,10 +1,10 @@
|
|
| 1 |
from fastapi import FastAPI
|
| 2 |
import os
|
| 3 |
-
import pymupdf
|
| 4 |
-
from pptx import Presentation
|
| 5 |
-
from sentence_transformers import SentenceTransformer
|
| 6 |
import torch
|
| 7 |
-
from transformers import CLIPProcessor, CLIPModel
|
| 8 |
from PIL import Image
|
| 9 |
import chromadb
|
| 10 |
import numpy as np
|
|
@@ -14,98 +14,139 @@ app = FastAPI()
|
|
| 14 |
|
| 15 |
# Initialize ChromaDB
|
| 16 |
client = chromadb.PersistentClient(path="/data/chroma_db")
|
| 17 |
-
collection = client.get_or_create_collection(name="knowledge_base"
|
| 18 |
|
|
|
|
| 19 |
pdf_file = "Sutures and Suturing techniques.pdf"
|
| 20 |
pptx_file = "impalnt 1.pptx"
|
| 21 |
|
| 22 |
-
# Initialize
|
| 23 |
-
text_model = SentenceTransformer('
|
| 24 |
-
|
| 25 |
-
|
| 26 |
|
|
|
|
| 27 |
IMAGE_FOLDER = "/data/extracted_images"
|
| 28 |
os.makedirs(IMAGE_FOLDER, exist_ok=True)
|
| 29 |
|
| 30 |
-
# Extract
|
| 31 |
def extract_text_from_pdf(pdf_path):
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
def extract_text_from_pptx(pptx_path):
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 39 |
def extract_images_from_pdf(pdf_path):
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
for
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
f.write(image["image"])
|
| 49 |
-
images.append(img_path)
|
| 50 |
-
return images
|
| 51 |
-
|
| 52 |
-
# Extract images from PowerPoint
|
| 53 |
-
def extract_images_from_pptx(pptx_path):
|
| 54 |
-
images = []
|
| 55 |
-
prs = Presentation(pptx_path)
|
| 56 |
-
for i, slide in enumerate(prs.slides):
|
| 57 |
-
for shape in slide.shapes:
|
| 58 |
-
if shape.shape_type == 13:
|
| 59 |
-
img_path = f"{IMAGE_FOLDER}/pptx_image_{i}.{shape.image.ext}"
|
| 60 |
with open(img_path, "wb") as f:
|
| 61 |
-
f.write(
|
| 62 |
images.append(img_path)
|
| 63 |
-
|
|
|
|
|
|
|
|
|
|
| 64 |
|
| 65 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
def get_text_embedding(text):
|
| 67 |
-
return text_model.encode(text).tolist()
|
| 68 |
|
| 69 |
-
# Extract
|
| 70 |
def get_image_embedding(image_path):
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 78 |
def reduce_embedding_dim(embeddings):
|
| 79 |
-
|
| 80 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 81 |
|
| 82 |
# Store Data in ChromaDB
|
| 83 |
def store_data(texts, image_paths):
|
| 84 |
for i, text in enumerate(texts):
|
| 85 |
-
|
|
|
|
| 86 |
|
| 87 |
-
if
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
for j, img_path in enumerate(image_paths):
|
| 92 |
-
collection.add(ids=[f"image_{j}"], embeddings=[transformed_embeddings[j]
|
| 93 |
|
| 94 |
print("Data stored successfully!")
|
| 95 |
|
| 96 |
-
# Process and
|
| 97 |
def process_and_store(pdf_path=None, pptx_path=None):
|
| 98 |
texts, images = [], []
|
| 99 |
if pdf_path:
|
| 100 |
-
|
|
|
|
|
|
|
| 101 |
images.extend(extract_images_from_pdf(pdf_path))
|
| 102 |
if pptx_path:
|
| 103 |
-
|
|
|
|
|
|
|
| 104 |
images.extend(extract_images_from_pptx(pptx_path))
|
| 105 |
store_data(texts, images)
|
| 106 |
|
|
|
|
| 107 |
process_and_store(pdf_path=pdf_file, pptx_path=pptx_file)
|
| 108 |
|
|
|
|
| 109 |
@app.get("/")
|
| 110 |
def greet_json():
|
| 111 |
return {"Hello": "World!"}
|
|
@@ -116,6 +157,9 @@ def greet_json():
|
|
| 116 |
|
| 117 |
@app.get("/search/")
|
| 118 |
def search(query: str):
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
from fastapi import FastAPI
|
| 2 |
import os
|
| 3 |
+
import pymupdf # PyMuPDF
|
| 4 |
+
from pptx import Presentation
|
| 5 |
+
from sentence_transformers import SentenceTransformer
|
| 6 |
import torch
|
| 7 |
+
from transformers import CLIPProcessor, CLIPModel
|
| 8 |
from PIL import Image
|
| 9 |
import chromadb
|
| 10 |
import numpy as np
|
|
|
|
| 14 |
|
| 15 |
# Initialize ChromaDB
|
| 16 |
client = chromadb.PersistentClient(path="/data/chroma_db")
|
| 17 |
+
collection = client.get_or_create_collection(name="knowledge_base")
|
| 18 |
|
| 19 |
+
# File Paths
|
| 20 |
pdf_file = "Sutures and Suturing techniques.pdf"
|
| 21 |
pptx_file = "impalnt 1.pptx"
|
| 22 |
|
| 23 |
+
# Initialize Embedding Models
|
| 24 |
+
text_model = SentenceTransformer('all-MiniLM-L6-v2')
|
| 25 |
+
model = CLIPModel.from_pretrained("openai/clip-vit-base-patch32")
|
| 26 |
+
processor = CLIPProcessor.from_pretrained("openai/clip-vit-base-patch32")
|
| 27 |
|
| 28 |
+
# Image Storage Folder
|
| 29 |
IMAGE_FOLDER = "/data/extracted_images"
|
| 30 |
os.makedirs(IMAGE_FOLDER, exist_ok=True)
|
| 31 |
|
| 32 |
+
# Extract Text from PDF
|
| 33 |
def extract_text_from_pdf(pdf_path):
|
| 34 |
+
try:
|
| 35 |
+
doc = pymupdf.open(pdf_path)
|
| 36 |
+
text = " ".join(page.get_text() for page in doc)
|
| 37 |
+
return text.strip() if text else None
|
| 38 |
+
except Exception as e:
|
| 39 |
+
print(f"Error extracting text from PDF: {e}")
|
| 40 |
+
return None
|
| 41 |
+
|
| 42 |
+
# Extract Text from PPTX
|
| 43 |
def extract_text_from_pptx(pptx_path):
|
| 44 |
+
try:
|
| 45 |
+
prs = Presentation(pptx_path)
|
| 46 |
+
text = " ".join(
|
| 47 |
+
shape.text for slide in prs.slides for shape in slide.shapes if hasattr(shape, "text")
|
| 48 |
+
)
|
| 49 |
+
return text.strip() if text else None
|
| 50 |
+
except Exception as e:
|
| 51 |
+
print(f"Error extracting text from PPTX: {e}")
|
| 52 |
+
return None
|
| 53 |
+
|
| 54 |
+
# Extract Images from PDF
|
| 55 |
def extract_images_from_pdf(pdf_path):
|
| 56 |
+
try:
|
| 57 |
+
doc = pymupdf.open(pdf_path)
|
| 58 |
+
images = []
|
| 59 |
+
for i, page in enumerate(doc):
|
| 60 |
+
for img_index, img in enumerate(page.get_images(full=True)):
|
| 61 |
+
xref = img[0]
|
| 62 |
+
image = doc.extract_image(xref)
|
| 63 |
+
img_path = f"{IMAGE_FOLDER}/pdf_image_{i}_{img_index}.{image['ext']}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 64 |
with open(img_path, "wb") as f:
|
| 65 |
+
f.write(image["image"])
|
| 66 |
images.append(img_path)
|
| 67 |
+
return images
|
| 68 |
+
except Exception as e:
|
| 69 |
+
print(f"Error extracting images from PDF: {e}")
|
| 70 |
+
return []
|
| 71 |
|
| 72 |
+
# Extract Images from PPTX
|
| 73 |
+
def extract_images_from_pptx(pptx_path):
|
| 74 |
+
try:
|
| 75 |
+
images = []
|
| 76 |
+
prs = Presentation(pptx_path)
|
| 77 |
+
for i, slide in enumerate(prs.slides):
|
| 78 |
+
for shape in slide.shapes:
|
| 79 |
+
if shape.shape_type == 13:
|
| 80 |
+
img_path = f"{IMAGE_FOLDER}/pptx_image_{i}.{shape.image.ext}"
|
| 81 |
+
with open(img_path, "wb") as f:
|
| 82 |
+
f.write(shape.image.blob)
|
| 83 |
+
images.append(img_path)
|
| 84 |
+
return images
|
| 85 |
+
except Exception as e:
|
| 86 |
+
print(f"Error extracting images from PPTX: {e}")
|
| 87 |
+
return []
|
| 88 |
+
|
| 89 |
+
# Convert Text to Embeddings
|
| 90 |
def get_text_embedding(text):
|
| 91 |
+
return text_model.encode(text).tolist()
|
| 92 |
|
| 93 |
+
# Extract Image Embeddings
|
| 94 |
def get_image_embedding(image_path):
|
| 95 |
+
try:
|
| 96 |
+
image = Image.open(image_path)
|
| 97 |
+
inputs = processor(images=image, return_tensors="pt")
|
| 98 |
+
with torch.no_grad():
|
| 99 |
+
image_embedding = model.get_image_features(**inputs).numpy().flatten()
|
| 100 |
+
return image_embedding.tolist()
|
| 101 |
+
except Exception as e:
|
| 102 |
+
print(f"Error generating image embedding: {e}")
|
| 103 |
+
return None
|
| 104 |
+
|
| 105 |
+
# Reduce Embedding Dimensions (If Needed)
|
| 106 |
def reduce_embedding_dim(embeddings):
|
| 107 |
+
try:
|
| 108 |
+
embeddings = np.array(embeddings)
|
| 109 |
+
n_components = min(embeddings.shape[0], embeddings.shape[1], 384) # Ensure valid PCA size
|
| 110 |
+
pca = PCA(n_components=n_components)
|
| 111 |
+
return pca.fit_transform(embeddings).tolist()
|
| 112 |
+
except Exception as e:
|
| 113 |
+
print(f"Error in PCA transformation: {e}")
|
| 114 |
+
return embeddings.tolist() # Return original embeddings if PCA fails
|
| 115 |
|
| 116 |
# Store Data in ChromaDB
|
| 117 |
def store_data(texts, image_paths):
|
| 118 |
for i, text in enumerate(texts):
|
| 119 |
+
if text:
|
| 120 |
+
collection.add(ids=[f"text_{i}"], embeddings=[get_text_embedding(text)], documents=[text])
|
| 121 |
|
| 122 |
+
all_embeddings = [get_image_embedding(img_path) for img_path in image_paths if get_image_embedding(img_path) is not None]
|
| 123 |
+
if all_embeddings:
|
| 124 |
+
all_embeddings = np.array(all_embeddings)
|
| 125 |
+
transformed_embeddings = reduce_embedding_dim(all_embeddings) if all_embeddings.shape[0] > 1 else all_embeddings.tolist()
|
| 126 |
for j, img_path in enumerate(image_paths):
|
| 127 |
+
collection.add(ids=[f"image_{j}"], embeddings=[transformed_embeddings[j]], documents=[img_path])
|
| 128 |
|
| 129 |
print("Data stored successfully!")
|
| 130 |
|
| 131 |
+
# Process and Store from Files
|
| 132 |
def process_and_store(pdf_path=None, pptx_path=None):
|
| 133 |
texts, images = [], []
|
| 134 |
if pdf_path:
|
| 135 |
+
pdf_text = extract_text_from_pdf(pdf_path)
|
| 136 |
+
if pdf_text:
|
| 137 |
+
texts.append(pdf_text)
|
| 138 |
images.extend(extract_images_from_pdf(pdf_path))
|
| 139 |
if pptx_path:
|
| 140 |
+
pptx_text = extract_text_from_pptx(pptx_path)
|
| 141 |
+
if pptx_text:
|
| 142 |
+
texts.append(pptx_text)
|
| 143 |
images.extend(extract_images_from_pptx(pptx_path))
|
| 144 |
store_data(texts, images)
|
| 145 |
|
| 146 |
+
# Run Data Processing
|
| 147 |
process_and_store(pdf_path=pdf_file, pptx_path=pptx_file)
|
| 148 |
|
| 149 |
+
# FastAPI Endpoints
|
| 150 |
@app.get("/")
|
| 151 |
def greet_json():
|
| 152 |
return {"Hello": "World!"}
|
|
|
|
| 157 |
|
| 158 |
@app.get("/search/")
|
| 159 |
def search(query: str):
|
| 160 |
+
try:
|
| 161 |
+
query_embedding = get_text_embedding(query)
|
| 162 |
+
results = collection.query(query_embeddings=[query_embedding], n_results=5)
|
| 163 |
+
return {"results": results.get("documents", [])}
|
| 164 |
+
except Exception as e:
|
| 165 |
+
return {"error": str(e)}
|