CoolFace
Apppublic

mohamedhassan22/WHEC_ERI_experimental

sourceHugging Facemitupdated 9mo agoView on Hugging Face
0likes
App README

๐Ÿฅ US Army Medical Research RAG System

A Retrieval-Augmented Generation (RAG) system for querying US Army medical research papers using state-of-the-art AI models - completely free and open-source!

๐ŸŒŸ Features

  • โ€”๐Ÿค– LLM: Uses OpenAI GPT-3.5 Turbo for intelligent answers
  • โ€”๐Ÿ” Semantic Search: OpenAI text-embedding-3-small for accurate retrieval
  • โ€”๐Ÿ“š Document Support: Upload JSONL or TXT files
  • โ€”โ˜๏ธ Cloud Powered: Leveraging OpenAI API for high performance
  • โ€”๐Ÿ”Œ REST API: Full FastAPI implementation with automatic docs
  • โ€”๐Ÿ’พ Persistent Index: Build once, query many times

๐Ÿš€ Quick Start

Using the API

1. Check System Health
bash
curl https://your-space-name.hf.space/health
2. Upload Documents
bash
curl -X POST "https://your-space-name.hf.space/upload" \
  -F "files=@your_document.jsonl"
3. Build Index
bash
curl -X POST "https://your-space-name.hf.space/build-index"
4. Query the System
bash
curl -X POST "https://your-space-name.hf.space/query" \
  -H "Content-Type: application/json" \
  -d '{
    "question": "What are the main causes of exertional injuries in US Army soldiers?",
    "top_k": 5
  }'

Using Python

python
import requests

# Base URL
BASE_URL = "https://your-space-name.hf.space"

# Query the RAG system
response = requests.post(
    f"{BASE_URL}/query",
    json={
        "question": "What injury prevention strategies are recommended?",
        "top_k": 5
    }
)

result = response.json()
print(f"Answer: {result['answer']}")
print(f"\nSources: {len(result['sources'])}")

Using JavaScript

javascript
const BASE_URL = "https://your-space-name.hf.space";

async function queryRAG(question) {
  const response = await fetch(`${BASE_URL}/query`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      question: question,
      top_k: 5
    })
  });
  
  const data = await response.json();
  return data;
}

// Use it
queryRAG("What are the risk factors for heat illness?")
  .then(result => console.log(result.answer));

๐Ÿ“‹ API Endpoints

Core Endpoints

EndpointMethodDescription
/GETAPI information
/healthGETHealth check and system status
/queryPOSTAsk questions to the RAG system
/uploadPOSTUpload documents (JSONL or TXT)
/build-indexPOSTBuild the RAG index from documents
/statsGETGet system statistics
/deleteDELETEDelete the current index

Interactive Documentation

Visit /docs for full Swagger UI documentation with interactive testing.

๐Ÿ“Š API Request/Response Examples

Query Request

json
POST /query
{
  "question": "What are the main causes of exertional injuries?",
  "top_k": 5
}

Query Response

json
{
  "answer": "The main causes of exertional injuries in US Army soldiers include...",
  "sources": [
    {
      "text": "Excerpt from the paper...",
      "score": 0.85,
      "metadata": {
        "title": "Risk factors for musculoskeletal injuries...",
        "journal": "Military Medical Research",
        "year": "2021",
        "authors": "Author1, Author2, Author3",
        "pmcid": "PMC123456"
      }
    }
  ],
  "question": "What are the main causes of exertional injuries?"
}

๐Ÿ“ Document Format

JSONL Format (Recommended)

json
{"pmcid": "PMC123456", "title": "Paper Title", "text": "Full paper text...", "metadata": {"authors": ["Author1", "Author2"], "journal": "Journal Name", "year": "2021", "doi": "10.1234/example", "keywords": ["keyword1", "keyword2"]}}

Plain Text Format

Simply upload .txt files containing your documents. Metadata will be extracted from filenames.

๐Ÿ› ๏ธ Configuration

The system uses the following default configuration:

python
EMBEDDING_MODEL = "text-embedding-3-small"
LLM_MODEL = "gpt-3.5-turbo"
CHUNK_SIZE = 1024
CHUNK_OVERLAP = 200
TOP_K = 5
TEMPERATURE = 0.1

๐Ÿ”ง Local Development

Prerequisites

  • โ€”Python 3.10+
  • โ€”NVIDIA GPU with CUDA support (recommended)
  • โ€”16GB+ RAM
  • โ€”Docker (for containerized deployment)

Setup

  1. 1.Clone the repository
bash
git clone https://huggingface.co/spaces/your-username/your-space-name
cd your-space-name
  1. 1.Install dependencies
bash
pip install -r requirements.txt
  1. 1.Run the application
bash
uvicorn app:app --host 0.0.0.0 --port 7860
  1. 1.Access the API
  2. 2.API: http://localhost:7860
  3. 3.Docs: http://localhost:7860/docs

Docker Build

bash
docker build -t rag-system .
docker run -p 7860:7860 --gpus all rag-system

๐Ÿ“ฆ Project Structure

.
โ”œโ”€โ”€ Dockerfile              # Docker configuration
โ”œโ”€โ”€ requirements.txt        # Python dependencies
โ”œโ”€โ”€ app.py                 # FastAPI application
โ”œโ”€โ”€ rag_pipeline.py        # Core RAG logic
โ”œโ”€โ”€ README.md              # This file
โ”œโ”€โ”€ data/                  # Document storage (created automatically)
โ””โ”€โ”€ rag_index/             # Vector index storage (created automatically)

๐Ÿง  How It Works

  1. 1.Document Processing: Documents are split into chunks using sentence-based splitting
  2. 2.Embedding: Each chunk is embedded using OpenAI's text-embedding-3-small
  3. 3.Indexing: Embeddings are stored in a vector index
  4. 4.Query: User questions are embedded and similar chunks are retrieved
  5. 5.Generation: GPT-3.5 Turbo generates answers based on retrieved context

๐ŸŽฏ Use Cases

  • โ€”๐Ÿ“– Research paper analysis
  • โ€”๐Ÿ” Medical literature search
  • โ€”๐Ÿ’ก Knowledge extraction from documents
  • โ€”๐ŸŽ“ Educational Q&A systems
  • โ€”๐Ÿ“Š Data-driven insights

โš™๏ธ System Requirements

Minimum

  • โ€”CPU: 4 cores
  • โ€”RAM: 16GB
  • โ€”Storage: 20GB

Recommended

  • โ€”GPU: NVIDIA GPU with 8GB+ VRAM
  • โ€”CPU: 8+ cores
  • โ€”RAM: 32GB+
  • โ€”Storage: 50GB+ SSD

๐Ÿšจ Troubleshooting

Index Not Found

Issue: RAG system returns "not initialized" Solution: Upload documents and build the index using /build-index

API Key Missing

Issue: RAG system errors with authentication failure Solution: Ensure OPENAI_API_KEY is set in your environment variables or Space settings.

Rate Limits

Issue: Queries failing continuously Solution: Check your OpenAI API usage and limits.

๐Ÿ“ Example Questions

  • โ€”"What are the main causes of exertional injuries in US Army soldiers?"
  • โ€”"How does heat illness affect military readiness?"
  • โ€”"What injury prevention strategies are recommended for military training?"
  • โ€”"What are the risk factors for musculoskeletal injuries?"
  • โ€”"How can training programs reduce injury rates?"

๐Ÿค Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

๐Ÿ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

๐Ÿ™ Acknowledgments

  • โ€”OpenAI for LLM and Embedding models
  • โ€”LlamaIndex for the RAG framework
  • โ€”Hugging Face for hosting and model infrastructure

๐Ÿ“ง Contact

For questions or support, please open an issue on the repository.


Note: This system is designed for research and educational purposes. Always verify critical information with primary sources.