Download app.py from Neerajkadari/Context-Aware_Conversational_Intelligence_System: direct link, hf CLI and curl.
- Browser
- Download file 26 kB
-
https://huggingface.co/spaces/Neerajkadari/Context-Aware_Conversational_Intelligence_System/resolve/main/app.py
- Command line
-
hf download hf://spaces/Neerajkadari/Context-Aware_Conversational_Intelligence_System/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Neerajkadari/Context-Aware_Conversational_Intelligence_System/resolve/main/app.py
26 kB
| """ | |
| FLASK WEB APPLICATION & RUNTIME AI ENGINE | |
| ========================================= | |
| Context-Aware Conversational Intelligence System. | |
| Dual-mode operation: | |
| - Document-aware assistant (RAG mode) | |
| - General-purpose conversational chatbot | |
| Supports PDF/DOCX upload, Groq LLM API for answers. | |
| """ | |
| import logging | |
| import json | |
| import os | |
| import sys | |
| from datetime import datetime | |
| from collections import deque | |
| from typing import List, Dict, Any, Optional | |
| from dotenv import load_dotenv | |
| load_dotenv() | |
| from flask import Flask, request, jsonify, render_template, send_from_directory | |
| from werkzeug.utils import secure_filename | |
| from flask_cors import CORS | |
| import chromadb | |
| from sentence_transformers import SentenceTransformer | |
| import torch | |
| from transformers import AutoModelForSequenceClassification, AutoTokenizer | |
| # Setup path | |
| sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) | |
| import config | |
| logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(name)s] [%(levelname)s] %(message)s") | |
| logger = logging.getLogger(__name__) | |
| DEVICE = torch.device('cuda' if torch.cuda.is_available() else 'cpu') | |
| # βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # INFERENCE ENGINE β Transformer Text Classification | |
| # βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| class ModelInference: | |
| """Loads trained transformer models and performs text classification.""" | |
| def __init__(self): | |
| self.loaded_model_name = None | |
| self.model = None | |
| self.tokenizer = None | |
| def load_model(self, model_key: str): | |
| if self.loaded_model_name == model_key: | |
| return | |
| model_path = config.MODEL_DIR / model_key | |
| if not model_path.exists(): | |
| raise FileNotFoundError(f"Model {model_key.upper()} not found at {model_path}. Please run train.py first.") | |
| logger.info("Loading %s from %s...", model_key, model_path) | |
| self.tokenizer = AutoTokenizer.from_pretrained(str(model_path)) | |
| if (model_path / "adapter_config.json").exists(): | |
| from peft import PeftModel | |
| with open(model_path / "adapter_config.json") as f: | |
| adapter_cfg = json.load(f) | |
| base_model_name = adapter_cfg["base_model_name_or_path"] | |
| logger.info("Loading base model %s for PEFT adapter...", base_model_name) | |
| base_model = AutoModelForSequenceClassification.from_pretrained( | |
| base_model_name, num_labels=config.NUM_CLASSES, torch_dtype=torch.float32 | |
| ) | |
| base_model.config.pad_token_id = self.tokenizer.pad_token_id | |
| self.model = PeftModel.from_pretrained(base_model, str(model_path)) | |
| else: | |
| self.model = AutoModelForSequenceClassification.from_pretrained(str(model_path)) | |
| self.model.to(DEVICE) | |
| self.model.eval() | |
| self.loaded_model_name = model_key | |
| logger.info("Successfully loaded %s from disk!", model_key) | |
| def classify_text(self, text: str, model_key: str = "bert") -> str: | |
| if model_key == "mistral": | |
| import requests | |
| hf_token = os.environ.get("HF_TOKEN") | |
| if not hf_token: | |
| return "Error: HF_TOKEN environment variable is missing." | |
| headers = {"Authorization": f"Bearer {hf_token}"} | |
| prompt = ( | |
| "You are a news classifier.\n\n" | |
| "Categories:\n" | |
| "World\n" | |
| "Sports\n" | |
| "Business\n" | |
| "Sci/Tech\n\n" | |
| "Return ONLY the category name.\n\n" | |
| f"Text:\n{text}\n\n" | |
| "Category:\n" | |
| ) | |
| try: | |
| api_url = "https://api-inference.huggingface.co/models/mistralai/Mistral-7B-Instruct-v0.2" | |
| payload = {"inputs": prompt, "parameters": {"max_new_tokens": 10, "return_full_text": False}} | |
| response = requests.post(api_url, headers=headers, json=payload, timeout=15) | |
| if response.status_code == 200: | |
| result = response.json()[0]["generated_text"].strip() | |
| for c in config.CLASS_NAMES: | |
| if c.lower() in result.lower(): return c | |
| return result | |
| return f"Error: HF API failed with status {response.status_code} - {response.text}" | |
| except requests.exceptions.Timeout: | |
| return "Error: HF API request timed out." | |
| except Exception as e: | |
| return f"Error: {e}" | |
| try: | |
| self.load_model(model_key) | |
| except Exception as e: | |
| return str(e) | |
| inputs = self.tokenizer(text, return_tensors="pt", truncation=True, max_length=128, padding=True) | |
| inputs = {k: v.to(DEVICE) for k, v in inputs.items()} | |
| with torch.no_grad(): | |
| outputs = self.model(**inputs) | |
| pred_idx = outputs.logits.argmax(dim=-1).item() | |
| class_names = config.CLASS_NAMES | |
| if pred_idx < len(class_names): | |
| return class_names[pred_idx] | |
| return str(pred_idx) | |
| # βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # KNOWLEDGE STORE β Vector Database (RAG) | |
| # βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| class KnowledgeStore: | |
| """Manages document embeddings in ChromaDB for semantic search.""" | |
| def __init__(self): | |
| self.embed_model = SentenceTransformer(config.EMBEDDING_MODEL) | |
| self.client = chromadb.PersistentClient(path=str(config.VECTOR_DB_DIR)) | |
| self.collection = self.client.get_or_create_collection( | |
| name=config.CHROMA_COLLECTION, | |
| metadata={"hnsw:space": "cosine"} | |
| ) | |
| logger.info("KnowledgeStore initialized.") | |
| def add_custom_document(self, chunks: List[str], filename: str): | |
| """Index document chunks into ChromaDB.""" | |
| metas: List[Dict[str, Any]] = [{"source": filename} for _ in chunks] | |
| ids: List[str] = [f"{filename}_chunk_{i}" for i in range(len(chunks))] | |
| raw_embs = self.embed_model.encode(chunks).tolist() | |
| embeddings: List[List[float]] = raw_embs if isinstance(raw_embs, list) else [] | |
| for start in range(0, len(chunks), 100): | |
| end = start + 100 | |
| self.collection.upsert( | |
| documents=chunks[start:end], embeddings=embeddings[start:end], | |
| metadatas=metas[start:end], ids=ids[start:end] | |
| ) | |
| logger.info(f"Custom document '{filename}' indexed in ChromaDB ({len(chunks)} chunks).") | |
| def add_dataset_knowledge(self, texts: List[str], labels: List[int]): | |
| """Index training dataset text into ChromaDB for RAG use.""" | |
| class_names = config.CLASS_NAMES | |
| chunks = [] | |
| metas = [] | |
| ids = [] | |
| for i, (text, label) in enumerate(zip(texts, labels)): | |
| category = class_names[label] if label < len(class_names) else str(label) | |
| chunks.append(text) | |
| metas.append({"source": "ag_news_train", "category": category}) | |
| ids.append(f"ag_news_train_{i}") | |
| embeddings = self.embed_model.encode(chunks).tolist() | |
| for start in range(0, len(chunks), 100): | |
| end = start + 100 | |
| self.collection.upsert( | |
| documents=chunks[start:end], embeddings=embeddings[start:end], | |
| metadatas=metas[start:end], ids=ids[start:end] | |
| ) | |
| logger.info(f"Dataset knowledge indexed: {len(chunks)} samples.") | |
| def query(self, question: str, top_k: int = 5, source: str = None) -> List[Dict]: | |
| query_emb = self.embed_model.encode([question]).tolist() | |
| where_clause = {"source": source} if source else None | |
| results = self.collection.query( | |
| query_embeddings=query_emb, n_results=top_k, | |
| where=where_clause, | |
| include=["documents", "metadatas", "distances"] | |
| ) | |
| hits = [] | |
| if results["documents"]: | |
| docs = results["documents"][0] | |
| metas = results["metadatas"][0] | |
| dists = results["distances"][0] | |
| for doc, meta, dist in zip(docs, metas, dists): | |
| hits.append({"text": doc, "metadata": meta, "similarity": round(float(1.0 - float(dist)), 4)}) | |
| return hits | |
| def get_context_string(self, question: str, top_k: int = 5, source: str = None) -> str: | |
| hits = self.query(question, top_k, source) | |
| if not hits: | |
| return "" | |
| return "\n\n".join([f"{h['text']}" for h in hits]) | |
| def has_documents(self) -> bool: | |
| """Check if any custom documents have been indexed.""" | |
| try: | |
| count = self.collection.count() | |
| return count > 0 | |
| except Exception: | |
| return False | |
| # βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # CONVERSATIONAL ENGINE β Dual-Mode (Document QA + General Chat) | |
| # βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| class ConversationalEngine: | |
| """ | |
| Dual-mode conversational AI engine: | |
| 1. Document-aware mode: Uses RAG context to answer questions about uploaded files | |
| 2. General chatbot mode: Answers general questions using LLM knowledge | |
| """ | |
| def __init__(self): | |
| self.groq_client = None | |
| self.groq_api_key = None | |
| logger.info("ConversationalEngine initialized (dual-mode: document QA + general chatbot).") | |
| # Handle default API Key loaded from .env | |
| default_groq_key = os.environ.get("GROQ_API_KEY") | |
| if default_groq_key: | |
| self.set_api_key(default_groq_key.strip('"\' ')) | |
| def set_api_key(self, api_key: str): | |
| """Set/update the Groq API key.""" | |
| self.groq_api_key = api_key | |
| try: | |
| from groq import Groq | |
| self.groq_client = Groq(api_key=api_key) | |
| logger.info("Groq API key received and client initialized.") | |
| except Exception as e: | |
| logger.error("Failed to initialize Groq client: %s", e) | |
| self.groq_client = None | |
| def generate_response(self, question: str, context: str, has_document: bool = False) -> str: | |
| """ | |
| Generate response based on context availability: | |
| - If context exists -> use RAG retrieval mode (document QA) | |
| - If no context but document uploaded -> inform user | |
| - If no document -> use general chatbot mode | |
| """ | |
| q_lower = question.lower().strip() | |
| # Greetings β always respond warmly | |
| if q_lower in ["hello", "hi", "hey", "hi!", "hello!", "hey!"]: | |
| if has_document: | |
| return ("Hello! I'm ready to help you with your uploaded document. " | |
| "Ask me anything about it, or feel free to ask general questions too!") | |
| return ("Hello! I'm your AI assistant. I can explain concepts, answer questions, and help you reason through problems. How can I help you today?") | |
| # --- MODE 1: Document context available -> RAG mode --- | |
| if context: | |
| if self.groq_client and self.groq_api_key: | |
| try: | |
| return self._groq_rag_response(question, context) | |
| except Exception as e: | |
| logger.warning("Groq RAG call failed: %s. Falling back.", e) | |
| # Fallback if Groq not available | |
| return self._context_fallback(question, context) | |
| # --- MODE 2: Document uploaded but no relevant context found --- | |
| if has_document and not context: | |
| if self.groq_client and self.groq_api_key: | |
| try: | |
| return self._groq_general_response(question, | |
| note="The user has uploaded a document, but this question doesn't seem related to it. Answer generally.") | |
| except Exception as e: | |
| logger.warning("Groq general call failed: %s", e) | |
| return ("I couldn't find relevant information about that in your uploaded document. " | |
| "Try rephrasing your question, or if it's a general question, " | |
| "I'll do my best to help! Please configure your Groq API key in the `.env` file for enhanced responses.") | |
| # --- MODE 3: No document uploaded -> General chatbot mode --- | |
| if self.groq_client and self.groq_api_key: | |
| try: | |
| return self._groq_general_response(question) | |
| except Exception as e: | |
| logger.warning("Groq general call failed: %s", e) | |
| # Ultimate fallback when no API key is set | |
| return ("I'd love to help! To get the best responses, please configure your Groq API key in the `.env` file.\n\n" | |
| "With an API key, I can answer questions on any topic, explain concepts in detail, and help with reasoning and problem-solving.") | |
| def _groq_rag_response(self, question: str, context: str) -> str: | |
| """Generate response using Groq API with RAG context.""" | |
| system_prompt = ( | |
| "You are a helpful, accurate AI assistant that answers questions based on the provided document context. " | |
| "Always base your answers on the context provided. If the context doesn't contain enough information " | |
| "to fully answer the question, say so and provide what you can. Be detailed, accurate, and helpful. " | |
| "Format your responses clearly with proper structure." | |
| ) | |
| user_prompt = f"""Context from the uploaded document: | |
| {context} | |
| Question: {question} | |
| Please provide a detailed, accurate answer based on the document context above.""" | |
| response = self.groq_client.chat.completions.create( | |
| model=config.GROQ_MODEL, | |
| messages=[ | |
| {"role": "system", "content": system_prompt}, | |
| {"role": "user", "content": user_prompt} | |
| ], | |
| temperature=config.TEMPERATURE, | |
| max_tokens=config.MAX_RESPONSE_TOKENS | |
| ) | |
| return response.choices[0].message.content.strip() | |
| def _groq_general_response(self, question: str, note: str = "") -> str: | |
| """Generate general conversational response using Groq API (no document context).""" | |
| system_prompt = ( | |
| "You are an intelligent, helpful, and friendly AI assistant. " | |
| "You can answer general questions, explain concepts, provide reasoning, " | |
| "summarize information, and assist users with a wide variety of topics. " | |
| "Be conversational yet informative. Format responses clearly." | |
| ) | |
| if note: | |
| system_prompt += f"\n\nNote: {note}" | |
| response = self.groq_client.chat.completions.create( | |
| model=config.GROQ_MODEL, | |
| messages=[ | |
| {"role": "system", "content": system_prompt}, | |
| {"role": "user", "content": question} | |
| ], | |
| temperature=0.7, | |
| max_tokens=config.MAX_RESPONSE_TOKENS | |
| ) | |
| return response.choices[0].message.content.strip() | |
| def _context_fallback(self, question: str, context: str) -> str: | |
| """Fallback: structured context presentation when Groq is unavailable.""" | |
| return f"Based on the uploaded document:\n\n{context}" | |
| # βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # MEMORY MANAGER β Conversation History | |
| # βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| class MemoryManager: | |
| """Manages conversation history and session state.""" | |
| def __init__(self): | |
| self.history = deque(maxlen=50) | |
| self.started_at = datetime.now().isoformat() | |
| self.active_document = None | |
| def add_turn(self, role, content): | |
| self.history.append({"role": role, "content": content}) | |
| def get_session_summary(self): | |
| doc_status = f"Active document: {self.active_document}" if self.active_document else "No document loaded" | |
| return f"Session started: {self.started_at}\nTurns: {len(self.history)}\n{doc_status}" | |
| # βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # AGENT CONTROLLER β Orchestrates All Modules | |
| # βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| class AgentController: | |
| """ | |
| Central AI agent that orchestrates: | |
| - Document Q&A (RAG mode) | |
| - General conversation (chatbot mode) | |
| - Text classification (transformer models) | |
| """ | |
| def __init__(self): | |
| self.memory = MemoryManager() | |
| self.knowledge = KnowledgeStore() | |
| self.conversation = ConversationalEngine() | |
| self.inference = ModelInference() | |
| # Load evaluation results if available | |
| p = config.REPORT_DIR / "evaluation_summary.json" | |
| try: | |
| self.results = json.load(open(p)) if p.exists() else {} | |
| except Exception: | |
| self.results = {} | |
| def set_api_key(self, api_key: str): | |
| """Forward API key to conversation engine.""" | |
| self.conversation.set_api_key(api_key) | |
| def handle_query(self, query: str) -> str: | |
| """ | |
| Process user query with intelligent routing: | |
| 1. Classification commands -> use transformer models | |
| 2. Document questions -> use RAG retrieval | |
| 3. General questions -> use LLM chatbot | |
| """ | |
| self.memory.add_turn("user", query) | |
| q_lower = query.lower() | |
| # --- Route 1: Text classification commands --- | |
| if "classify" in q_lower or "predict" in q_lower: | |
| model_to_use = "bert" | |
| for k in config.MODELS: | |
| if k in q_lower: | |
| model_to_use = k | |
| break | |
| text_to_classify = query | |
| if ":" in query: | |
| text_to_classify = query.split(":", 1)[-1].strip() | |
| result = self.inference.classify_text(text_to_classify, model_to_use) | |
| response = f"Using {model_to_use.upper()}, I classified this text as: **{result}**." | |
| self.memory.add_turn("assistant", response) | |
| return response | |
| # --- Route 2: Model results query --- | |
| if any(kw in q_lower for kw in ["model results", "model comparison", "evaluation results", "model performance"]): | |
| if self.results: | |
| lines = ["Here are the model evaluation results:\n"] | |
| lines.append("| Model | Accuracy | Precision | Recall | F1 Score |") | |
| lines.append("|-------|----------|-----------|--------|----------|") | |
| best_model = None | |
| best_f1 = 0 | |
| for model_key, metrics in self.results.items(): | |
| acc = metrics.get("accuracy", 0) | |
| prec = metrics.get("precision", 0) | |
| rec = metrics.get("recall", 0) | |
| f1 = metrics.get("f1", 0) | |
| lines.append(f"| {model_key.upper()} | {acc:.4f} | {prec:.4f} | {rec:.4f} | {f1:.4f} |") | |
| if f1 > best_f1: | |
| best_f1 = f1 | |
| best_model = model_key | |
| if best_model: | |
| lines.append(f"\n**Best performing model: {best_model.upper()}** (F1: {best_f1:.4f})") | |
| response = "\n".join(lines) | |
| else: | |
| response = "No evaluation results available yet. Please run `train.py` first to train and evaluate the models." | |
| self.memory.add_turn("assistant", response) | |
| return response | |
| # --- Route 3: Document Q&A (RAG) or General Chat --- | |
| source = self.memory.active_document | |
| has_document = source is not None | |
| context = self.knowledge.get_context_string(query, source=source) if has_document else "" | |
| response = self.conversation.generate_response(query, context, has_document=has_document) | |
| self.memory.add_turn("assistant", response) | |
| return response | |
| # βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # FLASK APPLICATION | |
| # βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| app = Flask( | |
| __name__, | |
| template_folder=str(config.BASE_DIR / "ui" / "templates"), | |
| static_folder=str(config.BASE_DIR / "ui" / "static") | |
| ) | |
| CORS(app) | |
| agent = None | |
| def get_agent(): | |
| global agent | |
| if agent is None: | |
| agent = AgentController() | |
| return agent | |
| # --- Routes --- | |
| def index(): | |
| return render_template("index.html") | |
| def chat(): | |
| data = request.get_json(force=True) | |
| msg = data.get("message", "").strip() | |
| if not msg: | |
| return jsonify({"error": "Empty message"}), 400 | |
| try: | |
| response = get_agent().handle_query(msg) | |
| return jsonify({"response": response}) | |
| except Exception as e: | |
| logger.exception("Chat error") | |
| return jsonify({"error": str(e)}), 500 | |
| def status(): | |
| return jsonify({"status": get_agent().memory.get_session_summary()}) | |
| def models(): | |
| model_info = {} | |
| for key, cfg in config.MODELS.items(): | |
| model_info[key] = { | |
| "name": cfg["name"], | |
| "architecture": cfg.get("architecture", "Transformer"), | |
| "description": cfg.get("description", ""), | |
| } | |
| return jsonify({"models": model_info}) | |
| def results(): | |
| res = get_agent().results | |
| safe = {} | |
| best_model = None | |
| best_f1 = 0 | |
| for k, v in res.items(): | |
| f1 = v.get("f1", 0) | |
| safe[k] = { | |
| "accuracy": v.get("accuracy"), | |
| "precision": v.get("precision"), | |
| "recall": v.get("recall"), | |
| "f1": f1 | |
| } | |
| if f1 > best_f1: | |
| best_f1 = f1 | |
| best_model = k | |
| return jsonify({"results": safe, "best_model": best_model}) | |
| def serve_report(filename): | |
| return send_from_directory(str(config.REPORT_DIR), filename) | |
| UPLOAD_FOLDER = str(config.BASE_DIR / "data") | |
| MAX_FILE_SIZE = 200 * 1024 * 1024 # 200MB | |
| def upload_file(): | |
| if "file" not in request.files: | |
| return jsonify({"error": "No file part"}), 400 | |
| file = request.files["file"] | |
| if file.filename == "": | |
| return jsonify({"error": "No selected file"}), 400 | |
| # Check file extension | |
| ext = os.path.splitext(file.filename)[1].lower() | |
| if ext not in ['.pdf', '.docx']: | |
| return jsonify({"error": f"Unsupported file type: {ext}. Only PDF and DOCX are supported."}), 400 | |
| try: | |
| filename = secure_filename(file.filename) | |
| filepath = os.path.join(UPLOAD_FOLDER, filename) | |
| os.makedirs(UPLOAD_FOLDER, exist_ok=True) | |
| file.save(filepath) | |
| # Check size | |
| if os.path.getsize(filepath) > MAX_FILE_SIZE: | |
| os.remove(filepath) | |
| return jsonify({"error": "File exceeds 200MB limit."}), 400 | |
| from rag.document_loader import DocumentLoader | |
| loader = DocumentLoader() | |
| chunks = loader.process_file(filepath, filename) | |
| get_agent().knowledge.add_custom_document(chunks, filename) | |
| get_agent().memory.active_document = filename | |
| get_agent().memory.add_turn("system", f"Document {filename} loaded successfully.") | |
| return jsonify({ | |
| "message": f"Successfully processed '{filename}' into {len(chunks)} contextual chunks. You can now ask questions about your document!", | |
| "filename": filename, | |
| "chunks": len(chunks) | |
| }) | |
| except Exception as e: | |
| logger.exception("Upload error") | |
| return jsonify({"error": str(e)}), 500 | |
| # βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # MAIN ENTRY POINT | |
| # βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| if __name__ == "__main__": | |
| import socket | |
| try: | |
| local_ip = socket.gethostbyname(socket.gethostname()) | |
| except Exception: | |
| local_ip = "127.0.0.1" | |
| print("=" * 60) | |
| print(" CONTEXT-AWARE CONVERSATIONAL INTELLIGENCE SYSTEM") | |
| print(" Dual Mode: Document QA + General Chatbot") | |
| print(f" Local Access: http://127.0.0.1:{config.PORT}") | |
| if config.HOST == "0.0.0.0": | |
| print(f" Network (Mobile) Access: http://{local_ip}:{config.PORT}") | |
| print("=" * 60) | |
| app.run(host=config.HOST, port=config.PORT, debug=False) | |