Spaces:
Build error
Build error
Update app.py
Browse files
app.py
CHANGED
|
@@ -12,7 +12,6 @@ import torch
|
|
| 12 |
from torch.cuda.amp import autocast
|
| 13 |
from transformers import AutoModel, AutoTokenizer
|
| 14 |
from sentence_transformers import SentenceTransformer
|
| 15 |
-
|
| 16 |
from langchain.docstore.document import Document
|
| 17 |
import chromadb
|
| 18 |
from chromadb import Settings
|
|
@@ -63,6 +62,7 @@ class ProcessingResult:
|
|
| 63 |
processed_files: int = 0
|
| 64 |
processed_chunks: int = 0
|
| 65 |
|
|
|
|
| 66 |
# === Model and Tokenizer Loading ===
|
| 67 |
tokenizer = None
|
| 68 |
model = None
|
|
@@ -76,7 +76,7 @@ def initialize_model():
|
|
| 76 |
cache_dir=CACHE_DIR,
|
| 77 |
device_map=device,
|
| 78 |
torch_dtype=torch.float16 if device == "cuda" else torch.float32,
|
| 79 |
-
|
| 80 |
)
|
| 81 |
tokenizer = AutoTokenizer.from_pretrained(EMBEDDING_MODEL_NAME, cache_dir=CACHE_DIR)
|
| 82 |
logger.info(f"Loaded model '{EMBEDDING_MODEL_NAME}' on '{device}'")
|
|
@@ -91,11 +91,11 @@ def get_model():
|
|
| 91 |
initialize_model()
|
| 92 |
return model
|
| 93 |
|
|
|
|
| 94 |
# === Vector Database Initialization ===
|
| 95 |
persistent_client = chromadb.PersistentClient(path=PERSISTENT_PATH, settings=Settings(allow_reset=True))
|
| 96 |
vector_db = None
|
| 97 |
|
| 98 |
-
|
| 99 |
def get_vector_db():
|
| 100 |
global vector_db
|
| 101 |
if vector_db is None:
|
|
@@ -114,9 +114,10 @@ def get_vector_db():
|
|
| 114 |
def chunk_text(text, chunk_size=CHUNK_SIZE, overlap=50):
|
| 115 |
chunks = []
|
| 116 |
for i in range(0, len(text), chunk_size - overlap):
|
| 117 |
-
|
| 118 |
return chunks
|
| 119 |
|
|
|
|
| 120 |
def handle_file_processing(files, chunk_size=CHUNK_SIZE) -> ProcessingResult:
|
| 121 |
try:
|
| 122 |
start_time = datetime.now()
|
|
@@ -142,19 +143,19 @@ def handle_file_processing(files, chunk_size=CHUNK_SIZE) -> ProcessingResult:
|
|
| 142 |
docs = [Document(page_content=chunk) for chunk in chunks]
|
| 143 |
all_docs.extend(docs)
|
| 144 |
processed_chunks += len(docs)
|
| 145 |
-
|
| 146 |
db = get_vector_db()
|
| 147 |
embeddings = []
|
| 148 |
for i in range(0,len(all_docs), BATCH_SIZE):
|
| 149 |
batch_docs = all_docs[i:i+BATCH_SIZE]
|
| 150 |
with autocast(enabled=USE_GPU):
|
| 151 |
-
|
| 152 |
db.add(
|
| 153 |
documents=[doc.page_content for doc in all_docs],
|
| 154 |
embeddings=embeddings,
|
| 155 |
ids = [f"{doc.page_content[:20]}_{i}" for i, doc in enumerate(all_docs)]
|
| 156 |
-
|
| 157 |
-
|
| 158 |
end_time = datetime.now()
|
| 159 |
processing_time = (end_time - start_time).total_seconds()
|
| 160 |
logger.info(
|
|
@@ -171,6 +172,7 @@ def handle_file_processing(files, chunk_size=CHUNK_SIZE) -> ProcessingResult:
|
|
| 171 |
processed_files=len(files),
|
| 172 |
processed_chunks=processed_chunks
|
| 173 |
)
|
|
|
|
| 174 |
except FileProcessingError as e:
|
| 175 |
logger.error(str(e))
|
| 176 |
return ProcessingResult(success=False, message=str(e), error="FILE_PROCESSING_ERROR")
|
|
@@ -178,12 +180,12 @@ def handle_file_processing(files, chunk_size=CHUNK_SIZE) -> ProcessingResult:
|
|
| 178 |
logger.error(f"Unexpected error: {str(e)}\n{traceback.format_exc()}")
|
| 179 |
return ProcessingResult(success=False, message="Unexpected error", error="UNEXPECTED_ERROR")
|
| 180 |
|
| 181 |
-
|
| 182 |
def handle_gpu_operation(func):
|
| 183 |
try:
|
| 184 |
start_time = datetime.now()
|
| 185 |
with autocast(enabled = USE_GPU):
|
| 186 |
-
|
|
|
|
| 187 |
end_time = datetime.now()
|
| 188 |
duration = (end_time - start_time).total_seconds()
|
| 189 |
logger.info(f"GPU operation completed in {duration:.2f}s")
|
|
@@ -203,7 +205,7 @@ def handle_gpu_operation(func):
|
|
| 203 |
else:
|
| 204 |
logger.error(f"Unexpected GPU error: {str(e)}")
|
| 205 |
raise
|
| 206 |
-
|
| 207 |
|
| 208 |
def query_database(query, k=5):
|
| 209 |
db = get_vector_db()
|
|
@@ -214,6 +216,7 @@ def query_database(query, k=5):
|
|
| 214 |
return "\n\n".join(
|
| 215 |
[f"Chunk {i+1}:\n{r}" for i, r in enumerate(results['documents'][0])]
|
| 216 |
)
|
|
|
|
| 217 |
def cleanup_resources():
|
| 218 |
global model, vector_db
|
| 219 |
if model:
|
|
@@ -221,14 +224,13 @@ def cleanup_resources():
|
|
| 221 |
del model
|
| 222 |
model = None
|
| 223 |
if vector_db:
|
| 224 |
-
|
| 225 |
-
|
| 226 |
if USE_GPU:
|
| 227 |
torch.cuda.empty_cache()
|
| 228 |
gc.collect()
|
| 229 |
logger.info("GPU memory has been cleaned up")
|
| 230 |
|
| 231 |
-
|
| 232 |
def create_gradio_app():
|
| 233 |
with gr.Blocks() as demo:
|
| 234 |
gr.Markdown("## Document Analysis System")
|
|
@@ -239,17 +241,17 @@ def create_gradio_app():
|
|
| 239 |
with gr.Row():
|
| 240 |
file_input = gr.File(
|
| 241 |
label="Upload Documents",
|
| 242 |
-
|
| 243 |
-
|
| 244 |
)
|
| 245 |
chunk_size = gr.Slider(
|
| 246 |
minimum=100,
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
| 250 |
step=50
|
| 251 |
-
|
| 252 |
-
|
| 253 |
process_button = gr.Button("Process Files")
|
| 254 |
output_status = gr.Textbox(label="Status")
|
| 255 |
|
|
@@ -260,15 +262,15 @@ def create_gradio_app():
|
|
| 260 |
result.message,
|
| 261 |
"" if result.success else result.message,
|
| 262 |
not result.success
|
| 263 |
-
|
| 264 |
except Exception as e:
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
process_button.click(
|
| 270 |
safe_process_files,
|
| 271 |
-
|
| 272 |
outputs=[output_status, error_box, error_box]
|
| 273 |
)
|
| 274 |
|
|
@@ -277,11 +279,11 @@ def create_gradio_app():
|
|
| 277 |
num_results = gr.Slider(1, 10, 5, label="Number of results")
|
| 278 |
search_button = gr.Button("Search")
|
| 279 |
results_output = gr.Textbox(label="Search Results", lines=10)
|
| 280 |
-
|
| 281 |
def safe_query_database(query, num_results):
|
| 282 |
try:
|
| 283 |
results = handle_gpu_operation(
|
| 284 |
-
|
| 285 |
)
|
| 286 |
return results, "", False
|
| 287 |
except GPUQuotaExceededError as e:
|
|
@@ -289,44 +291,44 @@ def create_gradio_app():
|
|
| 289 |
logger.error(error_msg)
|
| 290 |
return "", error_msg, True
|
| 291 |
except Exception as e:
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
|
| 295 |
|
| 296 |
search_button.click(
|
| 297 |
safe_query_database,
|
| 298 |
inputs=[query_input, num_results],
|
| 299 |
outputs=[results_output, error_box, error_box]
|
| 300 |
)
|
|
|
|
| 301 |
with gr.Tab("Inspect Embeddings"):
|
| 302 |
embed_input = gr.Textbox(label="Enter Text for Embedding")
|
| 303 |
embed_button = gr.Button("Generate Embedding")
|
| 304 |
embed_output = gr.Textbox(label="Embedding Vector", lines=5)
|
| 305 |
|
| 306 |
def safe_generate_embedding(text):
|
| 307 |
-
|
| 308 |
-
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
|
| 313 |
error_msg = str(e)
|
| 314 |
logger.error(error_msg)
|
| 315 |
return "", error_msg, True
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
|
| 321 |
embed_button.click(
|
| 322 |
-
|
| 323 |
-
|
| 324 |
outputs=[embed_output, error_box, error_box]
|
| 325 |
-
|
| 326 |
-
|
| 327 |
demo.add_event_listener("shutdown", cleanup_resources)
|
| 328 |
return demo
|
|
|
|
| 329 |
if __name__ == "__main__":
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
|
|
|
|
| 12 |
from torch.cuda.amp import autocast
|
| 13 |
from transformers import AutoModel, AutoTokenizer
|
| 14 |
from sentence_transformers import SentenceTransformer
|
|
|
|
| 15 |
from langchain.docstore.document import Document
|
| 16 |
import chromadb
|
| 17 |
from chromadb import Settings
|
|
|
|
| 62 |
processed_files: int = 0
|
| 63 |
processed_chunks: int = 0
|
| 64 |
|
| 65 |
+
|
| 66 |
# === Model and Tokenizer Loading ===
|
| 67 |
tokenizer = None
|
| 68 |
model = None
|
|
|
|
| 76 |
cache_dir=CACHE_DIR,
|
| 77 |
device_map=device,
|
| 78 |
torch_dtype=torch.float16 if device == "cuda" else torch.float32,
|
| 79 |
+
low_cpu_mem_usage=True
|
| 80 |
)
|
| 81 |
tokenizer = AutoTokenizer.from_pretrained(EMBEDDING_MODEL_NAME, cache_dir=CACHE_DIR)
|
| 82 |
logger.info(f"Loaded model '{EMBEDDING_MODEL_NAME}' on '{device}'")
|
|
|
|
| 91 |
initialize_model()
|
| 92 |
return model
|
| 93 |
|
| 94 |
+
|
| 95 |
# === Vector Database Initialization ===
|
| 96 |
persistent_client = chromadb.PersistentClient(path=PERSISTENT_PATH, settings=Settings(allow_reset=True))
|
| 97 |
vector_db = None
|
| 98 |
|
|
|
|
| 99 |
def get_vector_db():
|
| 100 |
global vector_db
|
| 101 |
if vector_db is None:
|
|
|
|
| 114 |
def chunk_text(text, chunk_size=CHUNK_SIZE, overlap=50):
|
| 115 |
chunks = []
|
| 116 |
for i in range(0, len(text), chunk_size - overlap):
|
| 117 |
+
chunks.append(text[i:min(len(text), i + chunk_size)])
|
| 118 |
return chunks
|
| 119 |
|
| 120 |
+
|
| 121 |
def handle_file_processing(files, chunk_size=CHUNK_SIZE) -> ProcessingResult:
|
| 122 |
try:
|
| 123 |
start_time = datetime.now()
|
|
|
|
| 143 |
docs = [Document(page_content=chunk) for chunk in chunks]
|
| 144 |
all_docs.extend(docs)
|
| 145 |
processed_chunks += len(docs)
|
| 146 |
+
|
| 147 |
db = get_vector_db()
|
| 148 |
embeddings = []
|
| 149 |
for i in range(0,len(all_docs), BATCH_SIZE):
|
| 150 |
batch_docs = all_docs[i:i+BATCH_SIZE]
|
| 151 |
with autocast(enabled=USE_GPU):
|
| 152 |
+
embeddings.extend(get_model().encode([doc.page_content for doc in batch_docs]).tolist())
|
| 153 |
db.add(
|
| 154 |
documents=[doc.page_content for doc in all_docs],
|
| 155 |
embeddings=embeddings,
|
| 156 |
ids = [f"{doc.page_content[:20]}_{i}" for i, doc in enumerate(all_docs)]
|
| 157 |
+
)
|
| 158 |
+
|
| 159 |
end_time = datetime.now()
|
| 160 |
processing_time = (end_time - start_time).total_seconds()
|
| 161 |
logger.info(
|
|
|
|
| 172 |
processed_files=len(files),
|
| 173 |
processed_chunks=processed_chunks
|
| 174 |
)
|
| 175 |
+
|
| 176 |
except FileProcessingError as e:
|
| 177 |
logger.error(str(e))
|
| 178 |
return ProcessingResult(success=False, message=str(e), error="FILE_PROCESSING_ERROR")
|
|
|
|
| 180 |
logger.error(f"Unexpected error: {str(e)}\n{traceback.format_exc()}")
|
| 181 |
return ProcessingResult(success=False, message="Unexpected error", error="UNEXPECTED_ERROR")
|
| 182 |
|
|
|
|
| 183 |
def handle_gpu_operation(func):
|
| 184 |
try:
|
| 185 |
start_time = datetime.now()
|
| 186 |
with autocast(enabled = USE_GPU):
|
| 187 |
+
logger.info(f"Using GPU for operation: GPU Available: {USE_GPU}, Device: {device}")
|
| 188 |
+
result = func()
|
| 189 |
end_time = datetime.now()
|
| 190 |
duration = (end_time - start_time).total_seconds()
|
| 191 |
logger.info(f"GPU operation completed in {duration:.2f}s")
|
|
|
|
| 205 |
else:
|
| 206 |
logger.error(f"Unexpected GPU error: {str(e)}")
|
| 207 |
raise
|
| 208 |
+
|
| 209 |
|
| 210 |
def query_database(query, k=5):
|
| 211 |
db = get_vector_db()
|
|
|
|
| 216 |
return "\n\n".join(
|
| 217 |
[f"Chunk {i+1}:\n{r}" for i, r in enumerate(results['documents'][0])]
|
| 218 |
)
|
| 219 |
+
|
| 220 |
def cleanup_resources():
|
| 221 |
global model, vector_db
|
| 222 |
if model:
|
|
|
|
| 224 |
del model
|
| 225 |
model = None
|
| 226 |
if vector_db:
|
| 227 |
+
persistent_client.persist()
|
| 228 |
+
vector_db = None
|
| 229 |
if USE_GPU:
|
| 230 |
torch.cuda.empty_cache()
|
| 231 |
gc.collect()
|
| 232 |
logger.info("GPU memory has been cleaned up")
|
| 233 |
|
|
|
|
| 234 |
def create_gradio_app():
|
| 235 |
with gr.Blocks() as demo:
|
| 236 |
gr.Markdown("## Document Analysis System")
|
|
|
|
| 241 |
with gr.Row():
|
| 242 |
file_input = gr.File(
|
| 243 |
label="Upload Documents",
|
| 244 |
+
file_count="multiple",
|
| 245 |
+
file_types=[".txt"]
|
| 246 |
)
|
| 247 |
chunk_size = gr.Slider(
|
| 248 |
minimum=100,
|
| 249 |
+
maximum=1000,
|
| 250 |
+
value=500,
|
| 251 |
+
label="Chunk Size",
|
| 252 |
step=50
|
| 253 |
+
)
|
| 254 |
+
|
| 255 |
process_button = gr.Button("Process Files")
|
| 256 |
output_status = gr.Textbox(label="Status")
|
| 257 |
|
|
|
|
| 262 |
result.message,
|
| 263 |
"" if result.success else result.message,
|
| 264 |
not result.success
|
| 265 |
+
)
|
| 266 |
except Exception as e:
|
| 267 |
+
error_msg = f"Error processing files: {str(e)}"
|
| 268 |
+
logger.error(error_msg)
|
| 269 |
+
return "", error_msg, True
|
| 270 |
+
|
| 271 |
process_button.click(
|
| 272 |
safe_process_files,
|
| 273 |
+
inputs=[file_input, chunk_size],
|
| 274 |
outputs=[output_status, error_box, error_box]
|
| 275 |
)
|
| 276 |
|
|
|
|
| 279 |
num_results = gr.Slider(1, 10, 5, label="Number of results")
|
| 280 |
search_button = gr.Button("Search")
|
| 281 |
results_output = gr.Textbox(label="Search Results", lines=10)
|
| 282 |
+
|
| 283 |
def safe_query_database(query, num_results):
|
| 284 |
try:
|
| 285 |
results = handle_gpu_operation(
|
| 286 |
+
lambda: query_database(query, k=num_results)
|
| 287 |
)
|
| 288 |
return results, "", False
|
| 289 |
except GPUQuotaExceededError as e:
|
|
|
|
| 291 |
logger.error(error_msg)
|
| 292 |
return "", error_msg, True
|
| 293 |
except Exception as e:
|
| 294 |
+
error_msg = f"Query error: {str(e)}"
|
| 295 |
+
logger.error(error_msg)
|
| 296 |
+
return "", error_msg, True
|
| 297 |
|
| 298 |
search_button.click(
|
| 299 |
safe_query_database,
|
| 300 |
inputs=[query_input, num_results],
|
| 301 |
outputs=[results_output, error_box, error_box]
|
| 302 |
)
|
| 303 |
+
|
| 304 |
with gr.Tab("Inspect Embeddings"):
|
| 305 |
embed_input = gr.Textbox(label="Enter Text for Embedding")
|
| 306 |
embed_button = gr.Button("Generate Embedding")
|
| 307 |
embed_output = gr.Textbox(label="Embedding Vector", lines=5)
|
| 308 |
|
| 309 |
def safe_generate_embedding(text):
|
| 310 |
+
try:
|
| 311 |
+
embedding = handle_gpu_operation(
|
| 312 |
+
lambda: get_model().encode(text).tolist()
|
| 313 |
+
)
|
| 314 |
+
return embedding, "", False
|
| 315 |
+
except GPUQuotaExceededError as e:
|
| 316 |
error_msg = str(e)
|
| 317 |
logger.error(error_msg)
|
| 318 |
return "", error_msg, True
|
| 319 |
+
except Exception as e:
|
| 320 |
+
error_msg = f"Error generating embedding: {str(e)}"
|
| 321 |
+
logger.error(error_msg)
|
| 322 |
+
return "", error_msg, True
|
|
|
|
| 323 |
embed_button.click(
|
| 324 |
+
safe_generate_embedding,
|
| 325 |
+
inputs=[embed_input],
|
| 326 |
outputs=[embed_output, error_box, error_box]
|
| 327 |
+
)
|
|
|
|
| 328 |
demo.add_event_listener("shutdown", cleanup_resources)
|
| 329 |
return demo
|
| 330 |
+
|
| 331 |
if __name__ == "__main__":
|
| 332 |
+
initialize_model()
|
| 333 |
+
demo_app = create_gradio_app()
|
| 334 |
+
demo_app.launch(server_name = "0.0.0.0")
|