{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "6cade155", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "d:\\projects\\doc-intelligence-rag\\.venv\\Scripts\\python.exe\n" ] } ], "source": [ "import sys\n", "sys.path.append(\"../\")\n", "print(sys.executable)" ] }, { "cell_type": "code", "execution_count": 3, "id": "8b183487", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Loaded .env from: d:\\projects\\doc-intelligence-rag\\notebooks\\..\\src\\rag\\../..\\.env\n", "✓ Chunker works: 6 chunks\n", "Split into 6 chunks:\n", " Chunk 0: 12 words | Machine Learning is a subset of artificial intelligence that\n", " Chunk 1: 12 words | training models to make predictions or decisions based on da\n", " Chunk 2: 12 words | It is a powerful tool for solving a wide range of problems,\n", " Chunk 3: 12 words | of problems, from image recognition to natural language proc\n", " Chunk 4: 12 words | this article, we will explore the basics of machine learning\n", " Chunk 5: 10 words | and how it can be used to solve real-world problems.\n" ] } ], "source": [ "# Test chunker\n", "from src.rag import chunk_text\n", "\n", "text = \"Machine Learning is a subset of artificial intelligence that involves training models to make predictions or decisions based on data. It is a powerful tool for solving a wide range of problems, from image recognition to natural language processing. In this article, we will explore the basics of machine learning and how it can be used to solve real-world problems.\"\n", "chunks = chunk_text(text, chunk_size=12, overlap=2)\n", "print(f\"✓ Chunker works: {len(chunks)} chunks\")\n", "print(f\"Split into {len(chunks)} chunks:\")\n", "for chunk in chunks:\n", " print(f\" Chunk {chunk.chunk_id}: {chunk.word_count} words | {chunk.text[:60]}\")" ] }, { "cell_type": "code", "execution_count": 4, "id": "f4c201be", "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "INFO:src.rag.embeddings:✓ Connected to Ollama at http://localhost:11434\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "✓ Embeddings work: 768 dimensions\n" ] } ], "source": [ "# check embeddings\n", "\n", "from src.rag import OllamaEmbeddingClient\n", "\n", "client = OllamaEmbeddingClient()\n", "embedding = client.embed(text)\n", "print(f\"✓ Embeddings work: {len(embedding)} dimensions\")" ] }, { "cell_type": "code", "execution_count": 5, "id": "04144e58", "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "INFO:chromadb.telemetry.product.posthog:Anonymized telemetry enabled. See https://docs.trychroma.com/telemetry for more information.\n", "INFO:src.rag.vector_store:✓ Initialized Chroma vector store at .chromadb_test (collection: rag)\n", "INFO:src.rag.vector_store:Cleared vector store\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Chunk ID: chunk1, Similarity: 1.00, Text: ml\n" ] } ], "source": [ "# check vector store\n", "\n", "from src.rag import ChromaVectorStore\n", "\n", "store = ChromaVectorStore(persist_directory=\".chromadb_test\")\n", "store.clear()\n", "# Add chunks\n", "store.add(\"chunk1\", \"ml\", embedding, metadata={\"source\": \"test\"})\n", "\n", "# Retrieve\n", "results = store.retrieve(embedding, top_k=1)\n", "for r in results:\n", " print(f\"Chunk ID: {r.chunk_id}, Similarity: {r.similarity:.2f}, Text: {r.text}\")\n" ] }, { "cell_type": "code", "execution_count": 6, "id": "80ccd988", "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "INFO:src.rag.llm:Groq LLM client initialized with model: llama-3.1-8b-instant\n", "INFO:httpx:HTTP Request: POST https://api.groq.com/openai/v1/chat/completions \"HTTP/1.1 200 OK\"\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "✓ LLM works: I am a helpful assistant....\n" ] } ], "source": [ "# test groq llm\n", "from src.rag import GroqLLMClient\n", "import os\n", "from dotenv import load_dotenv\n", "load_dotenv()\n", "api_key = os.getenv(\"GROQ_API_KEY\")\n", "\n", "llm = GroqLLMClient(api_key=api_key)\n", "answer = llm.query(\"Context: Hello\", \"Query: Who are you?\")\n", "print(f\"✓ LLM works: {answer[:50]}...\")" ] }, { "cell_type": "code", "execution_count": 7, "id": "6c95cec2", "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "INFO:src.rag.pipeline:Initializing RAG Pipeline...\n", "INFO:src.rag.embeddings:✓ Connected to Ollama at http://localhost:11434\n", "INFO:src.rag.pipeline:✓ Embeddings client ready\n", "INFO:src.rag.llm:Groq LLM client initialized with model: llama-3.1-8b-instant\n", "INFO:src.rag.pipeline:✓ LLM client ready\n", "INFO:chromadb.telemetry.product.posthog:Anonymized telemetry enabled. See https://docs.trychroma.com/telemetry for more information.\n", "INFO:src.rag.vector_store:✓ Initialized Chroma vector store at .chromadb (collection: rag)\n", "INFO:src.rag.pipeline:✓ Vector store ready\n", "INFO:src.rag.pipeline:✓ RAG Pipeline initialized\n", "INFO:src.rag.pipeline:Ingesting document: doc1\n", "INFO:src.rag.pipeline:✓ Chunks created: 1\n", "INFO:src.rag.pipeline:✓ Embedded 1/1 chunks\n", "INFO:src.rag.pipeline:Querying: What will you explore?\n", "INFO:httpx:HTTP Request: POST https://api.groq.com/openai/v1/chat/completions \"HTTP/1.1 200 OK\"\n", "INFO:src.rag.pipeline:Query complete: success\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "✓ Pipeline works!\n", "Answer: Based on the provided context, it's not explicitly stated what will be explored.\n" ] } ], "source": [ "#test full pipeline\n", "from src.rag import RAGPipeline\n", "\n", "pipeline = RAGPipeline()\n", "pipeline.ingest(\"doc1\", text)\n", "result = pipeline.query(\"What will you explore?\")\n", "print(f\"✓ Pipeline works!\")\n", "print(f\"Answer: {result['answer']}\")" ] }, { "cell_type": "code", "execution_count": 6, "id": "b6aa9c72", "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "INFO:src.rag.pipeline:Initializing RAG Pipeline...\n", "INFO:src.rag.embeddings:✓ Connected to Ollama at http://localhost:11434\n", "INFO:src.rag.pipeline:✓ Embeddings client ready\n", "INFO:src.rag.llm:Groq LLM client initialized with model: llama-3.1-8b-instant\n", "INFO:src.rag.pipeline:✓ LLM client ready\n", "INFO:src.rag.vector_store:✓ Initialized Chroma vector store at .chromadb (collection: rag)\n", "INFO:src.rag.pipeline:✓ Vector store ready\n", "INFO:src.rag.pipeline:✓ RAG Pipeline initialized\n", "INFO:src.rag.pdf_processor:Processing folder: d:\\projects\\doc-intelligence-rag\\papers\n", "INFO:src.rag.pdf_processor:Found 3 PDF files\n", "INFO:src.rag.pdf_processor:Processing PDF: CMBFSCNN.pdf\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "[1] Ingesting all PDFs from 'papers' folder...\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "INFO:src.rag.pdf_processor:✓ Extracted 26 pages, 90013 chars\n", "INFO:src.rag.pdf_processor:Processing PDF: CVPR Version 16723_CMB_ML_A_Cosmic_Microwav.pdf\n", "INFO:src.rag.pdf_processor:✓ Extracted 11 pages, 53068 chars\n", "INFO:src.rag.pdf_processor:Processing PDF: Petroff20 - Cleaning CMB with ML.pdf\n", "INFO:src.rag.pdf_processor:✓ Extracted 11 pages, 43264 chars\n", "INFO:src.rag.pdf_processor:✓ Processed 3 PDFs successfully\n", "INFO:src.rag.pipeline:Ingesting document: CMBFSCNN\n", "INFO:src.rag.pipeline:✓ Chunks created: 33\n", "INFO:src.rag.pipeline:✓ Embedded 33/33 chunks\n", "INFO:src.rag.pipeline:Ingesting document: CVPR Version 16723_CMB_ML_A_Cosmic_Microwav\n", "INFO:src.rag.pipeline:✓ Chunks created: 19\n", "INFO:src.rag.pipeline:✓ Embedded 19/19 chunks\n", "INFO:src.rag.pipeline:Ingesting document: Petroff20 - Cleaning CMB with ML\n", "INFO:src.rag.pipeline:✓ Chunks created: 16\n", "INFO:src.rag.pipeline:✓ Embedded 16/16 chunks\n", "INFO:src.rag.pipeline:Querying: What are the main findings?\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "[2] Ingestion Summary:\n", " CMBFSCNN: 33 chunks\n", " CVPR Version 16723_CMB_ML_A_Cosmic_Microwav: 19 chunks\n", " Petroff20 - Cleaning CMB with ML: 16 chunks\n", " Total: 68 chunks\n", "\n", "[3] Querying...\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "INFO:httpx:HTTP Request: POST https://api.groq.com/openai/v1/chat/completions \"HTTP/1.1 200 OK\"\n", "INFO:src.rag.pipeline:Query complete: success\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "📝 Question: What are the main findings?\n", "\n", "🤖 Answer:\n", "The provided context does not explicitly contain information about the main findings. It appears to be a collection of scientific texts discussing the Cosmic Microwave Background (CMB) and its analysis. The main topics covered include the CMB's power spectrum, contamination by foreground radiations, and the process of component separation.\n", "\n", "📚 Sources (3 chunks):\n", " - [57.3%] in- frared background (CIB) is a different diffuse extragalactic source. 0 200 4...\n", " - [57.1%] sion [1] and LiteBird [26], are expected to probe some of the 084 deepest myster...\n", " - [57.0%] primordial B mode originates from the primordial gravitational waves predicted b...\n" ] } ], "source": [ "# test pdf processor\n", "\n", "from src.rag import RAGPipeline\n", "import logging\n", "import os\n", "\n", "project_root = os.path.abspath(os.path.join(os.getcwd(), \"..\"))\n", "papers_path = os.path.join(project_root, \"papers\")\n", "\n", "logging.basicConfig(level=logging.INFO)\n", "\n", "# Initialize pipeline\n", "pipeline = RAGPipeline()\n", "\n", "# Option A: Ingest a single PDF\n", "# result = pipeline.ingest_pdf(\"papers/your_paper.pdf\")\n", "# print(f\"✓ Ingested {result['chunks_embedded']} chunks\")\n", "\n", "# Option B: Ingest all PDFs from folder (RECOMMENDED)\n", "if os.path.exists(papers_path):\n", " print(\"[1] Ingesting all PDFs from 'papers' folder...\")\n", " results = pipeline.ingest_folder(papers_path)\n", " \n", " print(f\"\\n[2] Ingestion Summary:\")\n", " total_chunks = 0\n", " for doc_id, result in results.items():\n", " print(f\" {doc_id}: {result['chunks_embedded']} chunks\")\n", " total_chunks += result['chunks_embedded']\n", " print(f\" Total: {total_chunks} chunks\")\n", " \n", " # Now query!\n", " print(f\"\\n[3] Querying...\")\n", " query = \"What are the main findings?\" # Change this to your question\n", " result = pipeline.query(query)\n", " \n", " print(f\"\\n📝 Question: {result['query']}\")\n", " print(f\"\\n🤖 Answer:\\n{result['answer']}\")\n", " print(f\"\\n📚 Sources ({result['chunks_used']} chunks):\")\n", " for source in result['sources']:\n", " print(f\" - [{source['similarity']:.1%}] {source['preview'][:80]}...\")\n", "else:\n", " print(\"❌ No 'papers' folder found. Create one and add PDFs!\")" ] }, { "cell_type": "code", "execution_count": 7, "id": "441624d7", "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "INFO:src.rag.pipeline:Querying: What is the Cosmic Microwave Background?\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "============================================================\n", "Q: What is the Cosmic Microwave Background?\n", "============================================================\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "INFO:httpx:HTTP Request: POST https://api.groq.com/openai/v1/chat/completions \"HTTP/1.1 200 OK\"\n", "INFO:src.rag.pipeline:Query complete: success\n", "INFO:src.rag.pipeline:Querying: How is machine learning used to analyze CMB data?\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "A: The Cosmic Microwave Background (CMB) has characteristic modes which are visible as consistently sized lumps and has a first peak at ℓ≈200, which corresponds roughly to 1 deg, about the size of the largest lumps visible in the CMB.\n", "\n", "Sources (3 chunks):\n", " [60.1%] Machine learning is AI. Deep learning uses networks....\n", " [46.4%] in- frared background (CIB) is a different diffuse extragala...\n", "\n", "============================================================\n", "Q: How is machine learning used to analyze CMB data?\n", "============================================================\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "INFO:httpx:HTTP Request: POST https://api.groq.com/openai/v1/chat/completions \"HTTP/1.1 200 OK\"\n", "INFO:src.rag.pipeline:Query complete: success\n", "INFO:src.rag.pipeline:Querying: What are foreground contaminations in CMB?\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "A: Based on the provided context, it appears that machine learning is mentioned as relevant to the analysis of CMB data in Chunk 1, but no specific information on how it is used is provided. However, in Chunk 2, it is mentioned that CMB-ML stands out distinctly because it includes Monte-Carlo simulations, which are not included in other software such as PySM3 and PSM.\n", "\n", "In Chunk 3, there are several references to machine learning and its applications in cosmology, including the use of deep learning for deblurring and the use of convolutional neural networks for component separation in CMB analysis. Specifically, reference [57] discusses the use of machine learning for foreground cleaning in CMB data, and reference [58] presents a method for CMB component separation using convolutional neural networks.\n", "\n", "Therefore, while the provided context does not provide a comprehensive answer, it suggests that machine learning is used in various ways to analyze CMB data, including simulation, deblurring, and component separation.\n", "\n", "Sources (3 chunks):\n", " [62.6%] Machine learning is AI. Deep learning uses networks....\n", " [59.9%] experiment [17, 60]. 131 Many other examples exist, but all ...\n", "\n", "============================================================\n", "Q: What are foreground contaminations in CMB?\n", "============================================================\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "INFO:httpx:HTTP Request: POST https://api.groq.com/openai/v1/chat/completions \"HTTP/1.1 200 OK\"\n", "INFO:src.rag.pipeline:Query complete: success\n", "INFO:src.rag.pipeline:Querying: What component separation methods are discussed?\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "A: Foreground contaminations in CMB refer to the various sources of radiation that contaminate the Cosmic Microwave Background (CMB) signal, making it difficult to accurately separate the primordial CMB signal from the foregrounds. These contaminants include Galactic polarized radiation, which tends to be brighter than the primordial B-mode signal, as well as other astrophysical sources such as point sources, diffuse sources, and extragalactic signals.\n", "\n", "Sources (3 chunks):\n", " [63.4%] in- frared background (CIB) is a different diffuse extragala...\n", " [59.7%] primordial B mode originates from the primordial gravitation...\n", "\n", "============================================================\n", "Q: What component separation methods are discussed?\n", "============================================================\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "INFO:httpx:HTTP Request: POST https://api.groq.com/openai/v1/chat/completions \"HTTP/1.1 429 Too Many Requests\"\n", "INFO:groq._base_client:Retrying request to /openai/v1/chat/completions in 25.000000 seconds\n", "INFO:httpx:HTTP Request: POST https://api.groq.com/openai/v1/chat/completions \"HTTP/1.1 200 OK\"\n", "INFO:src.rag.pipeline:Query complete: success\n", "INFO:src.rag.pipeline:Querying: What deep learning architectures are used?\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "A: The following component separation methods are discussed:\n", "\n", "1. Internal Linear Combination (ILC)\n", "2. Needlet (NILC)\n", "3. Scale Discretized (SILC)\n", "4. Hierarchical Morphological Component Analysis (HGMCA)\n", "5. Convolutional Neural Network (CNN)-based methods (CMBFSCNN is specifically mentioned)\n", "\n", "Sources (3 chunks):\n", " [55.4%] 497 [4] Yashar Akrami, M Ashdown, Jonathan Aumont, Carlo Bac...\n", " [55.0%] in several next generation CMB experiments, such as the CMB-...\n", "\n", "============================================================\n", "Q: What deep learning architectures are used?\n", "============================================================\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "INFO:httpx:HTTP Request: POST https://api.groq.com/openai/v1/chat/completions \"HTTP/1.1 429 Too Many Requests\"\n", "INFO:groq._base_client:Retrying request to /openai/v1/chat/completions in 23.000000 seconds\n", "INFO:httpx:HTTP Request: POST https://api.groq.com/openai/v1/chat/completions \"HTTP/1.1 200 OK\"\n", "INFO:src.rag.pipeline:Query complete: success\n", "INFO:src.rag.pipeline:Querying: What datasets are mentioned?\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "A: Based on the provided context, the following deep learning architectures are mentioned:\n", "\n", "1. Convolutional Neural Network (CNN) - mentioned in several references, including [51], [56], and [61].\n", "2. Multi-scale Convolutional Neural Network - mentioned in [53].\n", "3. Spherical Convolutional Neural Network - mentioned in [56] (DeepSphere).\n", "4. U-Net - mentioned in [61].\n", "\n", "Note that PyTorch is also mentioned, but it is a deep learning library rather than a specific architecture.\n", "\n", "Sources (3 chunks):\n", " [63.9%] Machine learning is AI. Deep learning uses networks....\n", " [63.3%] Advances in Neural Information Processing Systems 30, ed. I....\n", "\n", "============================================================\n", "Q: What datasets are mentioned?\n", "============================================================\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "INFO:httpx:HTTP Request: POST https://api.groq.com/openai/v1/chat/completions \"HTTP/1.1 429 Too Many Requests\"\n", "INFO:groq._base_client:Retrying request to /openai/v1/chat/completions in 14.000000 seconds\n", "INFO:httpx:HTTP Request: POST https://api.groq.com/openai/v1/chat/completions \"HTTP/1.1 200 OK\"\n", "INFO:src.rag.pipeline:Query complete: success\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "A: Based on the provided context, the following datasets are mentioned:\n", "\n", "1. The CMB-ML dataset, which is a unified framework for dataset generation and model evaluation.\n", "2. The CMB-S4 science mission dataset.\n", "3. The LiteBird dataset.\n", "4. The COBE (Cosmic Background Explorer) dataset.\n", "5. The Planck Mission dataset.\n", "6. The Cosmic Infrared Background (CIB) dataset.\n", "\n", "Sources (3 chunks):\n", " [62.0%] REVIEW COPY. DO NOT DISTRIBUTE. physics methods, each of the...\n", " [58.2%] in- frared background (CIB) is a different diffuse extragala...\n" ] } ], "source": [ "queries = [\n", " \"What is the Cosmic Microwave Background?\",\n", " \"How is machine learning used to analyze CMB data?\",\n", " \"What are foreground contaminations in CMB?\",\n", " \"What component separation methods are discussed?\",\n", " \"What deep learning architectures are used?\",\n", " \"What datasets are mentioned?\",\n", "]\n", "\n", "for query in queries:\n", " print(f\"\\n{'='*60}\")\n", " print(f\"Q: {query}\")\n", " print('='*60)\n", " \n", " result = pipeline.query(query)\n", " print(f\"\\nA: {result['answer']}\")\n", " print(f\"\\nSources ({result['chunks_used']} chunks):\")\n", " for source in result['sources'][:2]: # Show top 2\n", " print(f\" [{source['similarity']:.1%}] {source['preview'][:60]}...\")" ] }, { "cell_type": "code", "execution_count": null, "id": "76a5da4b", "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": ".venv", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.12.5" } }, "nbformat": 4, "nbformat_minor": 5 }