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('/') 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')