File size: 6,199 Bytes
cc50299
 
 
 
 
 
 
 
 
 
 
40e5eae
 
cc50299
40e5eae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
---
title: RAG Python System
emoji: πŸ€–
colorFrom: blue
colorTo: green
sdk: gradio
sdk_version: 4.44.1
app_file: app.py
pinned: false
---

# RAG System - Intelligent Document Q&A

A complete RAG (Retrieval-Augmented Generation) system for intelligent document search and question answering using Hugging Face Inference API.

## 🌟 Features

- πŸ“„ **Document Conversion**: Automatic conversion of PDF, DOCX, TXT files to markdown
- 🧩 **Smart Splitting**: Text chunking with context preservation (LangChain)
- πŸ” **Vector Search**: Fast semantic search across documents (ChromaDB)
- πŸ€– **Local LLM**: Answer generation using Ollama (no cloud data transfer)
- 🌐 **Web Interface**: User-friendly Gradio interface with streaming responses
- 🌍 **Multilingual**: Support for English, Russian, and Ukrainian languages

## πŸ—οΈ Architecture

```
Documents β†’ Conversion (PyMuPDF) β†’ Splitting (LangChain)
                                           ↓
User Question β†’ Search (ChromaDB) β†’ Context + Question
                                           ↓
                                 LLM (Ollama llama3.2)
                                           ↓
                                 Answer + Sources
```

## πŸ“‹ Requirements

- Python 3.9+
- Ollama (for local LLM model execution)
- 4+ GB RAM (for embedding model and LLM)

## πŸš€ Installation

### 1. Install Ollama

```bash
# macOS / Linux
curl -fsSL https://ollama.com/install.sh | sh

# After installation, download the model
ollama pull llama3.2
```

### 2. Clone and Setup Project

```bash
# Navigate to project directory
cd /Users/v.hirenko/Desktop/DevHubVault/my-ai-projects/rag-python-rag

# Create virtual environment
python3 -m venv venv

# Activate virtual environment
source venv/bin/activate  # Linux/macOS
# or
venv\Scripts\activate  # Windows

# Install dependencies
pip install -r requirements.txt
```

## πŸ“š Project Structure

```
rag-python-rag/
β”œβ”€β”€ config.py                # System configuration
β”œβ”€β”€ document_converter.py    # Document conversion
β”œβ”€β”€ text_splitter.py        # Text chunking
β”œβ”€β”€ vector_store.py         # Vector storage
β”œβ”€β”€ llm_handler.py          # LLM request handling
β”œβ”€β”€ main.py                 # Main application
β”œβ”€β”€ requirements.txt        # Dependencies
β”œβ”€β”€ documents/              # Source documents
β”œβ”€β”€ processed_docs/         # Converted documents
└── chroma_db/             # Vector database
```

## 🎯 Usage

### Quick Start

```bash
# Activate virtual environment
source venv/bin/activate

# Run the application
python main.py
```

The application will automatically:

1. Download test document (Think Python PDF)
2. Convert it to markdown
3. Split into chunks
4. Create vector database
5. Launch web interface at http://localhost:7860

### Adding Your Own Documents

1. Place documents (PDF, DOCX, TXT) in the `documents/` folder
2. Restart the application or run indexing:

```bash
python -c "
from main import RAGSystem
rag = RAGSystem()
rag.setup_pipeline(force_rebuild=True)
"
```

### Using Python API

```python
from vector_store import retrieve_context
from llm_handler import generate_answer, format_response

# Ask a question
question = "How do loops work in Python?"

# Get context from documents
context, sources = retrieve_context(question, n_results=5)

# Generate answer
answer = generate_answer(question, context)

# Format result
response = format_response(question, answer, sources)
print(response)
```

### Streaming Answer Generation

```python
from vector_store import retrieve_context
from llm_handler import stream_llm_answer

question = "What are Python functions?"
context, sources = retrieve_context(question)

# Stream output
for token in stream_llm_answer(question, context):
    print(token, end='', flush=True)
```

## βš™οΈ Configuration

Main settings are in `config.py`:

```python
# Embedding model
EMBEDDING_MODEL = "all-MiniLM-L6-v2"

# LLM model
OLLAMA_MODEL = "llama3.2"

# Text splitting parameters
TEXT_SPLITTER_CONFIG = {
    "chunk_size": 1000,
    "chunk_overlap": 200,
}

# Number of search results
DEFAULT_N_RESULTS = 5
```

## πŸ§ͺ Testing Components

### Document Conversion

```bash
python document_converter.py
```

### Text Chunking

```bash
python text_splitter.py
```

### Vector Store

```bash
python vector_store.py
```

### LLM Handler

```bash
python llm_handler.py
```

## πŸ”§ Troubleshooting

### Issue: Model not found

```bash
# Check available models
ollama list

# Download required model
ollama pull llama3.2
```

### Issue: Out of memory

- Reduce `chunk_size` in `config.py`
- Reduce `DEFAULT_N_RESULTS`
- Use a lighter model (e.g., `llama3.2:1b`)

### Issue: Slow generation

- Use a faster model
- Reduce number of search results
- Consider using GPU version of Ollama

## πŸ“Š Performance

On Think Python document (300+ pages):

- **Conversion**: ~5 seconds
- **Indexing**: ~30 seconds (847 chunks)
- **Search**: < 1 second
- **Answer generation**: 5-15 seconds (depends on length)

## πŸ›£οΈ Roadmap

- [ ] Support more formats (Excel, PowerPoint)
- [ ] Embedding caching
- [ ] REST API endpoints
- [ ] Multimodal documents (images)
- [ ] Chat history and dialogue context
- [ ] Deploy to Hugging Face Spaces

## πŸ“– Sources and Inspiration

Project based on article: [How I Built a RAG System in One Evening](https://habr.com/ru/articles/955798/)

**Technologies Used:**

- [PyMuPDF](https://pymupdf.readthedocs.io/) - PDF conversion
- [LangChain](https://www.langchain.com/) - text splitting
- [ChromaDB](https://www.trychroma.com/) - vector database
- [Sentence Transformers](https://www.sbert.net/) - embeddings
- [Ollama](https://ollama.ai/) - local LLM models
- [Gradio](https://www.gradio.app/) - web interface

## πŸ“ License

This project is created for educational purposes. Use freely!

## 🀝 Contributing

If you want to improve the project:

1. Fork the repository
2. Create a feature branch
3. Commit your changes
4. Push to the branch
5. Create a Pull Request

## πŸ“§ Contact

If you have questions or suggestions, create an Issue in the repository.

---

**Made with ❀️ for learning RAG systems and local LLMs**