Spaces:
Running on Zero
Running on Zero
File size: 6,622 Bytes
dfa1d6c d10de1b 1970ce9 d10de1b 1970ce9 d10de1b dfa1d6c | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 | ---
license: mit
title: NLPforASD
sdk: gradio
emoji: π’
colorFrom: blue
colorTo: purple
short_description: Profile-adaptive RAG chatbot for Autism Spectrum Disorder in
---
# NLP4ASD β Autism Spectrum Disorder Specialized Chatbot
A RAG-powered chatbot that answers questions about Autism Spectrum Disorder using scientific sources.
Answers adapt dynamically based on the user's profile.
---
## What It Does
1. User selects a **profile** (Parent, Patient, Healthcare Professional, Teacher, Researcher)
2. User asks a question about ASD
3. The system **retrieves the most relevant scientific passages** from a local knowledge base
4. It builds a **profile-adapted prompt** and generates a grounded answer
5. Sources are displayed alongside the answer
No answer is generated without retrieved evidence β the chatbot is grounded, not free-form.
---
## π Project Structure
```
NLP4ASD/
βββ app.py # Gradio interface (entry point)
βββ requirements.txt
βββ README.md
β
βββ data/
β βββ raw/ # Plain .txt scientific documents (your corpus)
β βββ processed/ # Auto-generated: FAISS index + chunk JSON
β βββ sources_metadata.json # Document registry
β
βββ src/
β βββ config.py # All tunable settings (models, paths, parameters)
β βββ data_loader.py # Load .txt files from data/raw/
β βββ preprocessing.py # Clean raw text
β βββ chunking.py # Split text into overlapping chunks
β βββ embeddings.py # Encode chunks with SentenceTransformers
β βββ vector_store.py # Build, save, and load FAISS index
β βββ retriever.py # Retrieve top-k relevant chunks
β βββ prompt_builder.py # Build adaptive prompts per profile
β βββ generator.py # Generate answer with HF model
β βββ rag_pipeline.py # Orchestrate full pipeline
β βββ utils.py # File helpers
β
βββ notebooks/
βββ build_knowledge_base.ipynb # Interactive knowledge base builder
```
---
## π Quick Start (Local)
### 1. Install dependencies
```bash
pip install -r requirements.txt
```
### 2. Add your documents
Place plain `.txt` files in `data/raw/`. The project includes 4 sample documents.
### 3. Build the knowledge base
```bash
python -c "from src.rag_pipeline import build_knowledge_base; build_knowledge_base()"
```
This embeds all documents and creates the FAISS index in `data/processed/`.
### 4. Run the app
```bash
python app.py
```
Open the local URL shown in your terminal.
---
## π€ Deploy to Hugging Face Spaces
1. Create a new Space (type: **Gradio**)
2. Push the full project:
```bash
git init
git remote add origin https://huggingface.co/spaces/YOUR_USERNAME/NLP4ASD
git add .
git commit -m "Initial commit"
git push origin main
```
3. The Space will auto-install `requirements.txt` and launch `app.py`
4. On first start, the knowledge base is built automatically from `data/raw/`
> **Tip:** For faster startup, commit `data/processed/` (index + chunks) to avoid rebuilding on every cold start.
---
## βοΈ Configuration
All key settings are in `src/config.py`:
| Setting | Default | Description |
|---------|---------|-------------|
| `EMBEDDING_MODEL` | `all-MiniLM-L6-v2` | SentenceTransformer model |
| `GENERATOR_MODEL` | `google/flan-t5-base` | HF generation model |
| `CHUNK_SIZE` | `512` | Characters per chunk |
| `CHUNK_OVERLAP` | `64` | Overlap between chunks |
| `TOP_K` | `4` | Chunks retrieved per query |
| `MAX_NEW_TOKENS` | `512` | Max tokens generated |
| `TEMPERATURE` | `0.3` | Generation temperature |
---
## π Switching to a Better Model
To use a more powerful model, change `GENERATOR_MODEL` in `src/config.py`:
```python
# Biomedical-focused
GENERATOR_MODEL = "BioMistral/BioMistral-7B"
# Instruction-following
GENERATOR_MODEL = "mistralai/Mistral-7B-Instruct-v0.2"
GENERATOR_MODEL = "google/gemma-2b-it"
# Medical LLM
GENERATOR_MODEL = "meta-llama/Llama-3-8B-Instruct"
```
For 7B+ models on Spaces, use a **GPU Space** (T4 or A10) and enable 4-bit quantization:
```python
# In src/generator.py, replace the pipeline() call with:
from transformers import BitsAndBytesConfig
quantization_config = BitsAndBytesConfig(load_in_4bit=True)
model = AutoModelForCausalLM.from_pretrained(
GENERATOR_MODEL,
quantization_config=quantization_config,
device_map="auto",
)
```
---
## π¬ Future: LoRA / QLoRA Fine-Tuning
To fine-tune the generation model on ASD-specific data, insert the following step between `generator.py` (base model loading) and deployment:
### Where to add it
Create `src/fine_tuning.py` with:
```python
from peft import LoraConfig, get_peft_model, TaskType
from transformers import TrainingArguments, Trainer
# 1. Define LoRA configuration
lora_config = LoraConfig(
r=16, # rank
lora_alpha=32,
target_modules=["q_proj", "v_proj"], # for LLaMA/Mistral
lora_dropout=0.05,
bias="none",
task_type=TaskType.CAUSAL_LM,
)
# 2. Wrap base model
model = get_peft_model(base_model, lora_config)
# 3. Prepare dataset: (prompt, expected_answer) pairs
# Use clinical Q&A from published ASD literature
# 4. Train
training_args = TrainingArguments(
output_dir="./lora_checkpoints",
per_device_train_batch_size=2,
gradient_accumulation_steps=4,
num_train_epochs=3,
fp16=True,
logging_steps=10,
save_strategy="epoch",
)
trainer = Trainer(model=model, args=training_args, train_dataset=dataset)
trainer.train()
# 5. Save adapter (NOT full model weights β only ~10MB)
model.save_pretrained("./lora_adapter")
# 6. In generator.py, load with:
# from peft import PeftModel
# model = PeftModel.from_pretrained(base_model, "./lora_adapter")
```
QLoRA reduces VRAM requirements to ~6GB for a 7B model, enabling fine-tuning on a single consumer GPU.
---
## π Adding French Support
The prompt builder (`src/prompt_builder.py`) already supports French via `LANGUAGE_INSTRUCTIONS`.
To add translated profile instructions, extend `PROFILE_INSTRUCTIONS` with French keys or add a `_fr` suffix per profile.
---
## β οΈ Disclaimer
NLP4ASD is a research prototype. It is not a medical device and does not provide professional medical advice.
All answers are grounded in retrieved scientific documents and should be verified by qualified professionals.
---
## π License
MIT License β see `LICENSE` for details. |