Redmind commited on
Commit
dc53a20
·
verified ·
1 Parent(s): 6bbcff4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +106 -62
app.py CHANGED
@@ -1,10 +1,10 @@
1
  from fastapi import FastAPI
2
  import os
3
- import pymupdf
4
- from pptx import Presentation # PowerPoint
5
- from sentence_transformers import SentenceTransformer # Text embeddings
6
  import torch
7
- from transformers import CLIPProcessor, CLIPModel # Image embeddings
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", metadata={"hnsw:space": "cosine"})
18
 
 
19
  pdf_file = "Sutures and Suturing techniques.pdf"
20
  pptx_file = "impalnt 1.pptx"
21
 
22
- # Initialize models
23
- text_model = SentenceTransformer('sentence-transformers/paraphrase-MiniLM-L3-v2') # 384-dim text model
24
- clip_model = CLIPModel.from_pretrained("openai/clip-vit-base-patch32")
25
- clip_processor = CLIPProcessor.from_pretrained("openai/clip-vit-base-patch32")
26
 
 
27
  IMAGE_FOLDER = "/data/extracted_images"
28
  os.makedirs(IMAGE_FOLDER, exist_ok=True)
29
 
30
- # Extract text from PDF
31
  def extract_text_from_pdf(pdf_path):
32
- return " ".join([page.get_text() for page in pymupdf.open(pdf_path)]).strip()
33
-
34
- # Extract text from PowerPoint
 
 
 
 
 
 
35
  def extract_text_from_pptx(pptx_path):
36
- return " ".join([shape.text for slide in Presentation(pptx_path).slides for shape in slide.shapes if hasattr(shape, "text")]).strip()
37
-
38
- # Extract images from PDF
 
 
 
 
 
 
 
 
39
  def extract_images_from_pdf(pdf_path):
40
- images = []
41
- doc = pymupdf.open(pdf_path)
42
- for i, page in enumerate(doc):
43
- for img_index, img in enumerate(page.get_images(full=True)):
44
- xref = img[0]
45
- image = doc.extract_image(xref)
46
- img_path = f"{IMAGE_FOLDER}/pdf_image_{i}_{img_index}.{image['ext']}"
47
- with open(img_path, "wb") as f:
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(shape.image.blob)
62
  images.append(img_path)
63
- return images
 
 
 
64
 
65
- # Convert text to embeddings
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66
  def get_text_embedding(text):
67
- return text_model.encode(text).tolist() # 384-dim output
68
 
69
- # Extract image embeddings
70
  def get_image_embedding(image_path):
71
- image = Image.open(image_path)
72
- inputs = clip_processor(images=image, return_tensors="pt")
73
- with torch.no_grad():
74
- image_embedding = clip_model.get_image_features(**inputs).numpy().flatten() # 512-dim output
75
- return image_embedding.tolist()
76
-
77
- # Reduce image embedding dimensionality (512 → 384)
 
 
 
 
78
  def reduce_embedding_dim(embeddings):
79
- pca = PCA(n_components=384)
80
- return pca.fit_transform(np.array(embeddings))
 
 
 
 
 
 
81
 
82
  # Store Data in ChromaDB
83
  def store_data(texts, image_paths):
84
  for i, text in enumerate(texts):
85
- collection.add(ids=[f"text_{i}"], embeddings=[get_text_embedding(text)], documents=[text])
 
86
 
87
- if image_paths:
88
- all_embeddings = np.array([get_image_embedding(img_path) for img_path in image_paths])
89
- transformed_embeddings = reduce_embedding_dim(all_embeddings) if all_embeddings.shape[1] > 384 else all_embeddings
90
-
91
  for j, img_path in enumerate(image_paths):
92
- collection.add(ids=[f"image_{j}"], embeddings=[transformed_embeddings[j].tolist()], documents=[img_path])
93
 
94
  print("Data stored successfully!")
95
 
96
- # Process and store from files
97
  def process_and_store(pdf_path=None, pptx_path=None):
98
  texts, images = [], []
99
  if pdf_path:
100
- texts.append(extract_text_from_pdf(pdf_path))
 
 
101
  images.extend(extract_images_from_pdf(pdf_path))
102
  if pptx_path:
103
- texts.append(extract_text_from_pptx(pptx_path))
 
 
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
- query_embedding = get_text_embedding(query)
120
- results = collection.query(query_embeddings=[query_embedding], n_results=5)
121
- return {"results": results["documents"][0] if results["documents"] else []} # Fix empty results handling
 
 
 
 
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)}