gmustafa413 commited on
Commit
1970d42
·
verified ·
1 Parent(s): 86aeb78

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +226 -0
app.py ADDED
@@ -0,0 +1,226 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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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" # 🔑 REPLACE WITH YOUR ACTUAL KEY
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
+ print(f"Processing: {file_path}")
59
+
60
+ if file_path.endswith('.pdf'):
61
+ text = self.extract_text_from_pdf(file_path)
62
+ elif file_path.endswith('.docx'):
63
+ text = " ".join(p.text for p in Document(file_path).paragraphs)
64
+ elif file_path.endswith('.txt'):
65
+ with open(file_path, 'r', encoding='utf-8') as f:
66
+ text = f.read()
67
+ elif file_path.endswith('.pptx'):
68
+ text = self.extract_text_from_pptx(file_path)
69
+ elif file_path.endswith(('.xls', '.xlsx', '.csv')):
70
+ text = self.extract_text_from_xls_csv(file_path)
71
+ else:
72
+ return ""
73
+
74
+ clean_text = re.sub(r'\s+', ' ', text).strip()
75
+ print(f"Extracted {len(clean_text)} characters from {file_path}")
76
+ return clean_text
77
+ except Exception as e:
78
+ print(f"Processing Error: {str(e)}")
79
+ return ""
80
+
81
+ def semantic_chunking(self, text):
82
+ words = re.findall(r'\S+\s*', text)
83
+ chunks = [''.join(words[i:i+CHUNK_SIZE//2]) for i in range(0, len(words), CHUNK_SIZE//2)]
84
+ return chunks[:1000]
85
+
86
+ def process_documents(self, files):
87
+ self.chunks = []
88
+ if not files:
89
+ return "No files uploaded!"
90
+
91
+ print("\n" + "="*40 + " PROCESSING DOCUMENTS " + "="*40)
92
+ texts = list(self.processor_pool.map(self.process_file, files))
93
+
94
+ with ThreadPoolExecutor(max_workers=WORKERS) as executor:
95
+ chunk_lists = list(executor.map(self.semantic_chunking, texts))
96
+
97
+ all_chunks = [chunk for chunk_list in chunk_lists for chunk in chunk_list]
98
+ print(f"Total chunks generated: {len(all_chunks)}")
99
+
100
+ if not all_chunks:
101
+ return "Error: No chunks generated from documents"
102
+
103
+ try:
104
+ embeddings = MODEL.encode(
105
+ all_chunks,
106
+ batch_size=512,
107
+ convert_to_tensor=True,
108
+ show_progress_bar=False
109
+ ).cpu().numpy().astype('float32')
110
+
111
+ self.index.reset()
112
+ self.index.add(embeddings)
113
+ self.chunks = all_chunks
114
+ return f"Processed {len(all_chunks)} chunks from {len(files)} files"
115
+ except Exception as e:
116
+ print(f"Embedding Error: {str(e)}")
117
+ return f"Error: {str(e)}"
118
+
119
+ def query(self, question):
120
+ if not self.chunks:
121
+ return "Please process documents first", False
122
+
123
+ try:
124
+ print("\n" + "="*40 + " QUERY PROCESSING " + "="*40)
125
+ print(f"Question: {question}")
126
+
127
+ question_embedding = MODEL.encode([question], convert_to_tensor=True).cpu().numpy().astype('float32')
128
+ _, indices = self.index.search(question_embedding, 3)
129
+ print(f"Top indices: {indices}")
130
+
131
+ context = "\n".join([self.chunks[i] for i in indices[0] if i < len(self.chunks)])
132
+ print(f"Context length: {len(context)} characters")
133
+
134
+ headers = {
135
+ "Authorization": f"Bearer {GROQ_API_KEY}",
136
+ "Content-Type": "application/json"
137
+ }
138
+
139
+ payload = {
140
+ "messages": [{
141
+ "role": "user",
142
+ "content": f"Answer concisely: {question}\nContext: {context}"
143
+ }],
144
+ "model": "mixtral-8x7b-32768",
145
+ "temperature": 0.3,
146
+ "max_tokens": MAX_TOKENS,
147
+ "stream": True
148
+ }
149
+
150
+ response = requests.post(
151
+ "https://api.groq.com/openai/v1/chat/completions",
152
+ headers=headers,
153
+ json=payload,
154
+ timeout=20
155
+ )
156
+
157
+ print(f"API Status Code: {response.status_code}")
158
+
159
+ if response.status_code != 200:
160
+ return f"API Error: {response.text}", False
161
+
162
+ full_answer = []
163
+ for chunk in response.iter_lines():
164
+ if chunk:
165
+ try:
166
+ decoded = chunk.decode('utf-8').strip()
167
+ if decoded.startswith('data:'):
168
+ data = json.loads(decoded[5:])
169
+ if content := data.get('choices', [{}])[0].get('delta', {}).get('content', ''):
170
+ full_answer.append(content)
171
+ except Exception as e:
172
+ print(f"Chunk Error: {str(e)}")
173
+ continue
174
+
175
+ final_answer = ''.join(full_answer)
176
+ print(f"Final Answer: {final_answer}")
177
+ return final_answer, True
178
+
179
+ except Exception as e:
180
+ print(f"Query Error: {str(e)}")
181
+ return f"Error: {str(e)}", False
182
+
183
+ processor = DocumentProcessor()
184
+
185
+ def ask_question(question, chat_history):
186
+ if not question.strip():
187
+ return chat_history + [("", "Please enter a valid question")]
188
+
189
+ answer, success = processor.query(question)
190
+ return chat_history + [(question, answer)]
191
+
192
+ with gr.Blocks(title="System") as app:
193
+ gr.Markdown("## 🚀 Multi-Format-Reader ChatBot")
194
+ with gr.Row():
195
+ files = gr.File(file_count="multiple",
196
+ file_types=[".pdf", ".docx", ".txt", ".pptx", ".xls", ".xlsx", ".csv"],
197
+ label="Upload Documents")
198
+ process_btn = gr.Button("Process", variant="primary")
199
+ status = gr.Textbox(label="Processing Status", interactive=False)
200
+ chatbot = gr.Chatbot(height=500, label="Chat History")
201
+ with gr.Row():
202
+ question = gr.Textbox(label="Your Query",
203
+ placeholder="Enter your question...",
204
+ max_lines=3)
205
+ ask_btn = gr.Button("Ask", variant="primary")
206
+ clear_btn = gr.Button("Clear Chat")
207
+
208
+ process_btn.click(
209
+ fn=processor.process_documents,
210
+ inputs=files,
211
+ outputs=status
212
+ )
213
+
214
+ ask_btn.click(
215
+ fn=ask_question,
216
+ inputs=[question, chatbot],
217
+ outputs=chatbot
218
+ ).then(lambda: "", None, question)
219
+
220
+ clear_btn.click(
221
+ fn=lambda: [],
222
+ inputs=None,
223
+ outputs=chatbot
224
+ )
225
+
226
+ app.launch()