Upload 35 files
Browse filesFiles changed (36)
- .envAdded+1
- .gitattributes+3
- .gitignoreAdded+8
- ProcfileAdded+1
- README.md+247-8
- __pycache__/app.cpython-313.pycAdded
- __pycache__/config.cpython-313.pycAdded
- app.pyAdded+608
- config.pyAdded+118
- data/NEERAJ_DOCUMENTATION.pdfAdded+3
- data/Research_Paper_Team-2_pdf.pdfAdded+3
- flake8_log.txtAdded
- flake8_output.txtAdded
- models.jsonAdded+1
- reports/classification_report_bert.txtAdded+13
- reports/classification_report_gpt2.txtAdded+13
- reports/classification_report_llama.txtAdded+13
- reports/classification_report_xlnet.txtAdded+13
- reports/confusion_matrix_bert.pngAdded
- reports/confusion_matrix_gpt2.pngAdded
- reports/confusion_matrix_llama.pngAdded
- reports/confusion_matrix_xlnet.pngAdded
- reports/evaluation_summary.jsonAdded+34
- reports/model_comparison.csvAdded+5
- reports/model_comparison.pngAdded
- reports/training_curves.pngAdded
- requirements.txtAdded+41
- runtime.txtAdded+1
- ui/static/.gitkeepAdded
- ui/templates/index.htmlAdded+1320
- vector_store/52aba811-cb31-4a78-97f6-02209a9febcd/data_level0.binAdded+3
- vector_store/52aba811-cb31-4a78-97f6-02209a9febcd/header.binAdded+3
- vector_store/52aba811-cb31-4a78-97f6-02209a9febcd/length.binAdded+3
- vector_store/52aba811-cb31-4a78-97f6-02209a9febcd/link_lists.binAdded+3
- vector_store/chroma.sqlite3Added+3
- wsgi.pyAdded+4
1GROQ_API_KEY=gsk_gmXdBfU3dMebVXTaF6eYWGdyb3FYHY7iaLbBt7YyVWW8peBzGFuq32 unmodified lines33343532 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text32 unmodified lines33343536373832 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -textdata/NEERAJ_DOCUMENTATION.pdf filter=lfs diff=lfs merge=lfs -textdata/Research_Paper_Team-2_pdf.pdf filter=lfs diff=lfs merge=lfs -textvector_store/chroma.sqlite3 filter=lfs diff=lfs merge=lfs -text
12345678venv/__pycache__/*.pyc.envmodels/*/data/*/vector_store/logs/1web: gunicorn wsgi:app --timeout 120 --workers 21234567891011---title: Context-Aware Conversational Intelligence Systememoji: πcolorFrom: indigocolorTo: graysdk: dockerpinned: falselicense: mit---Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250# Context-Aware Conversational Intelligence using Transformer Models**Transforming Unstructured Data into Context-Aware Conversational Intelligence**---## Project OverviewThis system is a modular AI application that combines transformer model experimentation with Retrieval-Augmented Generation (RAG) to create a dual-mode conversational intelligence system.### Dual-Mode Operation1. **Document-Aware Assistant** β Upload PDF/DOCX files, process them into embeddings, and ask contextual questions2. **General Conversational Chatbot** β Ask any question, get explanations, reasoning, and conversational responses (no document required)### Key Capabilities- **Document Upload** β Drag-and-drop PDF/DOCX files for instant analysis- **RAG Pipeline** β Extract text, generate embeddings, store in vector DB, and retrieve relevant context- **Groq Integration** β Use Groq API (e.g., mixtral-8x7b) for fast, contextual answers- **General Chatbot** β Full conversational AI that works even without uploaded documents- **Model Training** β Fine-tune BERT, GPT-2, LLaMA, Mistral, and XLNet on AG News dataset- **Model Evaluation** β Accuracy, precision, recall, F1-score, confusion matrices- **Model Comparison** β Side-by-side performance comparison with charts and best model identification- **Report Generation** β Automated visualizations, training curves, and performance summaries---## System Architecture```User Interface (Flask Web App)|AI Agent Controller|Intelligent Router|+-----+------+-------+| | |Document QA General Chat Classification(RAG Mode) (LLM Mode) (Transformer)| | |ChromaDB Groq API BERT/GPT-2Embeddings LLaMA/Mistral/XLNet```---## Transformer Models| Model | Architecture | Base Model | Parameters | Training ||-------|-------------|-----------|------------|----------|| BERT | Bidirectional Transformer Encoder | bert-base-uncased | 110M | Full fine-tune || GPT-2 | Autoregressive Transformer Decoder | gpt2 | 124M | Full fine-tune || LLaMA | Decoder-based Large Language Model | TinyLlama-1.1B | 1.1B | LoRA (r=8) || Mistral | Transformer with Sliding Window Attention | Mistral-7B-v0.1 / Mistral-7B-Instruct-v0.2 | 7B | HF Inference API (Remote) || XLNet | Permutation-based Autoregressive Transformer | xlnet-base-cased | 110M | Full fine-tune |---## Dataset**AG News** β A 4-class text classification benchmark:| Class | Label ||-------|-------|| World | 0 || Sports | 1 || Business | 2 || Sci/Tech | 3 |- Training samples: 200 (configurable in `config.py`)- Test samples: 50 (configurable in `config.py`)---## Project Structure```project/βββ app.py # Flask web app + RAG engine + General chatbotβββ config.py # Central configurationβββ train.py # Model training (5 transformers) + report generationβββ requirements.txt # Python dependenciesβββ README.md # This fileββββ rag/β βββ __init__.pyβ βββ document_loader.py # PDF/DOCX text extraction & chunkingββββ ui/β βββ templates/β β βββ index.html # Web UI (Chat + Upload + General chatbot)β βββ static/ # Static assetsββββ models/ # Saved model checkpoints (created by train.py)β βββ bert/β βββ gpt2/β βββ llama/β βββ mistral/β βββ xlnet/ββββ data/ # Uploaded documentsβββ reports/ # Generated charts & evaluation reportsβββ vector_store/ # ChromaDB persistent storageβββ logs/ # Application logs```---## Installation### Prerequisites- Python 3.9 or higher- pip package manager- (Optional) NVIDIA GPU with CUDA for faster training- (Optional) Groq API key for enhanced chat responses- (Optional) HuggingFace API key (HF_TOKEN) for Mistral text classification### Setup```bash# 1. Navigate to the project directorycd "d:\major project-2"# 2. Create a virtual environment (recommended)python -m venv venvvenv\Scripts\activate # Windows# source venv/bin/activate # Linux/Mac# 3. Install dependenciespip install -r requirements.txt```---## How to Run### Step 1: Train Models (One-time, Optional)```bashpython train.py```This trains BERT, GPT-2, LLaMA, Mistral, and XLNet on the AG News dataset and generates:- Confusion matrix heatmaps for each model- Model comparison bar chart- Training loss and accuracy curves- Per-class classification reports- JSON evaluation summary- Best model identification### Step 2: Start the Web Application```bashpython app.py```Open your browser at **http://127.0.0.1:8509**### Using the Application#### General Chatbot Mode (No document needed)1. Open the application2. (Optional) Enter your Groq API key in the left panel3. Start chatting β ask any question, get explanations, and conversational responses#### Document Q&A Mode1. **Upload a file** β Drag-and-drop or click "Browse files" to select a PDF or DOCX2. **Enter API Key** β (Optional) Enter your Groq API key for enhanced responses3. **Click Process** β The system extracts text, creates embeddings, and indexes chunks4. **Chat with your file** β Ask questions about the uploaded document5. **Get answers** β The system retrieves relevant chunks and generates contextual answers---## Workflow```User opens applicationβMode A: General Chat Mode B: Document Q&Aβ βUser asks question User uploads document (PDF/DOCX)β βGroq generates User clicks Processgeneral response ββ System extracts text from documentResponse displayed βText split into overlapping chunksβChunks converted to embeddingsβEmbeddings stored in ChromaDBβUser asks question in chatβRetriever finds relevant chunksβLLM generates contextual answerβAnswer displayed in chat```---## Evaluation Metrics- **Accuracy** β Overall correctness- **Precision** β Proportion of correct positive predictions- **Recall** β Proportion of actual positives correctly identified- **F1-Score** β Harmonic mean of precision and recall- **Confusion Matrix** β Detailed prediction breakdown per class---## Generated ReportsAfter running `train.py`, the `reports/` directory will contain:- `confusion_matrix_bert.png` β BERT confusion matrix heatmap- `confusion_matrix_gpt2.png` β GPT-2 confusion matrix heatmap- `confusion_matrix_llama.png` β LLaMA confusion matrix heatmap- `confusion_matrix_mistral.png` β Mistral confusion matrix heatmap- `confusion_matrix_xlnet.png` β XLNet confusion matrix heatmap- `model_comparison.png` β Bar chart comparing all metrics- `training_curves.png` β Training loss and validation accuracy curves- `classification_report_*.txt` β Per-class classification reports- `model_comparison.csv` β Comparison table as CSV- `evaluation_summary.json` β Machine-readable metrics with best model---## ConfigurationEdit `config.py` to customize:- **MAX_SAMPLES_TRAIN / MAX_SAMPLES_TEST** β Dataset size- **MODELS dict** β Learning rate, batch size, epochs per model- **EMBEDDING_MODEL** β Sentence transformer for RAG- **CHUNK_SIZE / TOP_K_RESULTS** β RAG retrieval parameters- **GROQ_MODEL** β Groq model for chat responses (default: mixtral-8x7b-32768)- **PORT** β Web server port (default: 8509)---## LicenseThis project is for educational and research purposes (capstone project).
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608"""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 loggingimport jsonimport osimport sysfrom datetime import datetimefrom collections import dequefrom typing import List, Dict, Any, Optional
from dotenv import load_dotenvload_dotenv()
from flask import Flask, request, jsonify, render_template, send_from_directoryfrom werkzeug.utils import secure_filenamefrom flask_cors import CORSimport chromadbfrom sentence_transformers import SentenceTransformerimport torchfrom transformers import AutoModelForSequenceClassification, AutoTokenizer
# Setup pathsys.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 ---
@app.route("/")def index(): return render_template("index.html")
@app.route("/api/chat", methods=["POST"])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
@app.route("/api/status")def status(): return jsonify({"status": get_agent().memory.get_session_summary()})
@app.route("/api/models")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})
@app.route("/api/results")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})
@app.route("/reports/<path:filename>")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
@app.route("/api/upload", methods=["POST"])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)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118"""Global Configuration for the Conversational Intelligence System.Centralizes all paths, hyperparameters, and model settings."""
import osfrom pathlib import Path
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# PATHS# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββBASE_DIR = Path(__file__).parent.resolve()DATA_DIR = BASE_DIR / "data"MODEL_DIR = BASE_DIR / "models"REPORT_DIR = BASE_DIR / "reports"VECTOR_DB_DIR = BASE_DIR / "vector_store"LOG_DIR = BASE_DIR / "logs"
# Create directoriesfor d in [DATA_DIR, MODEL_DIR, REPORT_DIR, VECTOR_DB_DIR, LOG_DIR]: d.mkdir(parents=True, exist_ok=True)
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# DATASET# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββDATASET_NAME = "ag_news"NUM_CLASSES = 4CLASS_NAMES = ["World", "Sports", "Business", "Sci/Tech"]MAX_SAMPLES_TRAIN = 200 # Small sample for fast automatic demoMAX_SAMPLES_TEST = 50
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# MODEL CONFIGURATIONS# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββMODELS = { "bert": { "name": "bert-base-uncased", "architecture": "Bidirectional Transformer Encoder", "description": "Reads text in both directions simultaneously for strong contextual understanding", "max_length": 128, "batch_size": 16, "learning_rate": 2e-5, "epochs": 3, "weight_decay": 0.01, }, "gpt2": { "name": "gpt2", "architecture": "Autoregressive Transformer Decoder", "description": "Token-by-token text generation with causal attention mechanism", "max_length": 128, "batch_size": 8, "learning_rate": 5e-5, "epochs": 1, "weight_decay": 0.01, }, "llama": { "name": "TinyLlama/TinyLlama-1.1B-Chat-v1.0", "architecture": "Decoder-based Large Language Model", "description": "Efficient transformer architecture with strong reasoning ability", "max_length": 128, "batch_size": 4, "learning_rate": 2e-5, "epochs": 1, "weight_decay": 0.01, "use_lora": True, "lora_r": 8, "lora_alpha": 16, "lora_dropout": 0.1, }, "mistral": { "name": "mistralai/Mistral-7B-v0.1", "architecture": "Transformer with Sliding Window Attention", "description": "Efficient long-context processing with fast inference", "max_length": 128, "batch_size": 2, "learning_rate": 2e-5, "epochs": 1, "weight_decay": 0.01, "use_lora": True, "lora_r": 8, "lora_alpha": 16, "lora_dropout": 0.1, "local_training": False, }, "xlnet": { "name": "xlnet-base-cased", "architecture": "Permutation-based Autoregressive Transformer", "description": "Combines autoregressive and bidirectional modeling for improved contextual understanding", "max_length": 128, "batch_size": 16, "learning_rate": 2e-5, "epochs": 1, "weight_decay": 0.01, },}
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# EMBEDDING / RAG# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββEMBEDDING_MODEL = "all-MiniLM-L6-v2"CHROMA_COLLECTION = "project_knowledge"CHUNK_SIZE = 500CHUNK_OVERLAP = 50TOP_K_RESULTS = 5
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# CONVERSATIONAL AI# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββGROQ_MODEL = "llama-3.1-8b-instant"MAX_RESPONSE_TOKENS = 1000TEMPERATURE = 0.3
# βββββββββββββββββββββοΏ½οΏ½ββββββββββββββββββββββββββββββββββββββββ# SERVER# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββHOST = os.environ.get("HOST", "0.0.0.0")PORT = int(os.environ.get("PORT", "8509"))DEBUG = True123version https://git-lfs.github.com/spec/v1oid sha256:20253d33be8d0b9de100021badf47b250fdf9a177b24dfaba854c7461f00a44dsize 1762361123version https://git-lfs.github.com/spec/v1oid sha256:85ba1b483c1a8fb7a5b5d022eb9c77b8115b636399097819beff5da9d195b0fdsize 5947771["groq/compound-mini", "moonshotai/kimi-k2-instruct", "llama-3.3-70b-versatile", "meta-llama/llama-prompt-guard-2-22m", "openai/gpt-oss-safeguard-20b", "llama-3.1-8b-instant", "groq/compound", "moonshotai/kimi-k2-instruct-0905", "canopylabs/orpheus-v1-english", "whisper-large-v3-turbo", "whisper-large-v3", "qwen/qwen3-32b", "meta-llama/llama-4-scout-17b-16e-instruct", "meta-llama/llama-prompt-guard-2-86m", "meta-llama/llama-guard-4-12b", "openai/gpt-oss-120b", "canopylabs/orpheus-arabic-saudi", "allam-2-7b", "openai/gpt-oss-20b"]12345678910111213Classification Report οΏ½ BERT
============================================================
precision recall f1-score support
World 0.26 1.00 0.41 13
Sports 0.00 0.00 0.00 12
Business 0.00 0.00 0.00 16
Sci/Tech 0.00 0.00 0.00 9
accuracy 0.26 50
macro avg 0.07 0.25 0.10 50
weighted avg 0.07 0.26 0.11 5012345678910111213Classification Report οΏ½ GPT2
============================================================
precision recall f1-score support
World 0.58 0.54 0.56 13
Sports 0.48 0.92 0.63 12
Business 0.47 0.44 0.45 16
Sci/Tech 0.00 0.00 0.00 9
accuracy 0.50 50
macro avg 0.38 0.47 0.41 50
weighted avg 0.42 0.50 0.44 5012345678910111213Classification Report οΏ½ LLAMA
============================================================
precision recall f1-score support
World 0.23 0.38 0.29 13
Sports 0.50 0.08 0.14 12
Business 0.33 0.19 0.24 16
Sci/Tech 0.06 0.11 0.08 9
accuracy 0.20 50
macro avg 0.28 0.19 0.19 50
weighted avg 0.30 0.20 0.20 5012345678910111213Classification Report οΏ½ XLNET
============================================================
precision recall f1-score support
World 0.61 0.85 0.71 13
Sports 0.77 0.83 0.80 12
Business 0.64 0.56 0.60 16
Sci/Tech 0.60 0.33 0.43 9
accuracy 0.66 50
macro avg 0.66 0.64 0.63 50
weighted avg 0.66 0.66 0.65 5012345678910111213141516171819202122232425262728293031323334{
"bert": {
"accuracy": 0.26,
"precision": 0.0676,
"recall": 0.26,
"f1": 0.10730158730158729,
"training_time": 5.911094665527344,
"inference_time": 0.26036643981933594
},
"gpt2": {
"accuracy": 0.5,
"precision": 0.4157826086956522,
"recall": 0.5,
"f1": 0.44097327188940094,
"training_time": 8.525567531585693,
"inference_time": 0.31696391105651855
},
"llama": {
"accuracy": 0.2,
"precision": 0.29634581105169344,
"recall": 0.2,
"f1": 0.19921758241758236,
"training_time": 149.42568850517273,
"inference_time": 2.721841812133789
},
"xlnet": {
"accuracy": 0.66,
"precision": 0.6572185592185592,
"recall": 0.66,
"f1": 0.6456589861751152,
"training_time": 152.64913034439087,
"inference_time": 0.6542069911956787
}
}12345Model,Accuracy,Precision,Recall,F1-Score,Training Time (s)
XLNET,0.66,0.6572185592185592,0.66,0.6456589861751152,152.65
GPT2,0.5,0.4157826086956522,0.5,0.44097327188940094,8.53
LLAMA,0.2,0.29634581105169344,0.2,0.19921758241758236,149.43
BERT,0.26,0.0676,0.26,0.10730158730158729,5.911234567891011121314151617181920212223242526272829303132333435363738394041# Core ML & NLPtorch>=2.0.0transformers>=4.35.0datasets>=2.14.0accelerate>=0.24.0sentencepiece>=0.1.99protobuf>=3.20.0peft>=0.6.0
# Embeddings & Vector Storesentence-transformers>=2.2.0chromadb>=0.4.0
# Web Frameworkflask>=3.0.0flask-cors>=4.0.0werkzeug>=3.0.0
# Document ParsingPyPDF2>=3.0.0python-docx>=1.0.0
# LLM APIgroq>=0.4.0requests>=2.31.0
# Data Processingpandas>=2.0.0numpy>=1.24.0scikit-learn>=1.3.0
# Visualizationmatplotlib>=3.7.0seaborn>=0.12.0
# Utilitiespython-dotenv>=1.0.0tqdm>=4.65.0
# Deploymentgunicorn>=21.2.01python-3.11.0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320<!DOCTYPE html><html lang="en">
<head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>ScholarAI - Conversational Intelligence</title> <meta name="description" content="AI-powered conversational intelligence system using transformer models. Upload documents, ask questions, or chat freely."> <link rel="preconnect" href="https://fonts.googleapis.com"> <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet"> <style> /* ββ RESET & BASE βββββββββββββββββββββββββββββββββ */ * { margin: 0; padding: 0; box-sizing: border-box; }
:root { --bg-primary: #f8f9fa; --bg-secondary: #ffffff; --bg-tertiary: #f1f3f5; --bg-card: #ffffff; --bg-hover: #e9ecef; --accent: #228be6; --accent-light: #4dabf7; --accent-glow: rgba(34, 139, 230, 0.15); --text-primary: #212529; --text-secondary: #495057; --text-muted: #868e96; --border: #dee2e6; --border-light: #e9ecef; --success: #12b886; --error: #fa5252; --warning: #fcc419; --gradient-accent: linear-gradient(135deg, #1c7ed6 0%, #339af0 100%); --gradient-bg: linear-gradient(180deg, #f8f9fa 0%, #ffffff 100%); --glass: rgba(255, 255, 255, 0.9); --glass-border: rgba(0, 0, 0, 0.05); --shadow-sm: 0 2px 4px rgba(0, 0, 0, 0.05); --shadow-md: 0 4px 12px rgba(0, 0, 0, 0.08); --shadow-glow: 0 0 15px rgba(34, 139, 230, 0.15); --radius-sm: 8px; --radius-md: 12px; --radius-lg: 16px; --radius-xl: 24px; }
body { font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; background: var(--bg-primary); color: var(--text-primary); min-height: 100vh; overflow: hidden; }
/* ββ LAYOUT βββββββββββββββββββββββββββββββββββββββ */ .app-shell { display: flex; height: 100vh; overflow: hidden; }
/* ββ LEFT PANEL (Upload) ββββββββββββββββββββββββββ */ .upload-panel { width: 340px; min-width: 340px; background: var(--bg-secondary); border-right: 1px solid var(--border); display: flex; flex-direction: column; padding: 24px 22px; overflow-y: auto; position: relative; transition: transform 0.3s ease; }
.upload-panel.collapsed { transform: translateX(-100%); position: absolute; z-index: -1; }
.panel-header { display: flex; align-items: center; justify-content: space-between; margin-bottom: 24px; }
.panel-logo { display: flex; align-items: center; gap: 10px; }
.logo-icon { width: 36px; height: 36px; background: var(--gradient-accent); border-radius: var(--radius-sm); display: flex; align-items: center; justify-content: center; font-size: 18px; box-shadow: var(--shadow-glow); }
.logo-text { font-size: 15px; font-weight: 700; color: var(--accent); letter-spacing: -0.3px; }
.close-btn { width: 30px; height: 30px; border: 1px solid var(--border); background: transparent; font-size: 16px; color: var(--text-muted); cursor: pointer; border-radius: var(--radius-sm); display: flex; align-items: center; justify-content: center; transition: all 0.2s; }
.close-btn:hover { background: var(--bg-hover); color: var(--text-primary); border-color: var(--border-light); }
.upload-panel h2 { font-size: 13px; font-weight: 600; color: var(--text-secondary); text-transform: uppercase; letter-spacing: 0.8px; margin-bottom: 14px; }
/* Drop Zone */ .drop-zone { border: 2px dashed var(--border-light); border-radius: var(--radius-lg); padding: 28px 18px; text-align: center; cursor: pointer; transition: all 0.3s ease; background: var(--bg-tertiary); margin-bottom: 8px; position: relative; }
.drop-zone:hover { border-color: var(--accent); background: rgba(108, 92, 231, 0.05); }
.drop-zone.drag-over { border-color: var(--accent); background: var(--accent-glow); box-shadow: var(--shadow-glow); }
.drop-icon { font-size: 32px; margin-bottom: 10px; display: block; opacity: 0.7; }
.drop-zone-text { font-size: 13px; font-weight: 500; color: var(--text-secondary); margin-bottom: 4px; }
.drop-zone-hint { font-size: 11px; color: var(--text-muted); margin-bottom: 14px; }
.browse-btn { display: inline-block; padding: 7px 18px; border: 1px solid var(--border-light); border-radius: var(--radius-sm); background: var(--bg-hover); color: var(--text-secondary); font-size: 12px; font-weight: 500; cursor: pointer; transition: all 0.2s; font-family: inherit; }
.browse-btn:hover { background: var(--accent); color: white; border-color: var(--accent); }
.hidden-input { display: none; }
/* File Preview */ .file-preview { display: none; background: var(--bg-tertiary); border: 1px solid var(--border); border-radius: var(--radius-md); padding: 10px 12px; margin-top: 12px; margin-bottom: 4px; align-items: center; gap: 10px; }
.file-preview.visible { display: flex; }
.file-icon { width: 36px; height: 36px; background: var(--accent-glow); border-radius: var(--radius-sm); display: flex; align-items: center; justify-content: center; flex-shrink: 0; }
.file-icon svg { width: 18px; height: 18px; color: var(--accent-light); }
.file-info { flex: 1; min-width: 0; }
.file-name { font-size: 12px; font-weight: 500; color: var(--text-primary); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.file-size { font-size: 10px; color: var(--text-muted); }
.file-remove { width: 24px; height: 24px; border: none; background: transparent; color: var(--text-muted); cursor: pointer; font-size: 14px; border-radius: 4px; display: flex; align-items: center; justify-content: center; flex-shrink: 0; transition: all 0.2s; }
.file-remove:hover { background: rgba(253, 121, 168, 0.15); color: var(--error); }
/* Section Divider */ .section-divider { height: 1px; background: var(--border); margin: 20px 0; }
/* API Key */ .api-section { margin-top: 4px; }
.api-label { font-size: 13px; font-weight: 600; color: var(--text-secondary); text-transform: uppercase; letter-spacing: 0.8px; margin-bottom: 10px; display: block; }
.api-input-wrapper { position: relative; display: flex; align-items: center; }
.api-input { width: 100%; padding: 10px 38px 10px 12px; border: 1px solid var(--border); border-radius: var(--radius-sm); font-size: 12px; font-family: 'Courier New', monospace; color: var(--text-primary); background: var(--bg-tertiary); outline: none; transition: all 0.2s; }
.api-input:focus { border-color: var(--accent); box-shadow: 0 0 0 3px var(--accent-glow); }
.api-input::placeholder { color: var(--text-muted); }
.toggle-eye { position: absolute; right: 8px; background: none; border: none; cursor: pointer; color: var(--text-muted); font-size: 14px; padding: 4px; }
.toggle-eye:hover { color: var(--text-secondary); }
/* Process Button */ .process-btn { margin-top: 18px; width: 100%; padding: 11px 24px; border: none; border-radius: var(--radius-sm); background: var(--accent); color: white; font-size: 13px; font-weight: 600; cursor: pointer; font-family: inherit; transition: all 0.25s; position: relative; overflow: hidden; }
.process-btn::before { content: ''; position: absolute; top: 0; left: -100%; width: 100%; height: 100%; background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.1), transparent); transition: left 0.5s; }
.process-btn:hover::before { left: 100%; }
.process-btn:hover { background: #5b4bd5; transform: translateY(-1px); box-shadow: 0 4px 15px rgba(108, 92, 231, 0.4); }
.process-btn:disabled { opacity: 0.5; cursor: not-allowed; transform: none; }
.process-btn.processing { background: var(--warning); color: #333; }
.upload-status { font-size: 11px; margin-top: 10px; color: var(--text-muted); min-height: 16px; text-align: center; }
.upload-status.success { color: var(--success); }
.upload-status.error { color: var(--error); }
/* Panel Footer Info */ .panel-footer { margin-top: auto; padding-top: 16px; border-top: 1px solid var(--border); }
.panel-footer p { font-size: 11px; color: var(--text-muted); line-height: 1.6; }
.panel-footer .mode-badge { display: inline-block; padding: 2px 8px; border-radius: 10px; font-size: 10px; font-weight: 600; margin-top: 6px; }
.mode-badge.rag { background: rgba(0, 206, 201, 0.15); color: var(--success); }
.mode-badge.general { background: rgba(108, 92, 231, 0.15); color: var(--accent-light); }
/* ββ RIGHT PANEL (Chat) βββββββββββββββββββββββββββ */ .chat-panel { flex: 1; display: flex; flex-direction: column; background: var(--bg-primary); position: relative; }
/* Accent bar */ .accent-bar { height: 3px; background: var(--gradient-accent); flex-shrink: 0; }
/* Top bar */ .top-bar { padding: 10px 24px; border-bottom: 1px solid var(--border); display: flex; justify-content: space-between; align-items: center; background: var(--bg-secondary); flex-shrink: 0; }
.top-bar-left { display: flex; align-items: center; gap: 12px; }
.menu-btn { width: 34px; height: 34px; border: 1px solid var(--border); background: transparent; color: var(--text-secondary); cursor: pointer; border-radius: var(--radius-sm); display: flex; align-items: center; justify-content: center; font-size: 16px; transition: all 0.2s; }
.menu-btn:hover { background: var(--bg-hover); color: var(--text-primary); }
.chat-title { font-size: 14px; font-weight: 600; color: var(--text-primary); }
.chat-subtitle { font-size: 11px; color: var(--text-muted); }
.mode-indicator { padding: 4px 12px; border-radius: 20px; font-size: 11px; font-weight: 600; transition: all 0.3s; }
.mode-indicator.general-mode { background: var(--bg-tertiary); color: var(--text-secondary); border: 1px solid var(--border); }
.mode-indicator.doc-mode { background: rgba(18, 184, 134, 0.15); color: var(--success); border: 1px solid rgba(18, 184, 134, 0.3); }
/* Chat Messages Area */ .chat-messages { flex: 1; overflow-y: auto; padding: 24px 32px; scroll-behavior: smooth; }
/* Welcome Screen */ .welcome-screen { display: flex; flex-direction: column; align-items: center; justify-content: center; height: 100%; text-align: center; padding: 40px; }
.welcome-icon { font-size: 48px; margin-bottom: 20px; animation: float 3s ease-in-out infinite; }
@keyframes float { 0%, 100% { transform: translateY(0px); } 50% { transform: translateY(-10px); } }
.welcome-title { font-size: 22px; font-weight: 700; color: var(--text-primary); margin-bottom: 8px; background: var(--gradient-accent); -webkit-background-clip: text; -webkit-text-fill-color: transparent; background-clip: text; }
.welcome-subtitle { font-size: 14px; color: var(--text-secondary); max-width: 480px; line-height: 1.6; margin-bottom: 28px; }
.quick-actions { display: flex; flex-wrap: wrap; gap: 10px; justify-content: center; }
.quick-action { padding: 10px 18px; border: 1px solid var(--border-light); border-radius: var(--radius-xl); background: var(--bg-card); color: var(--text-secondary); font-size: 13px; cursor: pointer; transition: all 0.2s; font-family: inherit; }
.quick-action:hover { border-color: var(--accent); color: var(--accent-light); background: var(--accent-glow); transform: translateY(-2px); box-shadow: var(--shadow-glow); }
.quick-action .qa-icon { margin-right: 6px; }
/* Message Styles */ .msg { max-width: 760px; margin: 0 auto 16px; display: flex; gap: 12px; animation: slideUp 0.35s ease; }
@keyframes slideUp { from { opacity: 0; transform: translateY(12px); } to { opacity: 1; transform: translateY(0); } }
.msg.user-msg { justify-content: flex-end; }
.msg.bot-msg { justify-content: flex-start; }
.msg-avatar { width: 32px; height: 32px; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-size: 16px; flex-shrink: 0; margin-top: 2px; }
.msg.user-msg .msg-avatar { order: 2; }
.user-avatar { background: var(--accent-glow); border: 1px solid rgba(34, 139, 230, 0.3); }
.bot-avatar { background: var(--bg-tertiary); border: 1px solid var(--border); }
.msg-bubble { padding: 14px 18px; border-radius: var(--radius-lg); font-size: 13.5px; line-height: 1.7; max-width: 75%; word-wrap: break-word; }
.msg.user-msg .msg-bubble { background: var(--accent); color: white; border-bottom-right-radius: 4px; }
.msg.bot-msg .msg-bubble { background: var(--bg-card); color: var(--text-primary); border: 1px solid var(--border); border-bottom-left-radius: 4px; }
.msg-bubble strong { font-weight: 600; color: var(--accent); }
.msg-bubble table { border-collapse: collapse; margin: 8px 0; font-size: 12px; width: 100%; }
.msg-bubble table th, .msg-bubble table td { border: 1px solid var(--border-light); padding: 6px 10px; text-align: left; }
.msg-bubble table th { background: var(--bg-tertiary); font-weight: 600; }
/* Typing dots */ .typing-dots { display: flex; gap: 5px; padding: 8px 0; }
.typing-dots span { width: 7px; height: 7px; border-radius: 50%; background: var(--accent); animation: bounce 1.4s infinite; }
.typing-dots span:nth-child(2) { animation-delay: 0.15s; }
.typing-dots span:nth-child(3) { animation-delay: 0.3s; }
@keyframes bounce { 0%, 60%, 100% { transform: translateY(0); opacity: 0.3; } 30% { transform: translateY(-8px); opacity: 1; } }
/* ββ CHAT INPUT βββββββββββββββββββββββββββββββββββ */ .chat-input-area { padding: 16px 32px 24px; border-top: 1px solid var(--border); background: var(--bg-secondary); flex-shrink: 0; }
.chat-input-wrapper { max-width: 760px; margin: 0 auto; display: flex; align-items: center; gap: 10px; background: var(--bg-tertiary); border: 1px solid var(--border); border-radius: var(--radius-xl); padding: 4px 6px 4px 20px; transition: all 0.2s; }
.chat-input-wrapper:focus-within { border-color: var(--accent); box-shadow: 0 0 0 3px var(--accent-glow); }
.chat-input { flex: 1; border: none; background: transparent; font-size: 14px; font-family: inherit; color: var(--text-primary); outline: none; padding: 10px 0; }
.chat-input::placeholder { color: var(--text-muted); }
.input-actions { display: flex; align-items: center; gap: 4px; }
.attach-btn { width: 34px; height: 34px; border: none; background: transparent; cursor: pointer; color: var(--text-muted); font-size: 18px; border-radius: 50%; display: flex; align-items: center; justify-content: center; transition: all 0.2s; }
.attach-btn:hover { background: var(--accent-glow); color: var(--accent-light); }
.send-btn { width: 38px; height: 38px; border: none; background: var(--accent); cursor: pointer; color: #fff; font-size: 16px; border-radius: 50%; display: flex; align-items: center; justify-content: center; transition: all 0.25s; }
.send-btn:hover { background: #5b4bd5; transform: scale(1.08); box-shadow: 0 0 20px rgba(108, 92, 231, 0.4); }
.send-btn:disabled { opacity: 0.3; cursor: not-allowed; transform: none; box-shadow: none; }
/* Scrollbar */ ::-webkit-scrollbar { width: 6px; }
::-webkit-scrollbar-track { background: transparent; }
::-webkit-scrollbar-thumb { background: var(--border-light); border-radius: 3px; }
::-webkit-scrollbar-thumb:hover { background: var(--text-muted); }
/* Responsive */ @media (max-width: 768px) { .upload-panel { width: 100%; min-width: 100%; position: absolute; z-index: 10; height: 100%; }
.upload-panel.hidden-mobile { display: none; }
.chat-messages { padding: 16px; }
.chat-input-area { padding: 12px 16px 20px; } } </style></head>
<body> <div class="app-shell"> <!-- LEFT PANEL: Upload & Configuration --> <aside class="upload-panel" id="uploadPanel"> <div class="panel-header"> <div class="panel-logo"> <div class="logo-icon">⚡</div> <span class="logo-text">ScholarAI</span> </div> <button class="close-btn" onclick="togglePanel()" title="Close panel">×</button> </div>
<h2>Upload Document</h2>
<!-- Drop Zone --> <div class="drop-zone" id="dropZone" onclick="document.getElementById('fileInput').click()"> <span class="drop-icon">📄</span> <div class="drop-zone-text">Drag and drop your file here</div> <div class="drop-zone-hint">Up to 200MB • PDF, DOCX</div> <button class="browse-btn" type="button" onclick="event.stopPropagation(); document.getElementById('fileInput').click()">Browse files</button> </div> <input type="file" id="fileInput" class="hidden-input" accept=".pdf,.docx" />
<!-- File Preview --> <div class="file-preview" id="filePreview"> <div class="file-icon"> <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"> <path d="M14 2H6a2 2 0 00-2 2v16a2 2 0 002 2h12a2 2 0 002-2V8z" /> <polyline points="14,2 14,8 20,8" /> </svg> </div> <div class="file-info"> <div class="file-name" id="fileName">-</div> <div class="file-size" id="fileSize">-</div> </div> <button class="file-remove" onclick="removeFile()" title="Remove file">×</button> </div>
<!-- Process Button --> <button class="process-btn" id="processBtn" onclick="processDocument()">⚡ Process Document</button> <div class="upload-status" id="uploadStatus"></div>
<!-- Panel Footer --> <div class="panel-footer"> <p>Upload a document for contextual Q&A, or just start chatting for general conversation.</p> <span class="mode-badge general" id="modeBadge">● General Mode</span> </div> </aside>
<!-- RIGHT PANEL: Chat --> <main class="chat-panel"> <div class="accent-bar"></div> <div class="top-bar"> <div class="top-bar-left"> <button class="menu-btn" onclick="togglePanel()" title="Toggle sidebar">☰</button> <div> <div class="chat-title">ScholarAI</div> <div class="chat-subtitle">Context-Aware AI Assistant</div> </div> </div> <div class="mode-indicator general-mode" id="modeIndicator">💬 General Chat</div> </div>
<div class="chat-messages" id="chatMessages"> <!-- Welcome Screen --> <div class="welcome-screen" id="welcomeScreen"> <div class="welcome-icon">🤖</div> <div class="welcome-title">ScholarAI</div> <div class="welcome-subtitle"> I'm ScholarAI, your context-aware assistant powered by transformer models. You can chat, upload documents, or classify text using BERT, GPT-2, LLaMA, and XLNet by typing <strong>'classify using [model]: [text]'</strong>. </div> <div class="quick-actions"> <button class="quick-action" onclick="quickChat('What can you do?')"> <span class="qa-icon">💡</span>What can you do? </button> <button class="quick-action" onclick="quickChat('classify using bert: A new artificial intelligence model was just released.')"> <span class="qa-icon">🧠</span>Classify with BERT </button> <button class="quick-action" onclick="quickChat('Show model results')"> <span class="qa-icon">📊</span>Model comparison </button> <button class="quick-action" onclick="quickChat('What is RAG?')"> <span class="qa-icon">📚</span>What is RAG? </button> </div> </div> </div>
<div class="chat-input-area"> <div class="chat-input-wrapper"> <input type="text" id="chatInput" class="chat-input" placeholder="Ask anything..." onkeydown="handleChatKey(event)" /> <div class="input-actions"> <button class="attach-btn" title="Attach file" onclick="document.getElementById('fileInput').click()">📎</button> <button class="send-btn" id="sendBtn" onclick="sendChat()" title="Send">➤</button> </div> </div> </div> </main> </div>
<script> // ββ STATE ββββββββββββββββββββββββββββββββββββββββββ let selectedFile = null; let isProcessing = false; let documentReady = false; let apiKeySet = false;
// ββ DOM REFS βββββββββββββββββββββββββββββββββββββββ const dropZone = document.getElementById('dropZone'); const fileInput = document.getElementById('fileInput'); const filePreview = document.getElementById('filePreview'); const fileName = document.getElementById('fileName'); const fileSize = document.getElementById('fileSize'); const processBtn = document.getElementById('processBtn'); const uploadStatus = document.getElementById('uploadStatus'); const chatMessages = document.getElementById('chatMessages'); const chatInput = document.getElementById('chatInput'); const sendBtn = document.getElementById('sendBtn'); const welcomeScreen = document.getElementById('welcomeScreen'); const modeIndicator = document.getElementById('modeIndicator'); const modeBadge = document.getElementById('modeBadge');
// ββ DRAG & DROP ββββββββββββββββββββββββββββββββββββ ['dragenter', 'dragover'].forEach(ev => { dropZone.addEventListener(ev, e => { e.preventDefault(); e.stopPropagation(); dropZone.classList.add('drag-over'); }); });
['dragleave', 'drop'].forEach(ev => { dropZone.addEventListener(ev, e => { e.preventDefault(); e.stopPropagation(); dropZone.classList.remove('drag-over'); }); });
dropZone.addEventListener('drop', e => { const files = e.dataTransfer.files; if (files.length > 0) { handleFileSelect(files[0]); } });
fileInput.addEventListener('change', () => { if (fileInput.files.length > 0) { handleFileSelect(fileInput.files[0]); } });
function handleFileSelect(file) { const ext = file.name.split('.').pop().toLowerCase(); if (!['pdf', 'docx'].includes(ext)) { showStatus('Only PDF and DOCX files are supported.', 'error'); return; } if (file.size > 200 * 1024 * 1024) { showStatus('File exceeds 200MB limit.', 'error'); return; }
selectedFile = file; fileName.textContent = file.name; fileSize.textContent = formatBytes(file.size); filePreview.classList.add('visible'); showStatus(''); }
function removeFile() { selectedFile = null; fileInput.value = ''; filePreview.classList.remove('visible'); showStatus(''); }
function formatBytes(bytes) { if (bytes === 0) return '0 Bytes'; const k = 1024; const sizes = ['Bytes', 'KB', 'MB', 'GB']; const i = Math.floor(Math.log(bytes) / Math.log(k)); return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i]; }
// ββ PROCESS DOCUMENT βββββββββββββββββββββββββββββββ async function processDocument() { if (!selectedFile) { showStatus('Please select a file first.', 'error'); return; }
isProcessing = true; processBtn.disabled = true; processBtn.classList.add('processing'); processBtn.textContent = 'Processing...'; showStatus('Extracting text & generating embeddings...', '');
const formData = new FormData(); formData.append('file', selectedFile);
try { const res = await fetch('/api/upload', { method: 'POST', body: formData }); const data = await res.json();
if (data.error) { showStatus('Error: ' + data.error, 'error'); } else { showStatus('Document processed successfully!', 'success'); documentReady = true; chatInput.placeholder = 'Ask about your document or anything else...';
// Update mode indicators setMode('doc');
// Hide welcome if (welcomeScreen) welcomeScreen.style.display = 'none';
addBotMessage(data.message); } } catch (err) { showStatus('Connection error. Is the server running?', 'error'); }
isProcessing = false; processBtn.disabled = false; processBtn.classList.remove('processing'); processBtn.innerHTML = '⚡ Process Document'; }
// ββ MODE INDICATOR βββββββββββββββββββββββββββββββββ function setMode(mode) { if (mode === 'doc') { modeIndicator.className = 'mode-indicator doc-mode'; modeIndicator.innerHTML = '📄 Document Mode'; modeBadge.className = 'mode-badge rag'; modeBadge.innerHTML = '● Document Mode'; } else { modeIndicator.className = 'mode-indicator general-mode'; modeIndicator.innerHTML = '💬 General Chat'; modeBadge.className = 'mode-badge general'; modeBadge.innerHTML = '● General Mode'; } }
// ββ CHAT βββββββββββββββββββββββββββββββββββββββββββ function handleChatKey(e) { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); sendChat(); } }
function quickChat(text) { chatInput.value = text; sendChat(); }
async function sendChat() { const msg = chatInput.value.trim(); if (!msg || isProcessing) return;
if (welcomeScreen) welcomeScreen.style.display = 'none';
addUserMessage(msg); chatInput.value = '';
isProcessing = true; sendBtn.disabled = true;
const typingId = addTypingIndicator();
try { const res = await fetch('/api/chat', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ message: msg }) }); const data = await res.json(); removeTyping(typingId);
if (data.error) { addBotMessage('Error: ' + data.error); } else { addBotMessage(data.response); } } catch (err) { removeTyping(typingId); addBotMessage('Connection error. Please ensure the server is running.'); }
isProcessing = false; sendBtn.disabled = false; chatInput.focus(); }
function addUserMessage(text) { const div = document.createElement('div'); div.className = 'msg user-msg'; div.innerHTML = ` <div class="msg-bubble">${escapeHtml(text)}</div> <div class="msg-avatar user-avatar">👤</div> `; chatMessages.appendChild(div); scrollToBottom(); }
function addBotMessage(text) { const div = document.createElement('div'); div.className = 'msg bot-msg'; div.innerHTML = ` <div class="msg-avatar bot-avatar">🤖</div> <div class="msg-bubble">${formatResponse(text)}</div> `; chatMessages.appendChild(div); scrollToBottom(); }
function addTypingIndicator() { const id = 'typing-' + Date.now(); const div = document.createElement('div'); div.className = 'msg bot-msg'; div.id = id; div.innerHTML = ` <div class="msg-avatar bot-avatar">🤖</div> <div class="msg-bubble"> <div class="typing-dots"><span></span><span></span><span></span></div> </div> `; chatMessages.appendChild(div); scrollToBottom(); return id; }
function removeTyping(id) { const el = document.getElementById(id); if (el) el.remove(); }
function scrollToBottom() { requestAnimationFrame(() => { chatMessages.scrollTop = chatMessages.scrollHeight; }); }
function escapeHtml(text) { const d = document.createElement('div'); d.textContent = text; return d.innerHTML; }
function formatResponse(text) { let html = escapeHtml(text); // Bold **text** html = html.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>'); // Markdown-style table rendering if (html.includes('|') && html.includes('---')) { html = renderMarkdownTable(html); } // Bullet points html = html.replace(/^- (.*)/gm, '• $1'); // Newlines html = html.replace(/\n/g, '<br>'); return html; }
function renderMarkdownTable(html) { const lines = html.split('\n'); let tableHtml = ''; let inTable = false; let result = [];
for (let i = 0; i < lines.length; i++) { const line = lines[i].trim(); if (line.startsWith('|') && line.endsWith('|')) { if (!inTable) { inTable = true; tableHtml = '<table>'; } // Skip separator line if (line.replace(/[\|\s\-:]/g, '') === '') continue;
const cells = line.split('|').filter(c => c.trim() !== ''); const isHeader = !tableHtml.includes('<tr>'); const tag = isHeader ? 'th' : 'td'; tableHtml += '<tr>' + cells.map(c => `<${tag}>${c.trim()}</${tag}>`).join('') + '</tr>'; } else { if (inTable) { tableHtml += '</table>'; result.push(tableHtml); tableHtml = ''; inTable = false; } result.push(line); } } if (inTable) { tableHtml += '</table>'; result.push(tableHtml); } return result.join('\n'); }
// ββ PANEL TOGGLE βββββββββββββββββββββββββββββββββββ function togglePanel() { const panel = document.getElementById('uploadPanel'); panel.classList.toggle('hidden-mobile'); }
// ββ STATUS HELPER ββββββββββββββββββββββββββββββββββ function showStatus(msg, type) { uploadStatus.textContent = msg; uploadStatus.className = 'upload-status' + (type ? ' ' + type : ''); }
// ββ FOCUS CHAT INPUT ON LOAD βββββββββββββββββββββββ window.addEventListener('load', () => { chatInput.focus(); }); </script></body>
</html>123version https://git-lfs.github.com/spec/v1oid sha256:ea9ac6972cb4666769a17755f17c5727f676f11a742e9553bf3a21119ab54394size 167600123version https://git-lfs.github.com/spec/v1oid sha256:a0e81c3b22454233bc12d0762f06dcca48261a75231cf87c79b75e69a6c00150size 100123version https://git-lfs.github.com/spec/v1oid sha256:85e6a69d79dcde9634457d9a56f27eeb0ad315b848668133353a810b6d66fd6esize 400123version https://git-lfs.github.com/spec/v1oid sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855size 0123version https://git-lfs.github.com/spec/v1oid sha256:6d9d6c72876311bd7e02ee98cb4bf8962230334d2f1c1b2028fa219bfd6cb0d0size 25763841234from app import app
if __name__ == "__main__": app.run().envAdded+1
.gitattributes+3
.gitignoreAdded+8
ProcfileAdded+1
README.md+247-8
__pycache__/app.cpython-313.pycAdded
__pycache__/config.cpython-313.pycAdded
app.pyAdded+608
config.pyAdded+118
data/NEERAJ_DOCUMENTATION.pdfAdded+3
data/Research_Paper_Team-2_pdf.pdfAdded+3
flake8_log.txtAdded
flake8_output.txtAdded
models.jsonAdded+1
reports/classification_report_bert.txtAdded+13
reports/classification_report_gpt2.txtAdded+13
reports/classification_report_llama.txtAdded+13
reports/classification_report_xlnet.txtAdded+13
reports/confusion_matrix_bert.pngAdded

reports/confusion_matrix_gpt2.pngAdded

reports/confusion_matrix_llama.pngAdded

reports/confusion_matrix_xlnet.pngAdded

reports/evaluation_summary.jsonAdded+34
reports/model_comparison.csvAdded+5
reports/model_comparison.pngAdded

reports/training_curves.pngAdded

requirements.txtAdded+41
runtime.txtAdded+1
ui/static/.gitkeepAdded
ui/templates/index.htmlAdded+1320
vector_store/52aba811-cb31-4a78-97f6-02209a9febcd/data_level0.binAdded+3
vector_store/52aba811-cb31-4a78-97f6-02209a9febcd/header.binAdded+3
vector_store/52aba811-cb31-4a78-97f6-02209a9febcd/length.binAdded+3
vector_store/52aba811-cb31-4a78-97f6-02209a9febcd/link_lists.binAdded+3
vector_store/chroma.sqlite3Added+3
wsgi.pyAdded+4