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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
import os
from flask import Flask, send_from_directory, request, jsonify, Response, stream_with_context
from flask_cors import CORS
import json
import time
from dotenv import load_dotenv
from pinecone import Pinecone, ServerlessSpec
from sentence_transformers import SentenceTransformer
from groq import Groq
from werkzeug.utils import secure_filename
import PyPDF2

load_dotenv()

app = Flask(__name__, static_folder='dist', static_url_path='')
CORS(app)
app.config['UPLOAD_FOLDER'] = 'uploads'
app.config['MAX_CONTENT_LENGTH'] = 50 * 1024 * 1024  # 50MB max file size

# Create uploads folder if it doesn't exist
os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)

# Initialize clients
print("Initializing Pinecone...")
pc = Pinecone(api_key=os.getenv("PINECONE_API_KEY"))
print("Loading embedding model...")
model = SentenceTransformer('all-MiniLM-L6-v2')
print("Initializing Groq...")
groq_client = Groq(api_key=os.getenv("GROQ_API_KEY"))
index_name = "pdf-rag"

def get_or_create_index():
    """Get or create Pinecone index."""
    try:
        if index_name not in pc.list_indexes().names():
            print(f"Creating index '{index_name}'...")
            pc.create_index(
                name=index_name,
                dimension=384,  # all-MiniLM-L6-v2 embedding size
                metric="cosine",
                spec=ServerlessSpec(cloud="aws", region="us-east-1")
            )
            print(f"Index '{index_name}' created successfully")
        return pc.Index(index_name)
    except Exception as e:
        print(f"Error with index: {e}")
        return None

def extract_text_from_pdf(pdf_path):
    """Extract text from PDF file."""
    try:
        with open(pdf_path, 'rb') as file:
            reader = PyPDF2.PdfReader(file)
            text = ""
            for page in reader.pages:
                text += page.extract_text() + "\n"
        return text
    except Exception as e:
        print(f"Error extracting PDF text: {e}")
        raise

def chunk_text(text, chunk_size=300, overlap=30):
    """Split text into overlapping chunks."""
    words = text.split()
    chunks = []
    for i in range(0, len(words), chunk_size - overlap):
        chunk = " ".join(words[i:i + chunk_size])
        if chunk.strip():
            chunks.append(chunk)
    return chunks

def ingest_pdf_to_pinecone(pdf_path, filename, progress_callback=None):
    """Ingest a PDF document into Pinecone."""
    def log_progress(message, progress=None):
        print(message)
        if progress_callback:
            progress_callback(message, progress)
    
    try:
        log_progress(f"\nπŸ“„ Processing {filename}...", 5)
        
        # Get or create index
        log_progress("   Getting/creating Pinecone index...", 10)
        index = get_or_create_index()
        if not index:
            raise Exception("Failed to get or create Pinecone index")
        log_progress("   βœ“ Index ready", 15)
        
        # Check if document already exists
        log_progress("   Checking if document already exists...", 20)
        try:
            existing = index.query(
                vector=[0.0] * 384,  # dummy vector
                filter={"source": {"$eq": filename}},
                top_k=1,
                include_metadata=True
            )
            if existing['matches']:
                log_progress(f"   ⚠️  Document {filename} already exists - deleting old version...", 22)
                index.delete(filter={"source": {"$eq": filename}})
                log_progress(f"   βœ“ Deleted old vectors", 25)
        except Exception as e:
            log_progress(f"   ℹ️  Continuing with ingestion...", 25)
        
        # Extract text
        log_progress("   πŸ“– Extracting text from PDF...", 30)
        text = extract_text_from_pdf(pdf_path)
        if not text.strip():
            raise Exception("No text could be extracted from the PDF")
        
        text_length = len(text)
        word_count = len(text.split())
        log_progress(f"   βœ“ Extracted {word_count} words ({text_length} chars)", 40)
        
        # Chunk text
        log_progress("   βœ‚οΈ  Chunking text...", 45)
        chunks = chunk_text(text)
        log_progress(f"   βœ“ Created {len(chunks)} chunks", 50)
        
        # Create embeddings and upsert to Pinecone
        log_progress(f"   🧠 Creating AI embeddings for {len(chunks)} chunks...", 55)
        log_progress(f"   ⏳ This is the slowest part - please wait...", 55)
        
        # Batch encode for better performance
        embeddings = model.encode(chunks, show_progress_bar=False, batch_size=32)
        
        vectors = []
        for i, (chunk, embedding) in enumerate(zip(chunks, embeddings)):
            vectors.append({
                "id": f"{filename}_chunk_{i}",
                "values": embedding.tolist(),
                "metadata": {
                    "text": chunk,
                    "source": filename,
                    "chunk_id": i
                }
            })
            # Show progress every 20 chunks
            if (i + 1) % 20 == 0 or i == len(chunks) - 1:
                progress_pct = 55 + int((i + 1) / len(chunks) * 25)  # 55-80%
                log_progress(f"   ⏳ Embeddings: {i + 1}/{len(chunks)} chunks ({progress_pct}%)", progress_pct)
        
        log_progress(f"   βœ“ Created {len(vectors)} embeddings", 80)
        
        # Upsert in batches
        log_progress("   ☁️  Uploading to Pinecone...", 85)
        batch_size = 100
        for i in range(0, len(vectors), batch_size):
            batch = vectors[i:i + batch_size]
            index.upsert(vectors=batch)
            batch_num = i//batch_size + 1
            total_batches = (len(vectors)-1)//batch_size + 1
            progress_pct = 85 + int(batch_num / total_batches * 10)  # 85-95%
            log_progress(f"   βœ“ Uploaded batch {batch_num}/{total_batches}", progress_pct)
        
        # Verify ingestion
        stats = index.describe_index_stats()
        log_progress(f"\nβœ… Successfully ingested {filename}!", 100)
        log_progress(f"   Total vectors in index: {stats.total_vector_count}", 100)
        
        return True
    except Exception as e:
        print(f"\n❌ Error ingesting PDF: {e}")
        import traceback
        traceback.print_exc()
        raise

def retrieve_context(query, top_k=3):
    """Retrieve relevant context from Pinecone."""
    try:
        print(f"   Getting index...")
        index = get_or_create_index()
        if not index:
            print("   ❌ Failed to get index")
            return []
        
        print(f"   Creating query embedding...")
        query_embedding = model.encode(query).tolist()
        print(f"   βœ“ Embedding created (dimension: {len(query_embedding)})")
        
        print(f"   Querying Pinecone for top {top_k} matches...")
        results = index.query(vector=query_embedding, top_k=top_k, include_metadata=True)
        
        print(f"   βœ“ Query returned {len(results['matches'])} matches")
        
        contexts = []
        for i, match in enumerate(results['matches']):
            print(f"      Match {i+1}: score={match['score']:.4f}, id={match['id']}")
            contexts.append({
                'text': match['metadata']['text'],
                'source': match['metadata']['source'],
                'score': match['score']
            })
        
        return contexts
    except Exception as e:
        print(f"   ❌ Error retrieving context: {e}")
        import traceback
        traceback.print_exc()
        return []

def detect_language(text):
    """Detect the language of the input text using Groq."""
    try:
        print(f"\n🌍 Detecting language of query...")
        response = groq_client.chat.completions.create(
            model="llama-3.1-8b-instant",
            messages=[
                {"role": "system", "content": "You are a language detection expert. Respond with ONLY the language name in English (e.g., 'English', 'Spanish', 'French', 'Hindi', 'Arabic', etc.). No other text."},
                {"role": "user", "content": f"What language is this text in? Text: {text}"}
            ],
            temperature=0.1,
            max_tokens=20
        )
        language = response.choices[0].message.content.strip()
        print(f"   βœ“ Detected language: {language}")
        return language
    except Exception as e:
        print(f"   ⚠️  Language detection failed: {e}, defaulting to English")
        return "English"

def generate_response(query, contexts):
    """Generate response using Groq with automatic language detection and translation."""
    try:
        if not contexts:
            print("⚠️  No contexts provided to generate_response")
            return "I don't have any document context to answer your question. Please upload a document first."
        
        # Detect the language of the user's query
        user_language = detect_language(query)
        
        context_text = "\n\n".join([f"[Source: {c['source']}]\n{c['text']}" for c in contexts])
        
        # Create prompt with language instruction
        if user_language.lower() == "english":
            system_prompt = """You are a helpful assistant that answers questions based on provided document context. 

IMPORTANT FORMATTING RULES:
- Use markdown formatting
- Structure your response with clear sections using ## headings
- Use bullet points (β€’) for lists
- Use **bold** for key terms
- Keep it concise and scannable
- Use line breaks between sections
- If listing items, use numbered lists or bullet points
- Avoid long paragraphs - break into points"""

            prompt = f"""Based on the following context from documents, answer the user's question using clean markdown formatting.

Context:
{context_text}

Question: {query}

Answer (use markdown with headings, bullet points, and bold text):"""
        else:
            system_prompt = f"""You are a helpful multilingual assistant that answers questions based on provided document context. Always respond in {user_language}.

IMPORTANT FORMATTING RULES:
- Use markdown formatting
- Structure your response with clear sections using ## headings
- Use bullet points (β€’) for lists
- Use **bold** for key terms
- Keep it concise and scannable
- Use line breaks between sections
- Translate semantically (meaning-based), not word-for-word
- Avoid long paragraphs - break into points"""

            prompt = f"""Based on the following context from documents, answer the user's question in {user_language} using clean markdown formatting.

Context:
{context_text}

Question (in {user_language}): {query}

Answer (in {user_language}, use markdown with headings, bullet points, and bold text):"""
        
        print(f"\nπŸ“ Prompt being sent to Groq:")
        print(f"   Language: {user_language}")
        print(f"   System: {system_prompt[:100]}...")
        print(f"   User prompt length: {len(prompt)} characters")
        print(f"   Context length: {len(context_text)} characters")
        
        # Increase max_tokens for non-Latin scripts (Telugu, Hindi, Arabic, Chinese, etc.)
        # These languages require more tokens per character
        non_latin_languages = ['telugu', 'hindi', 'tamil', 'kannada', 'malayalam', 'bengali', 
                               'gujarati', 'marathi', 'punjabi', 'urdu', 'arabic', 'chinese', 
                               'japanese', 'korean', 'thai', 'hebrew']
        
        max_tokens = 2048 if any(lang in user_language.lower() for lang in non_latin_languages) else 1024
        
        print(f"\nπŸš€ Calling Groq API...")
        print(f"   Max tokens: {max_tokens} (adjusted for {user_language})")
        
        response = groq_client.chat.completions.create(
            model="llama-3.1-8b-instant",
            messages=[
                {"role": "system", "content": system_prompt},
                {"role": "user", "content": prompt}
            ],
            temperature=0.3,
            max_tokens=max_tokens
        )
        
        llm_response = response.choices[0].message.content
        
        print(f"\nβœ… Groq API Response:")
        print(f"   Model: {response.model}")
        print(f"   Language: {user_language}")
        print(f"   Response length: {len(llm_response)} characters")
        print(f"   Full response: {llm_response}")
        
        return llm_response
    except Exception as e:
        print(f"\n❌ Error generating response: {e}")
        import traceback
        traceback.print_exc()
        return f"Error generating response: {str(e)}"

# Serve React app
@app.route('/')
def index():
    """Serve React app."""
    return send_from_directory(app.static_folder, 'index.html')

@app.route('/<path:path>')
def serve_static(path):
    """Serve static files."""
    if os.path.exists(os.path.join(app.static_folder, path)):
        return send_from_directory(app.static_folder, path)
    return send_from_directory(app.static_folder, 'index.html')

# API endpoints
@app.route('/api/status', methods=['GET'])
def status():
    """Check if documents are uploaded."""
    try:
        index = get_or_create_index()
        if not index:
            return jsonify({'hasDocuments': False, 'error': 'Index not available'})
        
        # Check if index has any vectors
        stats = index.describe_index_stats()
        has_docs = stats.total_vector_count > 0
        
        return jsonify({
            'hasDocuments': has_docs,
            'vectorCount': stats.total_vector_count
        })
    except Exception as e:
        print(f"Status check error: {e}")
        return jsonify({'hasDocuments': False, 'error': str(e)})

@app.route('/api/chat', methods=['POST'])
def chat():
    """Handle chat requests."""
    try:
        print("\n" + "="*80)
        print("πŸ”΅ CHAT REQUEST RECEIVED")
        print("="*80)
        
        data = request.json
        query = data.get('query', '').strip()
        
        if not query:
            print("❌ Error: Empty query")
            return jsonify({'error': 'Query is required'}), 400
        
        print(f"πŸ“ User Query: {query}")
        
        # Retrieve context
        print("\nπŸ” Retrieving context from Pinecone...")
        contexts = retrieve_context(query)
        
        print(f"πŸ“Š Retrieved {len(contexts)} context chunks")
        
        if not contexts:
            print("⚠️  No contexts found in Pinecone")
            return jsonify({
                'response': "I couldn't find relevant information in the uploaded documents. Please make sure you've uploaded a document first.",
                'sources': []
            })
        
        # Log retrieved contexts
        for i, ctx in enumerate(contexts):
            print(f"\nπŸ“„ Context {i+1}:")
            print(f"   Source: {ctx['source']}")
            print(f"   Score: {ctx['score']:.4f}")
            print(f"   Text Preview: {ctx['text'][:200]}...")
        
        # Generate response
        print("\nπŸ€– Generating response with Groq LLM...")
        response = generate_response(query, contexts)
        
        print(f"\nβœ… LLM Response Generated:")
        print(f"   Length: {len(response)} characters")
        print(f"   Response: {response[:300]}...")
        
        sources = [{'source': c['source'], 'score': round(c['score'], 2)} for c in contexts]
        
        print(f"\nπŸ“€ Sending response with {len(sources)} sources")
        print("="*80 + "\n")
        
        return jsonify({
            'response': response,
            'sources': sources
        })
    except Exception as e:
        print(f"\n❌ CHAT ERROR: {e}")
        import traceback
        traceback.print_exc()
        return jsonify({'error': str(e)}), 500

@app.route('/api/upload-stream', methods=['POST'])
def upload_stream():
    """Handle PDF upload with streaming progress updates."""
    def generate():
        try:
            if 'file' not in request.files:
                yield f"data: {json.dumps({'error': 'No file provided'})}\n\n"
                return
            
            file = request.files['file']
            if file.filename == '':
                yield f"data: {json.dumps({'error': 'No file selected'})}\n\n"
                return
            
            if not file.filename.lower().endswith('.pdf'):
                yield f"data: {json.dumps({'error': 'Only PDF files are allowed'})}\n\n"
                return
            
            filename = secure_filename(file.filename)
            filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
            
            yield f"data: {json.dumps({'message': f'πŸ’Ύ Saving {filename}...', 'progress': 0})}\n\n"
            file.save(filepath)
            
            file_size = os.path.getsize(filepath)
            yield f"data: {json.dumps({'message': f'βœ“ Saved ({file_size / 1024:.1f} KB)', 'progress': 5})}\n\n"
            
            start_time = time.time()
            
            def progress_callback(message, progress):
                data = {'message': message, 'progress': progress or 0}
                return f"data: {json.dumps(data)}\n\n"
            
            # Ingest with progress updates
            def ingest_with_progress():
                def callback(msg, prog):
                    yield progress_callback(msg, prog)
                
                ingest_pdf_to_pinecone(filepath, filename, lambda msg, prog: None)
            
            # Actually we need to refactor this - let me use a simpler approach
            # Store progress in a global dict
            progress_data = {'message': '', 'progress': 0}
            
            def callback(msg, prog):
                progress_data['message'] = msg
                progress_data['progress'] = prog
            
            # Run ingestion in a way that yields progress
            import threading
            
            def run_ingestion():
                ingest_pdf_to_pinecone(filepath, filename, callback)
            
            thread = threading.Thread(target=run_ingestion)
            thread.start()
            
            last_progress = 0
            while thread.is_alive():
                if progress_data['progress'] != last_progress:
                    yield f"data: {json.dumps(progress_data)}\n\n"
                    last_progress = progress_data['progress']
                time.sleep(0.5)
            
            thread.join()
            
            elapsed = time.time() - start_time
            yield f"data: {json.dumps({'message': f'βœ… Completed in {elapsed:.1f}s!', 'progress': 100, 'done': True, 'filename': filename})}\n\n"
            
        except Exception as e:
            yield f"data: {json.dumps({'error': str(e), 'done': True})}\n\n"
    
    return Response(stream_with_context(generate()), mimetype='text/event-stream')

@app.route('/api/upload', methods=['POST'])
def upload():
    """Handle PDF upload and ingestion."""
    try:
        print("\n" + "="*80)
        print("πŸ“€ UPLOAD REQUEST RECEIVED")
        print("="*80)
        
        if 'file' not in request.files:
            print("❌ Error: No file in request")
            return jsonify({'error': 'No file provided'}), 400
        
        file = request.files['file']
        if file.filename == '':
            print("❌ Error: Empty filename")
            return jsonify({'error': 'No file selected'}), 400
        
        if not file.filename.lower().endswith('.pdf'):
            print(f"❌ Error: Invalid file type: {file.filename}")
            return jsonify({'error': 'Only PDF files are allowed'}), 400
        
        filename = secure_filename(file.filename)
        filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
        
        print(f"πŸ’Ύ Saving file: {filename}")
        print(f"   Path: {filepath}")
        file.save(filepath)
        
        file_size = os.path.getsize(filepath)
        print(f"   Size: {file_size / 1024:.2f} KB")
        
        if file_size > 5 * 1024 * 1024:  # > 5MB
            print(f"   ⚠️  Large file detected - this may take 1-2 minutes")
        
        # Ingest PDF
        print(f"\nπŸ”„ Starting ingestion of {filename}")
        print(f"   ⏰ Estimated time: {max(10, int(file_size / (1024 * 100)))} seconds")
        
        start_time = time.time()
        
        ingest_pdf_to_pinecone(filepath, filename)
        
        elapsed = time.time() - start_time
        print(f"\nβœ… Upload and ingestion completed in {elapsed:.1f} seconds")
        print("="*80 + "\n")
        
        return jsonify({
            'message': f'Successfully ingested {filename}',
            'filename': filename,
            'success': True,
            'processingTime': round(elapsed, 1)
        })
    except Exception as e:
        print(f"\n❌ UPLOAD ERROR: {e}")
        import traceback
        traceback.print_exc()
        return jsonify({'error': str(e)}), 500

if __name__ == '__main__':
    print("Starting Flask server...")
    print(f"Pinecone API Key: {'Set' if os.getenv('PINECONE_API_KEY') else 'Not Set'}")
    print(f"Groq API Key: {'Set' if os.getenv('GROQ_API_KEY') else 'Not Set'}")
    port = int(os.getenv('PORT', 5000))
    app.run(debug=False, port=port, host='0.0.0.0')