spagestic commited on
Commit
4ce49c4
Β·
1 Parent(s): 728418b
src/app.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Main entry point for the PDF Explainer app."""
2
+
3
+ import gradio as gr
4
+ from processors.pdf_processor import PDFProcessor
5
+ from ui_components.interface import build_interface
6
+ from dotenv import load_dotenv
7
+
8
+ load_dotenv()
9
+
10
+ def main():
11
+ pdf_processor = PDFProcessor()
12
+ demo = build_interface(pdf_processor.process_pdf)
13
+ return demo
14
+
15
+ if __name__ == "__main__":
16
+ demo = main()
17
+ demo.launch()
src/processors/audio_processor.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Audio generation functionality."""
2
+
3
+ import gradio as gr
4
+
5
+ class AudioProcessor:
6
+ """Handles audio generation operations."""
7
+ def generate_audio(self, explanation_text):
8
+ """Generate TTS audio for explanations."""
9
+ if not explanation_text or explanation_text.strip() == "":
10
+ raise gr.Error("No explanations available to convert to audio. Please generate explanations first.")
11
+ try:
12
+ from .generate_tts_audio import generate_tts_audio
13
+ clean_text = explanation_text.strip()
14
+ if len(clean_text) > 1000:
15
+ sentences = clean_text[:950].split('.')
16
+ if len(sentences) > 1:
17
+ clean_text = '.'.join(sentences[:-1]) + '.'
18
+ else:
19
+ clean_text = clean_text[:950]
20
+ clean_text += " [Text has been truncated for audio generation]"
21
+ audio_result = generate_tts_audio(clean_text, None)
22
+ return audio_result, gr.update(visible=True)
23
+ except Exception as e:
24
+ raise gr.Error(f"Error generating audio: {str(e)}")
src/processors/explanation_processor.py ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Explanation generation functionality."""
2
+
3
+ from pdf_text_extractor import PDFTextExtractor
4
+
5
+ class ExplanationProcessor:
6
+ """Handles explanation generation operations."""
7
+ def __init__(self):
8
+ self.extractor = PDFTextExtractor()
9
+
10
+ def generate_explanations(self, extracted_text):
11
+ """Generate explanations for extracted text."""
12
+ if not extracted_text or extracted_text.strip() == "":
13
+ return "No text available to explain. Please extract text from a PDF first."
14
+ try:
15
+ explanations = self.extractor.generate_explanations(extracted_text)
16
+ return explanations
17
+ except Exception as e:
18
+ return f"Error generating explanations: {str(e)}"
src/processors/generate_tts_audio.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ def generate_tts_audio(text_input: str, audio_prompt_input, progress=None):
2
+ import os
3
+ import requests
4
+ import tempfile
5
+ import soundfile as sf
6
+ import numpy as np
7
+ import gradio as gr
8
+
9
+ GENERATE_AUDIO_ENDPOINT = os.getenv("GENERATE_AUDIO_ENDPOINT", "YOUR-MODAL-ENDPOINT-URL/generate_audio")
10
+ GENERATE_WITH_FILE_ENDPOINT = os.getenv("GENERATE_WITH_FILE_ENDPOINT", "YOUR-MODAL-ENDPOINT-URL/generate_with_file")
11
+
12
+ if not text_input or len(text_input.strip()) == 0:
13
+ raise gr.Error("Please enter some text to synthesize.")
14
+
15
+ if progress: progress(0.1, desc="Preparing request...")
16
+
17
+ try:
18
+ if audio_prompt_input is None:
19
+ if progress: progress(0.3, desc="Sending request to API...")
20
+ payload = {"text": text_input}
21
+ response = requests.post(
22
+ GENERATE_AUDIO_ENDPOINT,
23
+ json=payload,
24
+ headers={"Content-Type": "application/json"},
25
+ timeout=120,
26
+ stream=True
27
+ )
28
+ if response.status_code != 200:
29
+ raise gr.Error(f"API Error: {response.status_code} - {response.text}")
30
+
31
+ if progress: progress(0.6, desc="Streaming audio response...")
32
+
33
+ # Get content length if available for progress tracking
34
+ content_length = response.headers.get('content-length')
35
+ if content_length:
36
+ content_length = int(content_length)
37
+
38
+ bytes_downloaded = 0
39
+ with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as temp_file:
40
+ for chunk in response.iter_content(chunk_size=8192):
41
+ if chunk:
42
+ temp_file.write(chunk)
43
+ bytes_downloaded += len(chunk)
44
+
45
+ # Update progress based on bytes downloaded
46
+ if content_length and progress:
47
+ download_progress = min(0.3, (bytes_downloaded / content_length) * 0.3)
48
+ progress(0.6 + download_progress, desc=f"Downloading audio... ({bytes_downloaded // 1024}KB)")
49
+ elif progress:
50
+ # If no content length, just show bytes downloaded
51
+ progress(0.6, desc=f"Downloading audio... ({bytes_downloaded // 1024}KB)")
52
+
53
+ temp_path = temp_file.name
54
+
55
+ if progress: progress(0.9, desc="Processing audio...")
56
+ audio_data, sample_rate = sf.read(temp_path)
57
+ os.unlink(temp_path)
58
+ if progress: progress(1.0, desc="Complete!")
59
+ return (sample_rate, audio_data)
60
+
61
+ else:
62
+ if progress: progress(0.3, desc="Preparing voice prompt...")
63
+ files = {'text': (None, text_input)}
64
+ with open(audio_prompt_input, 'rb') as f:
65
+ audio_content = f.read()
66
+ files['voice_prompt'] = ('voice_prompt.wav', audio_content, 'audio/wav')
67
+
68
+ if progress: progress(0.5, desc="Sending request with voice cloning...")
69
+ response = requests.post(
70
+ GENERATE_WITH_FILE_ENDPOINT,
71
+ files=files,
72
+ timeout=180,
73
+ stream=True
74
+ )
75
+ if response.status_code != 200:
76
+ raise gr.Error(f"API Error: {response.status_code} - {response.text}")
77
+
78
+ if progress: progress(0.8, desc="Streaming cloned voice response...")
79
+
80
+ # Get content length if available for progress tracking
81
+ content_length = response.headers.get('content-length')
82
+ if content_length:
83
+ content_length = int(content_length)
84
+
85
+ bytes_downloaded = 0
86
+ with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as temp_file:
87
+ for chunk in response.iter_content(chunk_size=8192):
88
+ if chunk:
89
+ temp_file.write(chunk)
90
+ bytes_downloaded += len(chunk)
91
+
92
+ # Update progress based on bytes downloaded for voice cloning
93
+ if content_length and progress:
94
+ download_progress = min(0.15, (bytes_downloaded / content_length) * 0.15)
95
+ progress(0.8 + download_progress, desc=f"Downloading cloned audio... ({bytes_downloaded // 1024}KB)")
96
+ elif progress:
97
+ progress(0.8, desc=f"Downloading cloned audio... ({bytes_downloaded // 1024}KB)")
98
+
99
+ temp_path = temp_file.name
100
+
101
+ audio_data, sample_rate = sf.read(temp_path)
102
+ os.unlink(temp_path)
103
+ if progress: progress(1.0, desc="Voice cloning complete!")
104
+ return (sample_rate, audio_data)
105
+
106
+ except requests.exceptions.Timeout:
107
+ raise gr.Error("Request timed out. The API might be under heavy load. Please try again.")
108
+ except requests.exceptions.ConnectionError:
109
+ raise gr.Error("Unable to connect to the API. Please check if the endpoint URL is correct.")
110
+ except Exception as e:
111
+ raise gr.Error(f"Error generating audio: {str(e)}")
src/processors/pdf_processor.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """PDF processing functionality."""
2
+
3
+ import gradio as gr
4
+ from .pdf_text_extractor import PDFTextExtractor
5
+
6
+
7
+ class PDFProcessor:
8
+ """Handles PDF processing operations."""
9
+
10
+ def __init__(self):
11
+ self.extractor = PDFTextExtractor()
12
+
13
+ def process_pdf(self, pdf_file):
14
+ """Process PDF and extract text, then explanations, then audio, updating UI at each step."""
15
+ if pdf_file is None:
16
+ yield "", "No PDF uploaded", "", None, gr.update(visible=False)
17
+ return
18
+
19
+ try:
20
+ # Step 1: Extract text
21
+ # Show "Extracting text..." message
22
+ yield "", gr.update(value="Extracting text..."), "", None, gr.update(visible=False)
23
+ extracted_text, status, images_data = self.extractor.extract_text_from_pdf(pdf_file)
24
+
25
+ if not extracted_text or extracted_text.strip() == "":
26
+ yield extracted_text, status, "No text available to explain.", None, gr.update(visible=False)
27
+ return
28
+
29
+ # Show extracted text immediately, explanations/audio loading
30
+ yield extracted_text, status, gr.update(value="Generating explanations..."), None, gr.update(visible=False)
31
+
32
+ # Step 2: Generate explanations
33
+ try:
34
+ explanations = self.extractor.generate_explanations(extracted_text)
35
+
36
+ # Show explanations immediately, update status for audio loading
37
+ yield extracted_text, gr.update(value="Generating audio..."), explanations, None, gr.update(visible=False)
38
+
39
+ # Step 3: Generate audio
40
+ try:
41
+ from .generate_tts_audio import generate_tts_audio
42
+
43
+ # Clean up the text for better TTS
44
+ clean_text = explanations.strip()
45
+
46
+ # Limit text length for TTS (assuming 1000 character limit)
47
+ if len(clean_text) > 1000:
48
+ sentences = clean_text[:950].split('.')
49
+ if len(sentences) > 1:
50
+ clean_text = '.'.join(sentences[:-1]) + '.'
51
+ else:
52
+ clean_text = clean_text[:950]
53
+ clean_text += " [Text has been truncated for audio generation]"
54
+
55
+ audio_result = generate_tts_audio(clean_text, None)
56
+
57
+ # Show everything, update status to complete
58
+ yield extracted_text, gr.update(value="All steps complete!"), explanations, audio_result, gr.update(visible=True)
59
+
60
+ except Exception as audio_error:
61
+ # Show explanations, update status with audio error
62
+ yield extracted_text, gr.update(value=f"Audio generation failed: {str(audio_error)}"), explanations, None, gr.update(visible=False)
63
+
64
+ except Exception as explanation_error:
65
+ # Show extracted text, but indicate explanation error
66
+ yield extracted_text, status, f"Error generating explanations: {str(explanation_error)}", None, gr.update(visible=False)
67
+
68
+ except Exception as e:
69
+ yield "", f"Error processing PDF: {str(e)}", "", None, gr.update(visible=False)
src/processors/pdf_text_extractor.py ADDED
@@ -0,0 +1,287 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import base64
2
+ import os
3
+ from typing import Optional, Tuple, List, Dict, Any
4
+ from mistralai import Mistral
5
+ from utils.text_explainer import TextExplainer
6
+
7
+ class PDFTextExtractor:
8
+ """PDF text extraction using Mistral AI OCR."""
9
+
10
+ def __init__(self):
11
+ """Initialize the PDF text extractor with Mistral AI client."""
12
+ self.api_key = os.environ.get("MISTRAL_API_KEY")
13
+ if not self.api_key:
14
+ raise ValueError("MISTRAL_API_KEY environment variable is required")
15
+ self.client = Mistral(api_key=self.api_key)
16
+ self.text_explainer = TextExplainer()
17
+
18
+ def encode_pdf(self, pdf_path: str) -> Optional[str]:
19
+ """
20
+ Encode the PDF file to base64.
21
+
22
+ Args:
23
+ pdf_path: Path to the PDF file
24
+
25
+ Returns:
26
+ Base64 encoded string or None if error
27
+ """
28
+ try:
29
+ with open(pdf_path, "rb") as pdf_file:
30
+ return base64.b64encode(pdf_file.read()).decode('utf-8')
31
+ except FileNotFoundError:
32
+ print(f"Error: The file {pdf_path} was not found.")
33
+ return None
34
+ except Exception as e:
35
+ print(f"Error encoding PDF: {e}")
36
+ return None
37
+
38
+ def extract_text_from_pdf(self, pdf_file) -> Tuple[str, str, List[Dict[str, Any]]]:
39
+ """
40
+ Extract text and images from uploaded PDF using Mistral AI OCR.
41
+
42
+ Args:
43
+ pdf_file: Gradio file object
44
+
45
+ Returns:
46
+ Tuple of (extracted_text, status_message, images_data)
47
+ """
48
+ if pdf_file is None:
49
+ return "", "Please upload a PDF file.", []
50
+
51
+ try:
52
+ # Get the file path from Gradio file object
53
+ pdf_path = pdf_file.name if hasattr(pdf_file, 'name') else pdf_file
54
+
55
+ # Encode PDF to base64
56
+ base64_pdf = self.encode_pdf(pdf_path)
57
+ if base64_pdf is None:
58
+ return "", "Failed to encode PDF file.", []
59
+
60
+ # Process with Mistral OCR
61
+ print(f"πŸ”„ Processing PDF with Mistral OCR...")
62
+ ocr_response = self.client.ocr.process(
63
+ model="mistral-ocr-latest",
64
+ document={
65
+ "type": "document_url",
66
+ "document_url": f"data:application/pdf;base64,{base64_pdf}"
67
+ },
68
+ include_image_base64=True
69
+ )
70
+
71
+ # Enhanced debugging and response parsing
72
+ print("πŸ” Analyzing OCR Response Structure...")
73
+ print(f" Type: {type(ocr_response)}")
74
+ print(f" String representation: {str(ocr_response)[:500]}...")
75
+
76
+ # Check if it's a simple object with attributes
77
+ if hasattr(ocr_response, '__dict__'):
78
+ print(f" Object attributes: {list(ocr_response.__dict__.keys())}")
79
+ for key, value in ocr_response.__dict__.items():
80
+ print(f" {key}: {type(value)} = {str(value)[:100]}...")
81
+
82
+ # Check if it has commonly expected attributes
83
+ common_attrs = ['text', 'content', 'result', 'data', 'output', 'extracted_text', 'ocr_text', 'choices', 'message']
84
+ for attr in common_attrs:
85
+ if hasattr(ocr_response, attr):
86
+ value = getattr(ocr_response, attr)
87
+ print(f" Has '{attr}': {type(value)} = {str(value)[:100]}...")
88
+
89
+ # Check if it's iterable but not a string
90
+ try:
91
+ if hasattr(ocr_response, '__iter__') and not isinstance(ocr_response, str):
92
+ print(f" Iterable with {len(list(ocr_response))} items")
93
+ for i, item in enumerate(ocr_response):
94
+ if i < 3: # Show first 3 items
95
+ print(f" Item {i}: {type(item)} = {str(item)[:100]}...")
96
+ except Exception as e:
97
+ print(f" Error checking iteration: {e}")
98
+
99
+ # Advanced text extraction with multiple strategies
100
+ extracted_text = ""
101
+ extraction_method = "none"
102
+ extracted_images = []
103
+
104
+ # Strategy 1: Mistral OCR specific - pages with markdown content and images
105
+ if hasattr(ocr_response, 'pages') and ocr_response.pages:
106
+ pages = ocr_response.pages
107
+ if isinstance(pages, list) and len(pages) > 0:
108
+ page_texts = []
109
+
110
+ for i, page in enumerate(pages):
111
+ # Extract text
112
+ if hasattr(page, 'markdown') and page.markdown:
113
+ page_texts.append(page.markdown)
114
+ print(f"βœ… Found text in page {i} markdown: {len(page.markdown)} characters")
115
+
116
+ # Extract images
117
+ if hasattr(page, 'images') and page.images:
118
+ for j, img in enumerate(page.images):
119
+ image_data = {
120
+ 'page': i,
121
+ 'image_id': f"img-{i}-{j}",
122
+ 'top_left_x': getattr(img, 'top_left_x', 0),
123
+ 'top_left_y': getattr(img, 'top_left_y', 0),
124
+ 'bottom_right_x': getattr(img, 'bottom_right_x', 0),
125
+ 'bottom_right_y': getattr(img, 'bottom_right_y', 0),
126
+ 'base64': getattr(img, 'image_base64', '')
127
+ }
128
+ extracted_images.append(image_data)
129
+ print(f"βœ… Found image in page {i}, image {j}: coordinates ({image_data['top_left_x']}, {image_data['top_left_y']}) to ({image_data['bottom_right_x']}, {image_data['bottom_right_y']})")
130
+
131
+ if page_texts:
132
+ extracted_text = "\n\n".join(page_texts)
133
+ extraction_method = f"pages_markdown_{len(page_texts)}_pages"
134
+
135
+ # Try to extract images from other response structures if no images found yet
136
+ if not extracted_images:
137
+ # Check if response has images attribute directly
138
+ if hasattr(ocr_response, 'images') and ocr_response.images:
139
+ for j, img in enumerate(ocr_response.images):
140
+ image_data = {
141
+ 'page': 0,
142
+ 'image_id': getattr(img, 'id', f"img-{j}"),
143
+ 'top_left_x': getattr(img, 'top_left_x', 0),
144
+ 'top_left_y': getattr(img, 'top_left_y', 0),
145
+ 'bottom_right_x': getattr(img, 'bottom_right_x', 0),
146
+ 'bottom_right_y': getattr(img, 'bottom_right_y', 0),
147
+ 'base64': getattr(img, 'image_base64', '')
148
+ }
149
+ extracted_images.append(image_data)
150
+ print(f"βœ… Found image {j}: coordinates ({image_data['top_left_x']}, {image_data['top_left_y']}) to ({image_data['bottom_right_x']}, {image_data['bottom_right_y']})")
151
+
152
+ # Continue with fallback strategies for text extraction
153
+ if not extracted_text:
154
+ # Strategy 2: Direct text attribute (fallback)
155
+ if hasattr(ocr_response, 'text') and ocr_response.text:
156
+ extracted_text = str(ocr_response.text)
157
+ extraction_method = "direct_text_attribute"
158
+
159
+ # Strategy 3: Content attribute (fallback)
160
+ elif hasattr(ocr_response, 'content') and ocr_response.content:
161
+ content = ocr_response.content
162
+ if isinstance(content, str):
163
+ extracted_text = content
164
+ extraction_method = "content_attribute_string"
165
+ elif hasattr(content, 'text'):
166
+ extracted_text = str(content.text)
167
+ extraction_method = "content_text_attribute"
168
+ else:
169
+ extracted_text = str(content)
170
+ extraction_method = "content_attribute_converted"
171
+
172
+ # Strategy 4: Result attribute (fallback)
173
+ elif hasattr(ocr_response, 'result'):
174
+ result = ocr_response.result
175
+ if isinstance(result, str):
176
+ extracted_text = result
177
+ extraction_method = "result_string"
178
+ elif hasattr(result, 'text'):
179
+ extracted_text = str(result.text)
180
+ extraction_method = "result_text_attribute"
181
+ elif isinstance(result, dict) and 'text' in result:
182
+ extracted_text = str(result['text'])
183
+ extraction_method = "result_dict_text"
184
+ else:
185
+ extracted_text = str(result)
186
+ extraction_method = "result_converted"
187
+
188
+ # Strategy 5: Choices attribute (ChatGPT-style response - fallback)
189
+ elif hasattr(ocr_response, 'choices') and ocr_response.choices:
190
+ choices = ocr_response.choices
191
+ if isinstance(choices, list) and len(choices) > 0:
192
+ choice = choices[0]
193
+ if hasattr(choice, 'message') and hasattr(choice.message, 'content'):
194
+ extracted_text = str(choice.message.content)
195
+ extraction_method = "choices_message_content"
196
+ elif hasattr(choice, 'text'):
197
+ extracted_text = str(choice.text)
198
+ extraction_method = "choices_text"
199
+ else:
200
+ extracted_text = str(choice)
201
+ extraction_method = "choices_converted"
202
+
203
+ # Strategy 6: Dict-like access (fallback)
204
+ elif hasattr(ocr_response, 'get') or isinstance(ocr_response, dict):
205
+ for key in ['text', 'content', 'result', 'extracted_text', 'ocr_text', 'output']:
206
+ if hasattr(ocr_response, 'get'):
207
+ value = ocr_response.get(key)
208
+ else:
209
+ value = ocr_response.get(key) if isinstance(ocr_response, dict) else None
210
+
211
+ if value:
212
+ extracted_text = str(value)
213
+ extraction_method = f"dict_key_{key}"
214
+ break
215
+
216
+ # Strategy 7: Inspect all attributes for string-like content (fallback)
217
+ elif hasattr(ocr_response, '__dict__'):
218
+ for key, value in ocr_response.__dict__.items():
219
+ if isinstance(value, str) and len(value) > 20: # Likely text content
220
+ extracted_text = value
221
+ extraction_method = f"attribute_{key}"
222
+ break
223
+ elif hasattr(value, 'text') and isinstance(value.text, str):
224
+ extracted_text = str(value.text)
225
+ extraction_method = f"nested_text_in_{key}"
226
+ break
227
+
228
+ # Strategy 8: Convert entire response to string if it seems to contain text (fallback)
229
+ if not extracted_text:
230
+ response_str = str(ocr_response)
231
+ if len(response_str) > 50 and not response_str.startswith('<'): # Not an object reference
232
+ extracted_text = response_str
233
+ extraction_method = "full_response_string"
234
+
235
+ print(f"🎯 Extraction method used: {extraction_method}")
236
+ print(f"πŸ“ Extracted text length: {len(extracted_text)} characters")
237
+ print(f"πŸ–ΌοΈ Extracted images: {len(extracted_images)}")
238
+
239
+ if extracted_text:
240
+ status = f"βœ… Successfully extracted text from PDF ({len(extracted_text)} characters)"
241
+ if extracted_images:
242
+ status += f" and {len(extracted_images)} image(s)"
243
+ else:
244
+ extracted_text = "No text could be extracted from this PDF."
245
+ status = "⚠️ OCR completed but no text was found in response."
246
+ if extracted_images:
247
+ status = f"βœ… Successfully extracted {len(extracted_images)} image(s) from PDF, but no text was found."
248
+ print(f"❌ No extractable text found in OCR response")
249
+
250
+ return extracted_text, status, extracted_images
251
+
252
+ except Exception as e:
253
+ error_msg = f"Error processing PDF: {str(e)}"
254
+ print(error_msg)
255
+ return "", f"❌ {error_msg}", []
256
+
257
+ def generate_explanations(self, extracted_text: str) -> str:
258
+ """
259
+ Generate explanations for the extracted text sections.
260
+
261
+ Args:
262
+ extracted_text: The extracted text from PDF
263
+
264
+ Returns:
265
+ Formatted explanations for all sections
266
+ """
267
+ try:
268
+ if not extracted_text or extracted_text.strip() == "":
269
+ return "No text available to explain."
270
+
271
+ if extracted_text.startswith("No text could be extracted"):
272
+ return "Cannot generate explanations - no text was extracted from the PDF."
273
+
274
+ print("πŸ€– Generating explanations for extracted text...")
275
+ explained_sections = self.text_explainer.explain_all_sections(extracted_text)
276
+
277
+ if not explained_sections:
278
+ return "No sections found to explain in the extracted text."
279
+
280
+ formatted_explanations = self.text_explainer.format_explanations_for_display(explained_sections)
281
+ return formatted_explanations
282
+
283
+ except Exception as e:
284
+ error_msg = f"Error generating explanations: {str(e)}"
285
+ print(error_msg)
286
+ return f"❌ {error_msg}"
287
+
src/ui_components/interface.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """UI component and layout for the PDF Explainer app."""
2
+
3
+ import gradio as gr
4
+ from gradio_pdf import PDF
5
+ from .styles import get_fullscreen_css
6
+
7
+ def build_interface(process_pdf_fn):
8
+ """Builds and returns the Gradio interface."""
9
+ with gr.Blocks(title="πŸ” PDF Text Extractor", theme=gr.themes.Soft()) as demo:
10
+ gr.HTML(get_fullscreen_css())
11
+ gr.Markdown("# πŸ” PDF Text Extractor")
12
+ gr.Markdown("Upload a PDF on the left to automatically extract and view text on the right.")
13
+ with gr.Row(equal_height=True):
14
+ with gr.Column(scale=1):
15
+ gr.Markdown("### πŸ“„ PDF Document")
16
+ pdf_input = PDF(
17
+ label="Upload and View PDF",
18
+ height=600,
19
+ interactive=True
20
+ )
21
+ status_output = gr.Textbox(
22
+ label="Status",
23
+ lines=2,
24
+ placeholder="Upload a PDF to see status...",
25
+ interactive=False
26
+ )
27
+ with gr.Column(scale=1):
28
+ gr.Markdown("### πŸ“ Extracted Content")
29
+ with gr.Tabs():
30
+ with gr.TabItem("Extracted Text"):
31
+ text_output = gr.Textbox(
32
+ label="Extracted Text",
33
+ lines=20,
34
+ placeholder="Upload a PDF to automatically extract text...",
35
+ show_copy_button=True,
36
+ interactive=False
37
+ )
38
+ with gr.TabItem("Explanation Script"):
39
+ explanation_output = gr.Textbox(
40
+ label="Generated Explanation Script",
41
+ lines=15,
42
+ placeholder="Explanations will be automatically generated after text extraction...",
43
+ show_copy_button=True,
44
+ interactive=False
45
+ )
46
+ gr.Markdown("### πŸ”Š Audio Generation")
47
+ audio_output = gr.Audio(
48
+ label="Generated Explanation Audio",
49
+ interactive=False,
50
+ visible=False
51
+ )
52
+ pdf_input.upload(
53
+ fn=process_pdf_fn,
54
+ inputs=[pdf_input],
55
+ outputs=[text_output, status_output, explanation_output, audio_output, audio_output]
56
+ )
57
+ return demo
src/ui_components/styles.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """CSS styles for the PDF Explainer application."""
2
+
3
+ def get_fullscreen_css():
4
+ """Return CSS for fullscreen layout."""
5
+ return """
6
+ <style>
7
+ html, body, #root, .gradio-container {
8
+ height: 100% !important;
9
+ width: 100% !important;
10
+ margin: 0 !important;
11
+ padding: 0 !important;
12
+ }
13
+ .gradio-container {
14
+ max-width: 100vw !important;
15
+ min-height: 100vh !important;
16
+ box-sizing: border-box;
17
+ }
18
+ </style>
19
+ """
src/utils/text_explainer.py ADDED
@@ -0,0 +1,341 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Text Explanation utilities using Mistral AI.
3
+ Splits text by markdown headings and generates contextual explanations for each section.
4
+ Maintains chat history to provide coherent explanations that build upon previous sections.
5
+ """
6
+
7
+ import os
8
+ import re
9
+ from typing import List, Dict, Tuple, Optional
10
+ from mistralai import Mistral
11
+
12
+
13
+ class TextExplainer:
14
+ """Generate explanations for text sections using Mistral AI."""
15
+
16
+ def __init__(self):
17
+ """Initialize the text explainer with Mistral AI client."""
18
+ self.api_key = os.environ.get("MISTRAL_API_KEY")
19
+ if not self.api_key:
20
+ raise ValueError("MISTRAL_API_KEY environment variable is required")
21
+ self.client = Mistral(api_key=self.api_key)
22
+ self.chat_history = []
23
+
24
+ def get_topic(self, text: str) -> Optional[str]:
25
+ """
26
+ Extract the main topic from the text using Mistral AI with structured output.
27
+
28
+ Args:
29
+ text: Input text to analyze
30
+
31
+ Returns:
32
+ Main topic as a string or None if not found
33
+ """
34
+ try:
35
+ # Define the JSON schema for structured output
36
+ topic_schema = {
37
+ "type": "json_schema",
38
+ "json_schema": {
39
+ "schema": {
40
+ "type": "object",
41
+ "properties": {
42
+ "main_topic": {
43
+ "type": "string",
44
+ "title": "Main Topic",
45
+ "description": "The primary / general topic or subject of the text"
46
+ },
47
+ },
48
+ "required": ["main_topic"],
49
+ "additionalProperties": False
50
+ },
51
+ "name": "topic_extraction",
52
+ "strict": True
53
+ }
54
+ }
55
+
56
+ response = self.client.chat.complete(
57
+ model="ministral-8b-2410", # Using a more recent model that supports structured output
58
+ messages=[
59
+ {
60
+ "role": "system",
61
+ "content": "You are an expert in summarizing texts. Extract the main topic from the provided text."
62
+ },
63
+ {
64
+ "role": "user",
65
+ "content": f"Analyze this text and extract the main topic:\n\n{text[:2000]}..." # Limit to first 2000 characters for performance
66
+ }
67
+ ],
68
+ temperature=0.3, # Lower temperature for more consistent structured output
69
+ max_tokens=200,
70
+ response_format=topic_schema
71
+ )
72
+
73
+ if hasattr(response, 'choices') and response.choices:
74
+ # Parse the structured JSON response
75
+ import json
76
+ try:
77
+ topic_data = json.loads(response.choices[0].message.content)
78
+ main_topic = topic_data.get("main_topic", "").strip()
79
+ confidence = topic_data.get("confidence", 0.0)
80
+ secondary_topics = topic_data.get("secondary_topics", [])
81
+
82
+ # Log the structured output for debugging
83
+ print(f"πŸ“Š Topic extraction - Main: '{main_topic}', Confidence: {confidence:.2f}")
84
+ if secondary_topics:
85
+ print(f"πŸ” Secondary topics: {', '.join(secondary_topics)}")
86
+
87
+ return main_topic if main_topic else None
88
+ except json.JSONDecodeError as json_err:
89
+ print(f"Error parsing JSON response: {json_err}")
90
+ # Fallback to raw content if JSON parsing fails
91
+ return response.choices[0].message.content.strip()
92
+ return None
93
+ except Exception as e:
94
+ print(f"Error extracting topic: {str(e)}")
95
+ return None
96
+
97
+ def split_text_by_headings(self, text: str) -> List[Dict[str, str]]:
98
+ """
99
+ Split text into sections based on markdown headings.
100
+
101
+ Args:
102
+ text: Input text with markdown headings
103
+
104
+ Returns:
105
+ List of dictionaries with 'heading' and 'content' keys
106
+ """
107
+ if not text:
108
+ return []
109
+
110
+ # Split by markdown headings (# ## ### etc.)
111
+ sections = []
112
+
113
+ # Regex to find headings and their content
114
+ # Matches: # Heading, ## Heading, ### Heading, etc.
115
+ heading_pattern = r'^(#{1,6})\s+(.+?)$'
116
+
117
+ lines = text.split('\n')
118
+ current_heading = None
119
+ current_content = []
120
+ current_level = 0
121
+
122
+ for line in lines:
123
+ heading_match = re.match(heading_pattern, line.strip())
124
+
125
+ if heading_match:
126
+ # Save previous section if it exists
127
+ if current_heading and current_content:
128
+ content_text = '\n'.join(current_content).strip()
129
+ if content_text: # Only add if there's actual content
130
+ sections.append({
131
+ 'heading': current_heading,
132
+ 'content': content_text,
133
+ 'level': current_level
134
+ })
135
+
136
+ # Start new section
137
+ level = len(heading_match.group(1)) # Count the # characters
138
+ current_heading = heading_match.group(2).strip()
139
+ current_level = level
140
+ current_content = []
141
+ else:
142
+ # Add line to current content if we have a heading
143
+ if current_heading is not None:
144
+ current_content.append(line)
145
+
146
+ # Don't forget the last section
147
+ if current_heading and current_content:
148
+ content_text = '\n'.join(current_content).strip()
149
+ if content_text:
150
+ sections.append({
151
+ 'heading': current_heading,
152
+ 'content': content_text,
153
+ 'level': current_level
154
+ })
155
+
156
+ # If no headings found, treat entire text as one section
157
+ if not sections and text.strip():
158
+ sections.append({
159
+ 'heading': 'Document Content',
160
+ 'content': text.strip(),
161
+ 'level': 1
162
+ })
163
+ return sections
164
+
165
+ def generate_explanation(self, topic: str, heading: str, content: str, section_number: int = 1, total_sections: int = 1) -> str:
166
+ """
167
+ Generate an explanation for a text section using Mistral AI with chat history context.
168
+
169
+ Args:
170
+ topic: General topic of the document
171
+ heading: Section heading
172
+ content: Section content
173
+ section_number: Current section number (for context)
174
+ total_sections: Total number of sections (for context)
175
+
176
+ Returns:
177
+ Generated explanation in simple terms
178
+ """
179
+ try:
180
+ # Build the current user message
181
+ prompt = f"""
182
+ **Section {section_number} of {total_sections}**
183
+ **Section Heading:** {heading}
184
+
185
+ **Section Content:**
186
+ {content}
187
+
188
+ **Your Explanation:**"""
189
+
190
+ # If this is the first section, initialize with system prompt
191
+ if section_number == 1:
192
+ system_prompt = f"""You are an expert teacher who explains complex topics in simple, easy-to-understand terms.
193
+
194
+ I will give you sections of text with their headings on the topic of "{topic}", and I want you to explain what each section is about in simple language, by breaking down any complex concepts or terminology. You should also explain why this information might be important or useful, use examples or analogies when helpful, and keep the explanation engaging and educational.
195
+
196
+ Make your explanation clear enough for someone without prior knowledge of the topic to understand. As you explain each section, consider how it relates to the previous sections you've already explained to provide coherent, contextual explanations throughout the document.
197
+
198
+ Do not mention anything far irrelevant from the topic of "{topic}". Do not repeat information unnecessarily, but build on previous explanations to create a comprehensive understanding of the topic. Avoid using the term 'section' and use the actual section heading instead. No need to mention the section number in your explanation.
199
+ """
200
+
201
+ # Initialize chat history with system message
202
+ self.chat_history = [
203
+ {
204
+ "role": "system",
205
+ "content": system_prompt
206
+ }
207
+ ]
208
+
209
+ # Check if content is too small (less than 200 characters)
210
+ if len(content) < 200:
211
+ print(f"πŸ“‹ Skipping API call for short content in '{heading}' ({len(content)} chars < 200)")
212
+ # Add the user prompt to chat history for context in subsequent queries
213
+ self.chat_history.append({
214
+ "role": "user",
215
+ "content": prompt
216
+ })
217
+ # Return a simple message indicating the content was too short
218
+ return f"This section contains minimal content ({len(content)} characters). The information has been noted for context in subsequent explanations."
219
+
220
+ # Add the current user message to chat history
221
+ self.chat_history.append({
222
+ "role": "user",
223
+ "content": prompt
224
+ })
225
+
226
+ # Call Mistral AI for explanation with full chat history
227
+ response = self.client.chat.complete(
228
+ model="mistral-small-2503",
229
+ messages=self.chat_history,
230
+ temperature=0.7, # Some creativity but still focused
231
+ # max_tokens=1000 # Reasonable explanation length
232
+ )
233
+
234
+ # Extract the explanation from response
235
+ if hasattr(response, 'choices') and response.choices:
236
+ explanation = response.choices[0].message.content
237
+
238
+ # Add the assistant's response to chat history
239
+ self.chat_history.append({
240
+ "role": "assistant",
241
+ "content": explanation
242
+ })
243
+
244
+ return explanation.strip()
245
+ else:
246
+ return f"Could not generate explanation for section: {heading}"
247
+
248
+ except Exception as e:
249
+ print(f"Error generating explanation for '{heading}': {str(e)}")
250
+ return f"Error generating explanation for this section: {str(e)}"
251
+
252
+ def explain_all_sections(self, text: str) -> List[Dict[str, str]]:
253
+ """
254
+ Split text by headings and generate explanations for all sections with chat history context.
255
+
256
+ Args:
257
+ text: Input text with markdown headings
258
+
259
+ Returns:
260
+ List of dictionaries with 'heading', 'content', 'explanation', and 'level' keys
261
+ """
262
+ sections = self.split_text_by_headings(text)
263
+
264
+ if not sections:
265
+ return []
266
+
267
+ print(f"πŸ” Found {len(sections)} sections to explain...")
268
+
269
+ # Extract the main topic from the text
270
+ print("🎯 Extracting main topic...")
271
+ topic = self.get_topic(text)
272
+ if topic:
273
+ print(f"πŸ“‹ Main topic identified: {topic}")
274
+ else:
275
+ topic = "General Content" # Fallback topic
276
+ print("⚠️ Could not identify main topic, using fallback")
277
+
278
+ # Reset chat history for new document
279
+ self.chat_history = []
280
+
281
+ explained_sections = []
282
+
283
+ for i, section in enumerate(sections, 1):
284
+ print(f"πŸ“ Generating explanation for section {i}/{len(sections)}: {section['heading'][:50]}...")
285
+
286
+ # Pass topic, section content, and context information
287
+ explanation = self.generate_explanation(
288
+ topic,
289
+ section['heading'],
290
+ section['content'],
291
+ section_number=i,
292
+ total_sections=len(sections)
293
+ )
294
+
295
+ explained_sections.append({
296
+ 'heading': section['heading'],
297
+ 'content': section['content'],
298
+ 'explanation': explanation,
299
+ 'level': section['level']
300
+ })
301
+
302
+ print(f"βœ… Generated explanations for all {len(explained_sections)} sections")
303
+ return explained_sections
304
+
305
+ def reset_chat_history(self):
306
+ """Reset the chat history for a new document or conversation."""
307
+ self.chat_history = []
308
+
309
+ def get_chat_history(self) -> List[Dict[str, str]]:
310
+ """Get the current chat history for debugging purposes."""
311
+ return self.chat_history.copy()
312
+
313
+ def get_chat_history_summary(self) -> str:
314
+ """Get a summary of the current chat history."""
315
+ if not self.chat_history:
316
+ return "No chat history available."
317
+
318
+ summary = f"Chat history contains {len(self.chat_history)} messages:\n"
319
+ for i, message in enumerate(self.chat_history, 1):
320
+ role = message['role']
321
+ content_preview = message['content'][:100] + "..." if len(message['content']) > 100 else message['content']
322
+ summary += f"{i}. {role.upper()}: {content_preview}\n"
323
+
324
+ return summary
325
+
326
+ def format_explanations_for_display(self, explained_sections: List[Dict[str, str]]) -> str:
327
+ """
328
+ Concatenate only the explanations from all sections for display, filtering out placeholder explanations for minimal content.
329
+ Args:
330
+ explained_sections: List of sections with explanations
331
+ Returns:
332
+ Concatenated explanations as a single string
333
+ """
334
+ if not explained_sections:
335
+ return "No sections found to explain."
336
+ skip_phrase = "This section contains minimal content"
337
+ return "\n\n".join(
338
+ section['explanation']
339
+ for section in explained_sections
340
+ if section.get('explanation') and not section['explanation'].strip().startswith(skip_phrase)
341
+ )