Spaces:
Sleeping

chatdocs / app.py
Pavankumardns's picture
done
fd16f5d
Raw History Blame Contribute Delete
21.3 kB
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')