gmustafa413 commited on
Commit
83833a8
·
verified ·
1 Parent(s): 321953b

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +190 -0
app.py ADDED
@@ -0,0 +1,190 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import fitz
3
+ import numpy as np
4
+ import requests
5
+ import faiss
6
+ import re
7
+ import json
8
+ import pandas as pd
9
+ from docx import Document
10
+ from pptx import Presentation
11
+ from sentence_transformers import SentenceTransformer
12
+ from concurrent.futures import ThreadPoolExecutor
13
+
14
+ # Configuration
15
+ GROQ_API_KEY = "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"
16
+ MODEL_NAME = "all-MiniLM-L6-v2"
17
+ CHUNK_SIZE = 512
18
+ MAX_TOKENS = 4096
19
+ MODEL = SentenceTransformer(MODEL_NAME)
20
+ WORKERS = 8
21
+
22
+ class DocumentProcessor:
23
+ def __init__(self):
24
+ self.index = faiss.IndexFlatIP(MODEL.get_sentence_embedding_dimension())
25
+ self.chunks = []
26
+ self.processor_pool = ThreadPoolExecutor(max_workers=WORKERS)
27
+
28
+ def extract_text_from_pptx(self, file_path):
29
+ try:
30
+ prs = Presentation(file_path)
31
+ return " ".join([shape.text for slide in prs.slides for shape in slide.shapes if hasattr(shape, "text")])
32
+ except Exception as e:
33
+ print(f"PPTX Error: {str(e)}")
34
+ return ""
35
+
36
+ def extract_text_from_xls_csv(self, file_path):
37
+ try:
38
+ if file_path.endswith(('.xls', '.xlsx')):
39
+ df = pd.read_excel(file_path)
40
+ else:
41
+ df = pd.read_csv(file_path)
42
+ return " ".join(df.astype(str).values.flatten())
43
+ except Exception as e:
44
+ print(f"Spreadsheet Error: {str(e)}")
45
+ return ""
46
+
47
+ def extract_text_from_pdf(self, file_path):
48
+ try:
49
+ doc = fitz.open(file_path)
50
+ return " ".join(page.get_text("text", flags=fitz.TEXT_PRESERVE_WHITESPACE) for page in doc)
51
+ except Exception as e:
52
+ print(f"PDF Error: {str(e)}")
53
+ return ""
54
+
55
+ def process_file(self, file):
56
+ try:
57
+ file_path = file.name
58
+ if file_path.endswith('.pdf'):
59
+ text = self.extract_text_from_pdf(file_path)
60
+ elif file_path.endswith('.docx'):
61
+ text = " ".join(p.text for p in Document(file_path).paragraphs)
62
+ elif file_path.endswith('.txt'):
63
+ with open(file_path, 'r', encoding='utf-8') as f:
64
+ text = f.read()
65
+ elif file_path.endswith('.pptx'):
66
+ text = self.extract_text_from_pptx(file_path)
67
+ elif file_path.endswith(('.xls', '.xlsx', '.csv')):
68
+ text = self.extract_text_from_xls_csv(file_path)
69
+ else:
70
+ return ""
71
+ return re.sub(r'\s+', ' ', text).strip()
72
+ except Exception as e:
73
+ print(f"Processing Error: {str(e)}")
74
+ return ""
75
+
76
+ def semantic_chunking(self, text):
77
+ words = re.findall(r'\S+\s*', text)
78
+ chunks = [''.join(words[i:i+CHUNK_SIZE//2]) for i in range(0, len(words), CHUNK_SIZE//2)]
79
+ return chunks[:1000]
80
+
81
+ def process_documents(self, files):
82
+ self.chunks = []
83
+ if not files:
84
+ return "No files uploaded!"
85
+
86
+ texts = list(self.processor_pool.map(self.process_file, files))
87
+ with ThreadPoolExecutor(max_workers=WORKERS) as executor:
88
+ chunk_lists = list(executor.map(self.semantic_chunking, texts))
89
+
90
+ all_chunks = [chunk for chunk_list in chunk_lists for chunk in chunk_list]
91
+ if not all_chunks:
92
+ return "Error: No chunks generated from documents"
93
+
94
+ try:
95
+ embeddings = MODEL.encode(
96
+ all_chunks,
97
+ batch_size=512,
98
+ convert_to_tensor=True,
99
+ show_progress_bar=False
100
+ ).cpu().numpy().astype('float32')
101
+
102
+ self.index.reset()
103
+ self.index.add(embeddings)
104
+ self.chunks = all_chunks
105
+ return f"Successfully Processed {len(all_chunks)} chunks from {len(files)} files"
106
+ except Exception as e:
107
+ print(f"Embedding Error: {str(e)}")
108
+ return f"Error: {str(e)}"
109
+
110
+ def query(self, question):
111
+ if not self.chunks:
112
+ return "Please process documents first", False
113
+
114
+ try:
115
+ question_embedding = MODEL.encode([question], convert_to_tensor=True).cpu().numpy().astype('float32')
116
+ _, indices = self.index.search(question_embedding, 3)
117
+ context = "\n".join([self.chunks[i] for i in indices[0] if i < len(self.chunks)])
118
+
119
+ response = requests.post(
120
+ "https://api.groq.com/openai/v1/chat/completions",
121
+ headers={"Authorization": f"Bearer {GROQ_API_KEY}"},
122
+ json={
123
+ "messages": [{
124
+ "role": "user",
125
+ "content": f"Answer concisely: {question}\nContext: {context}"
126
+ }],
127
+ "model": "mixtral-8x7b-32768",
128
+ "temperature": 0.3,
129
+ "max_tokens": MAX_TOKENS,
130
+ "stream": True
131
+ },
132
+ timeout=20
133
+ )
134
+
135
+ if response.status_code != 200:
136
+ return f"API Error: {response.text}", False
137
+
138
+ full_answer = []
139
+ for chunk in response.iter_lines():
140
+ if chunk:
141
+ try:
142
+ decoded = chunk.decode('utf-8').strip()
143
+ if decoded.startswith('data:'):
144
+ data = json.loads(decoded[5:])
145
+ if content := data.get('choices', [{}])[0].get('delta', {}).get('content', ''):
146
+ full_answer.append(content)
147
+ except:
148
+ continue
149
+
150
+ return ''.join(full_answer), True
151
+ except Exception as e:
152
+ print(f"Query Error: {str(e)}")
153
+ return f"Error: {str(e)}", False
154
+
155
+ processor = DocumentProcessor()
156
+
157
+ def ask_question(question, chat_history):
158
+ if not question.strip():
159
+ return chat_history
160
+ answer, success = processor.query(question)
161
+ return chat_history + [(question, answer if success else f"Error: {answer}")]
162
+
163
+ with gr.Blocks(title="RAG System", css=".footer {display: none !important}") as app:
164
+ gr.Markdown("## Multi-Format-Reader")
165
+ with gr.Row():
166
+ files = gr.File(file_count="multiple",
167
+ file_types=[".pdf", ".docx", ".txt", ".pptx", ".xls", ".xlsx", ".csv"],
168
+ label="Upload Documents")
169
+ process_btn = gr.Button("Process", variant="primary")
170
+ status = gr.Textbox(label="Processing Status", interactive=False)
171
+ chatbot = gr.Chatbot(height=500, label="Chat History")
172
+ with gr.Row():
173
+ question = gr.Textbox(label="Your Query", placeholder="Enter your question...", max_lines=3)
174
+ ask_btn = gr.Button("Ask", variant="primary")
175
+ clear_btn = gr.Button("Clear Chat")
176
+
177
+ process_btn.click(
178
+ processor.process_documents,
179
+ files,
180
+ status
181
+ )
182
+ ask_btn.click(
183
+ ask_question,
184
+ [question, chatbot],
185
+ chatbot
186
+ ).then(lambda: "", None, question)
187
+ clear_btn.click(lambda: [], None, chatbot)
188
+
189
+ app.launch()
190
+