bilalabic commited on
Commit
c7df5be
·
verified ·
1 Parent(s): 54f5cfb

Upload folder using huggingface_hub

Browse files
.gitignore ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Large model files and folders
2
+ fine_tuned_FitTurkAI_QLoRA/
3
+ fitness_rag_store_merged/
4
+
5
+ # Downloaded zip files
6
+ *.zip
7
+ fine_tuned_model.zip
8
+ vector_store.zip
9
+
10
+ # Python cache and virtual environments
11
+ __pycache__/
12
+ *.py[cod]
13
+ *$py.class
14
+ *.so
15
+ .Python
16
+ venv/
17
+ env/
18
+ fitturkrai_env/
19
+
20
+ # Distribution / packaging
21
+ .Python
22
+ build/
23
+ develop-eggs/
24
+ dist/
25
+ downloads/
26
+ eggs/
27
+ .eggs/
28
+ lib/
29
+ lib64/
30
+ parts/
31
+ sdist/
32
+ var/
33
+ wheels/
34
+ *.egg-info/
35
+ .installed.cfg
36
+ *.egg
37
+ MANIFEST
38
+
39
+ # PyInstaller
40
+ *.manifest
41
+ *.spec
42
+
43
+ # Installer logs
44
+ pip-log.txt
45
+ pip-delete-this-directory.txt
46
+
47
+ # Unit test / coverage reports
48
+ htmlcov/
49
+ .tox/
50
+ .coverage
51
+ .coverage.*
52
+ .cache
53
+ nosetests.xml
54
+ coverage.xml
55
+ *.cover
56
+ .hypothesis/
57
+ .pytest_cache/
58
+
59
+ # Jupyter Notebook
60
+ .ipynb_checkpoints
61
+
62
+ # IPython
63
+ profile_default/
64
+ ipython_config.py
65
+
66
+ # Environment variables
67
+ .env
68
+ .venv
69
+
70
+ # IDE files
71
+ .vscode/
72
+ .idea/
73
+ *.swp
74
+ *.swo
75
+
76
+ # OS files
77
+ .DS_Store
78
+ Thumbs.db
79
+
80
+ # Log files
81
+ *.log
82
+
83
+ # Temporary files
84
+ *.tmp
85
+ *.temp
86
+
87
+ # Large data files
88
+ *.bin
89
+ *.pkl
90
+ *.safetensors
91
+ *.h5
92
+ *.model
93
+
94
+ # NLTK data (will be downloaded automatically)
95
+ nltk_data/
README.md CHANGED
@@ -1,3 +1,243 @@
1
- ---
2
- license: apache-2.0
3
- ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # FitTürkAI RAG Sistemi - CPU Optimize Linux Versiyonu
2
+
3
+ 🏋️ **FitTürkAI**, Türkçe fitness ve sağlık danışmanlığı için geliştirilmiş Retrieval-Augmented Generation (RAG) sistemidir. Bu versiyon **CPU kullanımı için optimize edilmiştir** ve **Google Colab** gibi Linux ortamlarında sorunsuz çalışır.
4
+
5
+ ## 🚀 Özellikler
6
+
7
+ - **CPU Optimize Edilmiş**: GPU gerektirmez, CPU'da verimli çalışır
8
+ - **Türkçe Dil Desteği**: Türkçe dokümanları işler ve yanıtlar
9
+ - **RAG Sistemi**: PDF ve JSON belgelerinden bilgi çıkarır ve kullanır
10
+ - **Interactive Chat**: Gerçek zamanlı soru-cevap sistemi
11
+ - **LoRA Adapter Desteği**: Fine-tune edilmiş modelleri destekler
12
+ - **Linux Uyumlu**: Google Colab, Ubuntu, ve diğer Linux dağıtımlarında çalışır
13
+
14
+ ## 📋 Sistem Gereksinimleri
15
+
16
+ ### Minimum Gereksinimler
17
+ - **RAM**: En az 4 GB (8 GB önerilir)
18
+ - **Disk**: 5 GB boş alan
19
+ - **İşletim Sistemi**: Linux (Ubuntu, Google Colab vb.)
20
+ - **Python**: 3.8 veya üzeri
21
+
22
+ ### Google Colab İçin
23
+ - Ücretsiz Google Colab hesabı yeterlidir
24
+ - GPU gerekmez (CPU modunda çalışır)
25
+
26
+ ## 🛠️ Kurulum
27
+
28
+ ### 1. Google Colab'da Hızlı Kurulum
29
+
30
+ ```python
31
+ # Google Colab'da yeni bir notebook oluşturun ve şunu çalıştırın:
32
+
33
+ # 1. Repository'yi klonlayın
34
+ !git clone https://github.com/YOUR_USERNAME/FitTurkAI-RAG.git
35
+ %cd FitTurkAI-RAG
36
+
37
+ # 2. Otomatik kurulum scriptini çalıştırın
38
+ !python colab_setup_and_run.py
39
+ ```
40
+
41
+ ### 2. Manuel Kurulum
42
+
43
+ ```bash
44
+ # 1. Repository'yi klonlayın
45
+ git clone https://github.com/YOUR_USERNAME/FitTurkAI-RAG.git
46
+ cd FitTurkAI-RAG
47
+
48
+ # 2. Python sanal ortamı oluşturun (opsiyonel)
49
+ python -m venv venv
50
+ source venv/bin/activate # Linux/Mac
51
+
52
+ # 3. Gerekli paketleri yükleyin
53
+ pip install -r requirements.txt
54
+
55
+ # 4. NLTK verilerini indirin
56
+ python -c "import nltk; nltk.download('punkt'); nltk.download('stopwords')"
57
+ ```
58
+
59
+ ## 📁 Klasör Yapısı
60
+
61
+ ```
62
+ FitTurkAI-RAG/
63
+ ├── test.py # Ana RAG sistemi (CPU optimize)
64
+ ├── colab_setup_and_run.py # Google Colab kurulum scripti
65
+ ├── requirements.txt # CPU için paket listesi
66
+ ├── README.md # Bu dosya
67
+ ├── indirilen_pdfler/ # PDF dosyalarınız (oluşturulacak)
68
+ ├── DATA/ # JSON veri dosyalarınız (oluşturulacak)
69
+ ├── fitness_rag_store_merged/ # Vector store (oluşturulacak)
70
+ └── fine_tuned_FitTurkAI_QLoRA/ # LoRA adapter (opsiyonel)
71
+ ```
72
+
73
+ ## 🚴‍♀️ Kullanım
74
+
75
+ ### 1. Temel Kullanım
76
+
77
+ ```python
78
+ # Ana scripti çalıştırın
79
+ python test.py
80
+ ```
81
+
82
+ ### 2. Google Colab'da Programmatik Kullanım
83
+
84
+ ```python
85
+ from test import FitnessRAG, RAGConfig
86
+
87
+ # Konfigürasyon oluşturun
88
+ config = RAGConfig(
89
+ peft_model_path=None # Base model kullanmak için None yapın
90
+ )
91
+
92
+ # RAG sistemini başlatın
93
+ rag_system = FitnessRAG(config)
94
+
95
+ # Bilgi tabanını oluşturun (ilk çalıştırmada)
96
+ rag_system.build_knowledge_base(
97
+ pdf_dir="./indirilen_pdfler",
98
+ json_dir="./DATA"
99
+ )
100
+
101
+ # Soru sorun
102
+ answer = rag_system.ask("Sağlıklı kahvaltı için ne önerirsiniz?")
103
+ print(answer)
104
+
105
+ # Interactive mode başlatın
106
+ rag_system.interactive_chat()
107
+ ```
108
+
109
+ ### 3. Veri Ekleme
110
+
111
+ #### PDF Dosyaları
112
+ ```bash
113
+ # PDF'lerinizi bu klasöre koyun
114
+ cp your_fitness_pdfs/*.pdf ./indirilen_pdfler/
115
+ ```
116
+
117
+ #### JSON Verileri
118
+ ```python
119
+ # Örnek JSON formatı
120
+ {
121
+ "soru": "Egzersiz öncesi ne yemeli?",
122
+ "cevap": "Egzersiz öncesi hafif, karbonhidrat ağırlıklı besinler tercih edin..."
123
+ }
124
+ ```
125
+
126
+ ## ⚙️ Konfigürasyon
127
+
128
+ `RAGConfig` sınıfında özelleştirilebilir parametreler:
129
+
130
+ ```python
131
+ config = RAGConfig(
132
+ # Veri parametreleri
133
+ chunk_size=300, # Kelime başına chunk boyutu
134
+ chunk_overlap_sentences=2, # Overlap cümle sayısı
135
+ retrieval_k=5, # Kaç belge getirilecek
136
+
137
+ # Model parametreleri
138
+ generator_model_name="ytu-ce-cosmos/Turkish-Llama-8b-v0.1",
139
+ peft_model_path=None, # LoRA adapter yolu
140
+
141
+ # Performans parametreleri
142
+ max_context_length=3000 # Maksimum context uzunluğu
143
+ )
144
+ ```
145
+
146
+ ## 🔧 Sorun Giderme
147
+
148
+ ### Yaygın Sorunlar
149
+
150
+ #### 1. Bellek Hatası (OOM)
151
+ ```python
152
+ # Chunk boyutunu küçültün
153
+ config = RAGConfig(chunk_size=200, max_context_length=2000)
154
+ ```
155
+
156
+ #### 2. Model Yükleme Hatası
157
+ ```python
158
+ # Base model kullanın (LoRA olmadan)
159
+ config = RAGConfig(peft_model_path=None)
160
+ ```
161
+
162
+ #### 3. NLTK Veri Hatası
163
+ ```python
164
+ import nltk
165
+ nltk.download('punkt_tab') # Yeni NLTK sürümü için
166
+ nltk.download('punkt') # Eski NLTK sürümü için
167
+ nltk.download('stopwords')
168
+ ```
169
+
170
+ ### Google Colab Özel Çözümler
171
+
172
+ #### GPU'yu Kapatın
173
+ ```python
174
+ import os
175
+ os.environ['CUDA_VISIBLE_DEVICES'] = '' # GPU'yu devre dışı bırak
176
+ ```
177
+
178
+ #### Bellek Optimizasyonu
179
+ ```python
180
+ # Büyük modeller için
181
+ import torch
182
+ torch.set_num_threads(2) # CPU thread sayısını sınırla
183
+ ```
184
+
185
+ ## 📊 Performans Optimizasyonları
186
+
187
+ ### CPU İçin İpuçları
188
+
189
+ 1. **Model Boyutu**: Daha küçük embedding modelleri kullanın
190
+ 2. **Chunk Size**: Daha küçük chunk'lar daha hızlıdır
191
+ 3. **Thread Sayısı**: CPU çekirdek sayınıza göre ayarlayın
192
+ 4. **Batch Size**: Tek seferde işlenecek belge sayısını sınırlayın
193
+
194
+ ```python
195
+ # Hızlı konfigürasyon
196
+ fast_config = RAGConfig(
197
+ embedding_model_name="paraphrase-multilingual-MiniLM-L6-v2", # Daha küçük
198
+ chunk_size=200,
199
+ retrieval_k=3,
200
+ max_context_length=2000
201
+ )
202
+ ```
203
+
204
+ ## 🤝 Katkıda Bulunma
205
+
206
+ 1. Fork edin
207
+ 2. Feature branch oluşturun (`git checkout -b feature/AmazingFeature`)
208
+ 3. Commit yapın (`git commit -m 'Add some AmazingFeature'`)
209
+ 4. Push edin (`git push origin feature/AmazingFeature`)
210
+ 5. Pull Request açın
211
+
212
+ ## 📝 Değişiklik Notları
213
+
214
+ ### v2.0 - CPU Optimized
215
+ - ✅ GPU bağımlılığı kaldırıldı
216
+ - ✅ CPU için optimize edildi
217
+ - ✅ Google Colab desteği eklendi
218
+ - ✅ Otomatik kurulum scripti eklendi
219
+ - ✅ Bellek optimizasyonları
220
+
221
+ ### v1.0 - GPU Version
222
+ - ⚠️ Bu versiyon GPU gerektiriyordu (deprecated)
223
+
224
+ ## 📞 Destek
225
+
226
+ - **Issues**: GitHub Issues bölümünü kullanın
227
+ - **Discussions**: Genel sorular için GitHub Discussions
228
+ - **Email**: [your-email@domain.com]
229
+
230
+ ## 📄 Lisans
231
+
232
+ Bu proje MIT lisansı altında lisanslanmıştır - detaylar için [LICENSE](LICENSE) dosyasına bakın.
233
+
234
+ ## 🙏 Teşekkürler
235
+
236
+ - Hugging Face Transformers ekibine
237
+ - Turkish LLaMA projesine
238
+ - Sentence Transformers ekibine
239
+ - FAISS ekibine
240
+
241
+ ---
242
+
243
+ ⭐ **Bu projeyi beğendiyseniz, lütfen yıldızlamayı unutmayın!**
colab_setup_and_run.py ADDED
@@ -0,0 +1,218 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ FitTürkAI RAG System - Google Colab Setup and Demo Script
4
+ CPU Optimized for Linux Environment
5
+
6
+ Bu script Google Colab ortamında FitTürkAI RAG sistemini kurar ve çalıştırır.
7
+ """
8
+
9
+ import os
10
+ import sys
11
+ import subprocess
12
+ import shutil
13
+ from pathlib import Path
14
+
15
+ def install_requirements():
16
+ """Gerekli kütüphaneleri yükle"""
17
+ print("🔧 Gerekli kütüphaneler yükleniyor...")
18
+
19
+ # Önce pip'i güncelle
20
+ subprocess.run([sys.executable, "-m", "pip", "install", "--upgrade", "pip"], check=True)
21
+
22
+ # Ana kütüphaneleri yükle
23
+ requirements = [
24
+ "torch>=2.0.0,<2.2.0",
25
+ "transformers>=4.36.0,<4.40.0",
26
+ "sentence-transformers>=2.2.2,<3.0.0",
27
+ "accelerate>=0.24.0,<0.26.0",
28
+ "peft>=0.7.0,<0.8.0",
29
+ "nltk>=3.8",
30
+ "regex>=2022.10.31",
31
+ "faiss-cpu>=1.7.4",
32
+ "numpy>=1.24.0,<2.0.0",
33
+ "scipy>=1.9.0",
34
+ "PyPDF2>=3.0.0",
35
+ "PyMuPDF>=1.23.0",
36
+ "tqdm>=4.64.0",
37
+ "requests>=2.28.0",
38
+ "gdown>=4.7.0",
39
+ "datasets>=2.14.0",
40
+ "tokenizers>=0.15.0",
41
+ "safetensors>=0.3.0",
42
+ "psutil>=5.9.0"
43
+ ]
44
+
45
+ for requirement in requirements:
46
+ try:
47
+ print(f"📦 Yükleniyor: {requirement}")
48
+ subprocess.run([sys.executable, "-m", "pip", "install", requirement],
49
+ check=True, capture_output=True)
50
+ except subprocess.CalledProcessError as e:
51
+ print(f"❌ Hata: {requirement} yüklenemedi: {e}")
52
+ continue
53
+
54
+ print("✅ Kütüphane kurulumu tamamlandı!")
55
+
56
+ def download_nltk_data():
57
+ """NLTK verilerini indir"""
58
+ print("📚 NLTK verileri indiriliyor...")
59
+ import nltk
60
+ try:
61
+ nltk.download('punkt', quiet=True)
62
+ nltk.download('punkt_tab', quiet=True)
63
+ nltk.download('stopwords', quiet=True)
64
+ print("✅ NLTK verileri başarıyla indirildi!")
65
+ except Exception as e:
66
+ print(f"⚠️ NLTK veri indirme uyarısı: {e}")
67
+
68
+ def setup_directories():
69
+ """Gerekli klasörleri oluştur"""
70
+ print("📁 Klasör yapısı oluşturuluyor...")
71
+
72
+ directories = [
73
+ "./indirilen_pdfler",
74
+ "./DATA",
75
+ "./fitness_rag_store_merged",
76
+ "./fine_tuned_FitTurkAI_QLoRA"
77
+ ]
78
+
79
+ for directory in directories:
80
+ Path(directory).mkdir(parents=True, exist_ok=True)
81
+ print(f"✅ Klasör oluşturuldu: {directory}")
82
+
83
+ def create_demo_data():
84
+ """Demo için örnek veri oluştur"""
85
+ print("📝 Demo verileri oluşturuluyor...")
86
+
87
+ # Örnek JSON veri oluştur
88
+ demo_data = [
89
+ {
90
+ "soru": "Sağlıklı kahvaltı için ne önerirsiniz?",
91
+ "cevap": "Sağlıklı bir kahvaltı protein, kompleks karbonhidrat ve healthy yağlar içermelidir. Yumurta, tam tahıllı ekmek, avokado, meyveler iyi seçeneklerdir."
92
+ },
93
+ {
94
+ "soru": "Günde kaç bardak su içmeliyim?",
95
+ "cevap": "Genel olarak günde 8-10 bardak (2-2.5 litre) su içmek önerilir. Aktivite düzeyinize ve hava durumuna göre bu miktar artabilir."
96
+ },
97
+ {
98
+ "soru": "Egzersiz sonrası ne yemeli?",
99
+ "cevap": "Egzersiz sonrası 30-60 dakika içinde protein ve karbonhidrat içeren besinler tüketin. Örneğin protein smoothie veya yoğurt ile meyve."
100
+ }
101
+ ]
102
+
103
+ import json
104
+ with open("./DATA/demo_fitness_data.json", "w", encoding="utf-8") as f:
105
+ json.dump(demo_data, f, ensure_ascii=False, indent=2)
106
+
107
+ print("✅ Demo JSON verileri oluşturuldu!")
108
+
109
+ def check_system_resources():
110
+ """Sistem kaynaklarını kontrol et"""
111
+ print("💻 Sistem kaynakları kontrol ediliyor...")
112
+ try:
113
+ import psutil
114
+ cpu_count = psutil.cpu_count()
115
+ memory = psutil.virtual_memory()
116
+
117
+ print(f"🔍 CPU Çekirdek Sayısı: {cpu_count}")
118
+ print(f"🔍 Toplam RAM: {memory.total / (1024**3):.1f} GB")
119
+ print(f"🔍 Kullanılabilir RAM: {memory.available / (1024**3):.1f} GB")
120
+
121
+ if memory.available < 2 * (1024**3): # 2GB'dan az
122
+ print("⚠️ Uyarı: RAM düşük. Model yükleme sırasında sorun yaşayabilirsiniz.")
123
+ else:
124
+ print("✅ Sistem kaynakları yeterli görünüyor!")
125
+
126
+ except ImportError:
127
+ print("⚠️ psutil yüklü değil, sistem kontrolü atlanıyor...")
128
+
129
+ def main():
130
+ """Ana kurulum ve demo fonksiyonu"""
131
+ print("🚀 FitTürkAI RAG Sistemi - Google Colab Kurulumu Başlıyor...")
132
+ print("="*60)
133
+
134
+ try:
135
+ # 1. Sistem kontrolü
136
+ check_system_resources()
137
+
138
+ # 2. Kütüphane kurulumu
139
+ install_requirements()
140
+
141
+ # 3. NLTK verileri
142
+ download_nltk_data()
143
+
144
+ # 4. Klasör yapıs��
145
+ setup_directories()
146
+
147
+ # 5. Demo verileri
148
+ create_demo_data()
149
+
150
+ print("\n" + "="*60)
151
+ print("✅ Kurulum tamamlandı!")
152
+ print("="*60)
153
+ print("\n📋 Sonraki adımlar:")
154
+ print("1. test.py dosyasını çalıştırın:")
155
+ print(" python test.py")
156
+ print("\n2. Veya interaktif modda başlatın:")
157
+ print(" from test import FitnessRAG, RAGConfig")
158
+ print(" config = RAGConfig()")
159
+ print(" rag = FitnessRAG(config)")
160
+ print(" rag.interactive_chat()")
161
+
162
+ print("\n💡 İpuçları:")
163
+ print("- İlk çalıştırmada model indirileceği için biraz zaman alabilir")
164
+ print("- PDF dosyalarınızı './indirilen_pdfler' klasörüne koyun")
165
+ print("- JSON verilerinizi './DATA' klasörüne koyun")
166
+ print("- LoRA adapter'ınız varsa './fine_tuned_FitTurkAI_QLoRA' klasörüne koyun")
167
+
168
+ except Exception as e:
169
+ print(f"\n❌ Kurulum hatası: {e}")
170
+ print("Lütfen hataları kontrol edin ve tekrar deneyin.")
171
+ return False
172
+
173
+ return True
174
+
175
+ # Demo fonksiyonu
176
+ def run_quick_demo():
177
+ """Hızlı demo çalıştır"""
178
+ print("\n🎯 Hızlı Demo Başlatılıyor...")
179
+
180
+ try:
181
+ # test.py modülünü import et
182
+ from test import FitnessRAG, RAGConfig
183
+
184
+ # Konfigürasyon oluştur (PEFT olmadan)
185
+ config = RAGConfig(peft_model_path=None)
186
+
187
+ print("🤖 Model yükleniyor... (Bu işlem biraz zaman alabilir)")
188
+ rag_system = FitnessRAG(config)
189
+
190
+ # Bilgi tabanı oluştur
191
+ print("📚 Demo bilgi tabanı oluşturuluyor...")
192
+ rag_system.build_knowledge_base(json_dir="./DATA")
193
+
194
+ # Örnek soru sor
195
+ demo_question = "Sağlıklı kahvaltı için ne önerirsiniz?"
196
+ print(f"\n🤔 Demo Sorusu: {demo_question}")
197
+
198
+ answer = rag_system.ask(demo_question)
199
+ print(f"\n🤖 FitTürkAI Cevabı:\n{answer}")
200
+
201
+ print("\n✅ Demo tamamlandı! Artık interactive_chat() ile tam sürümü kullanabilirsiniz.")
202
+
203
+ except Exception as e:
204
+ print(f"❌ Demo hatası: {e}")
205
+ print("Manuel olarak test.py'yi çalıştırmayı deneyin.")
206
+
207
+ if __name__ == "__main__":
208
+ # Kurulumu çalıştır
209
+ success = main()
210
+
211
+ # Başarılıysa demo sor
212
+ if success:
213
+ print("\n" + "="*60)
214
+ demo_choice = input("Hızlı demo çalıştırmak ister misiniz? (y/N): ").strip().lower()
215
+ if demo_choice == 'y':
216
+ run_quick_demo()
217
+ else:
218
+ print("Demo atlandı. Manuel olarak test.py'yi çalıştırabilirsiniz.")
create_high_ram_vm.sh ADDED
@@ -0,0 +1,188 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ # FitTürkAI RAG System - High RAM Google Cloud VM Creator
4
+ # CPU Optimized for Maximum Performance
5
+
6
+ echo "🚀 FitTürkAI için Yüksek RAM'li Google Cloud VM Oluşturucu"
7
+ echo "============================================================"
8
+
9
+ # Colors for output
10
+ RED='\033[0;31m'
11
+ GREEN='\033[0;32m'
12
+ YELLOW='\033[1;33m'
13
+ BLUE='\033[0;34m'
14
+ NC='\033[0m' # No Color
15
+
16
+ # Configuration variables
17
+ PROJECT_ID=""
18
+ VM_NAME="fitturkrai-high-ram"
19
+ ZONE="us-central1-a"
20
+ REGION="us-central1"
21
+
22
+ # RAM Seçenekleri (CPU optimize)
23
+ echo -e "${BLUE}📊 Mevcut RAM Seçenekleri:${NC}"
24
+ echo "1. n2-highmem-2: 2 vCPU, 16 GB RAM (~$100/ay) [Temel]"
25
+ echo "2. n2-highmem-4: 4 vCPU, 32 GB RAM (~$200/ay) [Önerilen]"
26
+ echo "3. n2-highmem-8: 8 vCPU, 64 GB RAM (~$400/ay) [Yüksek Performans]"
27
+ echo "4. n2-highmem-16: 16 vCPU, 128 GB RAM (~$800/ay) [Maksimum]"
28
+ echo "5. n2-highmem-32: 32 vCPU, 256 GB RAM (~$1600/ay) [Ultra]"
29
+ echo "6. m2-ultramem-416: 416 vCPU, 5.9 TB RAM (~$30000/ay) [Extreme - Sadece özel durumlar]"
30
+
31
+ echo ""
32
+ read -p "🔢 Seçiminizi yapın (1-6): " choice
33
+
34
+ case $choice in
35
+ 1)
36
+ MACHINE_TYPE="n2-highmem-2"
37
+ RAM_GB="16"
38
+ ;;
39
+ 2)
40
+ MACHINE_TYPE="n2-highmem-4"
41
+ RAM_GB="32"
42
+ ;;
43
+ 3)
44
+ MACHINE_TYPE="n2-highmem-8"
45
+ RAM_GB="64"
46
+ ;;
47
+ 4)
48
+ MACHINE_TYPE="n2-highmem-16"
49
+ RAM_GB="128"
50
+ ;;
51
+ 5)
52
+ MACHINE_TYPE="n2-highmem-32"
53
+ RAM_GB="256"
54
+ ;;
55
+ 6)
56
+ MACHINE_TYPE="m2-ultramem-416"
57
+ RAM_GB="5888"
58
+ echo -e "${RED}⚠️ UYARI: Bu çok pahalı bir seçenek! Sadece özel durumlar için.${NC}"
59
+ read -p "Devam etmek istediğinizden emin misiniz? (y/N): " confirm
60
+ if [[ $confirm != "y" ]]; then
61
+ echo "İşlem iptal edildi."
62
+ exit 1
63
+ fi
64
+ ;;
65
+ *)
66
+ echo -e "${RED}❌ Geçersiz seçim! Varsayılan olarak n2-highmem-4 kullanılacak.${NC}"
67
+ MACHINE_TYPE="n2-highmem-4"
68
+ RAM_GB="32"
69
+ ;;
70
+ esac
71
+
72
+ echo -e "${GREEN}✅ Seçilen: ${MACHINE_TYPE} (${RAM_GB} GB RAM)${NC}"
73
+
74
+ # Project ID kontrolü
75
+ if [ -z "$PROJECT_ID" ]; then
76
+ echo ""
77
+ echo -e "${YELLOW}🏗️ Google Cloud Project ID gerekli${NC}"
78
+ read -p "Project ID'nizi girin: " PROJECT_ID
79
+ fi
80
+
81
+ # Disk boyutu seçimi
82
+ echo ""
83
+ echo -e "${BLUE}💽 Disk Boyutu Seçimi:${NC}"
84
+ echo "1. 50 GB [Temel - Sadece sistem]"
85
+ echo "2. 100 GB [Önerilen - Modeller + veri]"
86
+ echo "3. 200 GB [Yüksek - Büyük veri setleri]"
87
+ echo "4. 500 GB [Maksimum - Çok büyük modeller]"
88
+
89
+ read -p "Disk boyutunu seçin (1-4): " disk_choice
90
+
91
+ case $disk_choice in
92
+ 1) DISK_SIZE="50" ;;
93
+ 2) DISK_SIZE="100" ;;
94
+ 3) DISK_SIZE="200" ;;
95
+ 4) DISK_SIZE="500" ;;
96
+ *)
97
+ echo -e "${YELLOW}⚠️ Varsayılan 100GB kullanılacak${NC}"
98
+ DISK_SIZE="100"
99
+ ;;
100
+ esac
101
+
102
+ # VM oluşturma komutu
103
+ echo ""
104
+ echo -e "${BLUE}🚀 VM oluşturuluyor...${NC}"
105
+
106
+ # Startup script içeriği
107
+ STARTUP_SCRIPT="#!/bin/bash
108
+ # FitTürkAI Setup Script
109
+ apt-get update && apt-get upgrade -y
110
+ apt-get install -y python3 python3-pip python3-venv git htop tree curl wget
111
+
112
+ # Python environment setup
113
+ python3 -m pip install --upgrade pip
114
+ pip3 install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cpu
115
+
116
+ # Clone repository (replace with your repo)
117
+ # git clone https://github.com/YOUR_USERNAME/FitTurkAI-RAG.git /home/ubuntu/FitTurkAI-RAG
118
+ # chown -R ubuntu:ubuntu /home/ubuntu/FitTurkAI-RAG
119
+
120
+ # System optimizations for high RAM
121
+ echo 'vm.swappiness=10' >> /etc/sysctl.conf
122
+ echo 'vm.vfs_cache_pressure=50' >> /etc/sysctl.conf
123
+ sysctl -p
124
+
125
+ # Install monitoring tools
126
+ apt-get install -y iotop nethogs
127
+
128
+ echo 'FitTürkAI VM setup completed!' >> /var/log/startup-script.log
129
+ "
130
+
131
+ # VM oluştur
132
+ gcloud compute instances create $VM_NAME \
133
+ --project=$PROJECT_ID \
134
+ --zone=$ZONE \
135
+ --machine-type=$MACHINE_TYPE \
136
+ --network-interface=network-tier=PREMIUM,stack-type=IPV4_ONLY,subnet=default \
137
+ --metadata="startup-script=$STARTUP_SCRIPT" \
138
+ --maintenance-policy=MIGRATE \
139
+ --provisioning-model=STANDARD \
140
+ --service-account=default \
141
+ --scopes=https://www.googleapis.com/auth/cloud-platform \
142
+ --tags=fitturkrai,http-server,https-server \
143
+ --create-disk=auto-delete=yes,boot=yes,device-name=$VM_NAME,image=projects/ubuntu-os-cloud/global/images/ubuntu-2204-jammy-v20240319,mode=rw,size=$DISK_SIZE,type=projects/$PROJECT_ID/zones/$ZONE/diskTypes/pd-balanced \
144
+ --no-shielded-secure-boot \
145
+ --shielded-vtpm \
146
+ --shielded-integrity-monitoring \
147
+ --labels=purpose=ml,project=fitturkrai \
148
+ --reservation-affinity=any
149
+
150
+ if [ $? -eq 0 ]; then
151
+ echo -e "${GREEN}✅ VM başarıyla oluşturuldu!${NC}"
152
+ echo ""
153
+ echo -e "${BLUE}📋 VM Bilgileri:${NC}"
154
+ echo " Ad: $VM_NAME"
155
+ echo " Tip: $MACHINE_TYPE"
156
+ echo " RAM: ${RAM_GB} GB"
157
+ echo " Disk: ${DISK_SIZE} GB"
158
+ echo " Zone: $ZONE"
159
+ echo ""
160
+
161
+ # IP adresini al
162
+ EXTERNAL_IP=$(gcloud compute instances describe $VM_NAME --zone=$ZONE --format='get(networkInterfaces[0].accessConfigs[0].natIP)')
163
+ echo -e "${GREEN}🌐 External IP: $EXTERNAL_IP${NC}"
164
+ echo ""
165
+
166
+ echo -e "${BLUE}🔗 Bağlantı Komutları:${NC}"
167
+ echo " SSH: gcloud compute ssh $VM_NAME --zone=$ZONE"
168
+ echo " SSH Direct: ssh ubuntu@$EXTERNAL_IP"
169
+ echo ""
170
+
171
+ echo -e "${YELLOW}⏳ VM'nin hazır olması için ~2-3 dakika bekleyin${NC}"
172
+ echo -e "${BLUE}📦 Sonraki adımlar:${NC}"
173
+ echo "1. SSH ile bağlanın"
174
+ echo "2. Repository'yi klonlayın"
175
+ echo "3. FitTürkAI sistemini kurun"
176
+
177
+ # SSH bağlantısı sor
178
+ echo ""
179
+ read -p "🔌 Şimdi SSH ile bağlanmak ister misiniz? (y/N): " connect_now
180
+ if [[ $connect_now == "y" ]]; then
181
+ echo "SSH bağlantısı kuruluyor..."
182
+ gcloud compute ssh $VM_NAME --zone=$ZONE
183
+ fi
184
+
185
+ else
186
+ echo -e "${RED}❌ VM oluşturma başarısız!${NC}"
187
+ exit 1
188
+ fi
cudatest.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ import torch
2
+ print(f"CUDA available: {torch.cuda.is_available()}")
3
+ print(f"CUDA version: {torch.version.cuda}")
4
+ print(f"Device count: {torch.cuda.device_count()}")
5
+ if torch.cuda.is_available():
6
+ print(f"Current device: {torch.cuda.current_device()}")
7
+ print(f"Device name: {torch.cuda.get_device_name(0)}")
download_models_gdown.py ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Alternative download script using gdown for Google Drive files.
4
+ Install: pip install gdown
5
+ """
6
+
7
+ import os
8
+ import zipfile
9
+ from pathlib import Path
10
+ import logging
11
+
12
+ logging.basicConfig(level=logging.INFO)
13
+ logger = logging.getLogger(__name__)
14
+
15
+ def download_with_gdown(file_id, destination):
16
+ """Download using gdown library (install with: pip install gdown)."""
17
+ try:
18
+ import gdown
19
+ except ImportError:
20
+ raise ImportError("gdown library not found. Install with: pip install gdown")
21
+
22
+ url = f"https://drive.google.com/uc?id={file_id}"
23
+ gdown.download(url, destination, quiet=False)
24
+ logger.info(f"Downloaded with gdown: {destination}")
25
+
26
+ def extract_zip(zip_path, extract_to):
27
+ """Extract zip file to destination."""
28
+ with zipfile.ZipFile(zip_path, 'r') as zip_ref:
29
+ zip_ref.extractall(extract_to)
30
+ logger.info(f"Extracted: {zip_path} -> {extract_to}")
31
+
32
+ # Remove zip file after extraction
33
+ os.remove(zip_path)
34
+ logger.info(f"Cleaned up: {zip_path}")
35
+
36
+ def main():
37
+ """Download using gdown method."""
38
+ current_dir = Path(__file__).parent
39
+
40
+ downloads = {
41
+ "fine_tuned_model.zip": {
42
+ "file_id": "1op6uXSfuXKEleLhZNQGcPWmsfbV9ocQL",
43
+ "extract_to": current_dir,
44
+ "folder_name": "fine_tuned_FitTurkAI_QLoRA"
45
+ },
46
+ "vector_store.zip": {
47
+ "file_id": "16m5c9tOUVw_vwkUzxxt7HYL6mdKS2taV",
48
+ "extract_to": current_dir,
49
+ "folder_name": "fitness_rag_store_merged"
50
+ }
51
+ }
52
+
53
+ # First try to install gdown
54
+ try:
55
+ import gdown
56
+ except ImportError:
57
+ print("📦 Installing gdown library...")
58
+ import subprocess
59
+ import sys
60
+ subprocess.check_call([sys.executable, "-m", "pip", "install", "gdown"])
61
+ import gdown
62
+
63
+ for filename, config in downloads.items():
64
+ folder_path = current_dir / config["folder_name"]
65
+
66
+ # Skip if folder already exists
67
+ if folder_path.exists():
68
+ logger.info(f"✅ {config['folder_name']} already exists, skipping download")
69
+ continue
70
+
71
+ logger.info(f"📥 Downloading {filename} with gdown...")
72
+ zip_path = current_dir / filename
73
+
74
+ try:
75
+ download_with_gdown(config["file_id"], str(zip_path))
76
+ extract_zip(str(zip_path), str(config["extract_to"]))
77
+ logger.info(f"✅ {config['folder_name']} ready!")
78
+ except Exception as e:
79
+ logger.error(f"❌ Failed to download {filename}: {e}")
80
+ # Clean up failed download
81
+ if zip_path.exists():
82
+ os.remove(str(zip_path))
83
+
84
+ if __name__ == "__main__":
85
+ main()
quick_vm_commands.md ADDED
@@ -0,0 +1,180 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚀 FitTürkAI - Yüksek RAM'li Google Cloud VM Hızlı Komutları
2
+
3
+ ## 💰 RAM ve Maliyet Tablosu
4
+
5
+ | VM Tipi | vCPU | RAM | Aylık Maliyet* | Kullanım Durumu |
6
+ |---------|------|-----|----------------|-----------------|
7
+ | **n2-highmem-2** | 2 | 16 GB | ~$100 | Küçük modeller, test |
8
+ | **n2-highmem-4** | 4 | 32 GB | ~$200 | **Önerilen** - Orta boyut |
9
+ | **n2-highmem-8** | 8 | 64 GB | ~$400 | Büyük modeller |
10
+ | **n2-highmem-16** | 16 | 128 GB | ~$800 | **Maksimum** pratik |
11
+ | **n2-highmem-32** | 32 | 256 GB | ~$1600 | Çok büyük modeller |
12
+ | **m1-ultramem-40** | 40 | 961 GB | ~$6000 | Extreme durum |
13
+
14
+ *Yaklaşık maliyetler, gerçek fiyatlar değişebilir
15
+
16
+ ## 🎯 Önerilen Konfigürasyonlar
17
+
18
+ ### 1. **En Çok Önerilen**: n2-highmem-8 (64 GB RAM)
19
+ ```bash
20
+ # Maksimum performans için ideal
21
+ gcloud compute instances create fitturkrai-vm \
22
+ --machine-type=n2-highmem-8 \
23
+ --zone=us-central1-a \
24
+ --image-family=ubuntu-2204-lts \
25
+ --image-project=ubuntu-os-cloud \
26
+ --boot-disk-size=100GB \
27
+ --boot-disk-type=pd-balanced \
28
+ --tags=fitturkrai \
29
+ --metadata-from-file startup-script=startup-script.sh
30
+ ```
31
+
32
+ ### 2. **Maksimum CPU RAM**: n2-highmem-16 (128 GB RAM)
33
+ ```bash
34
+ # En yüksek pratik RAM
35
+ gcloud compute instances create fitturkrai-max-vm \
36
+ --machine-type=n2-highmem-16 \
37
+ --zone=us-central1-a \
38
+ --image-family=ubuntu-2204-lts \
39
+ --image-project=ubuntu-os-cloud \
40
+ --boot-disk-size=200GB \
41
+ --boot-disk-type=pd-balanced \
42
+ --tags=fitturkrai \
43
+ --metadata-from-file startup-script=startup-script.sh
44
+ ```
45
+
46
+ ### 3. **Ultra RAM**: n2-highmem-32 (256 GB RAM)
47
+ ```bash
48
+ # En yüksek RAM (pahalı!)
49
+ gcloud compute instances create fitturkrai-ultra-vm \
50
+ --machine-type=n2-highmem-32 \
51
+ --zone=us-central1-a \
52
+ --image-family=ubuntu-2204-lts \
53
+ --image-project=ubuntu-os-cloud \
54
+ --boot-disk-size=500GB \
55
+ --boot-disk-type=pd-balanced \
56
+ --tags=fitturkrai \
57
+ --metadata-from-file startup-script=startup-script.sh
58
+ ```
59
+
60
+ ## 💡 CPU Optimize Ayarları
61
+
62
+ ### test.py için RAM optimizasyonu:
63
+ ```python
64
+ # Yüksek RAM'li VM'ler için config
65
+ config = RAGConfig(
66
+ chunk_size=500, # Daha büyük chunk'lar
67
+ retrieval_k=10, # Daha fazla belge
68
+ max_context_length=8000 # Daha uzun context
69
+ )
70
+ ```
71
+
72
+ ### Sistem ayarları (VM'de çalıştırın):
73
+ ```bash
74
+ # Yüksek RAM için optimizasyon
75
+ sudo sysctl -w vm.swappiness=1
76
+ sudo sysctl -w vm.vfs_cache_pressure=50
77
+ echo 'vm.overcommit_memory=1' | sudo tee -a /etc/sysctl.conf
78
+ ```
79
+
80
+ ## 🚀 Hızlı Kurulum
81
+
82
+ ### 1. VM oluştur (interactive script)
83
+ ```bash
84
+ chmod +x create_high_ram_vm.sh
85
+ ./create_high_ram_vm.sh
86
+ ```
87
+
88
+ ### 2. Manuel hızlı komut (64GB RAM)
89
+ ```bash
90
+ export PROJECT_ID="your-project-id"
91
+ export VM_NAME="fitturkrai-vm"
92
+
93
+ gcloud compute instances create $VM_NAME \
94
+ --project=$PROJECT_ID \
95
+ --zone=us-central1-a \
96
+ --machine-type=n2-highmem-8 \
97
+ --network-interface=network-tier=PREMIUM,subnet=default \
98
+ --maintenance-policy=MIGRATE \
99
+ --provisioning-model=STANDARD \
100
+ --service-account=default \
101
+ --scopes=https://www.googleapis.com/auth/cloud-platform \
102
+ --tags=fitturkrai \
103
+ --create-disk=auto-delete=yes,boot=yes,device-name=$VM_NAME,image=projects/ubuntu-os-cloud/global/images/ubuntu-2204-jammy-v20240319,mode=rw,size=100,type=projects/$PROJECT_ID/zones/us-central1-a/diskTypes/pd-balanced \
104
+ --reservation-affinity=any
105
+ ```
106
+
107
+ ### 3. SSH bağlantı
108
+ ```bash
109
+ gcloud compute ssh fitturkrai-vm --zone=us-central1-a
110
+ ```
111
+
112
+ ## 📊 RAM Kullanım İzleme
113
+
114
+ ### VM'de RAM durumunu kontrol:
115
+ ```bash
116
+ # Genel sistem durumu
117
+ htop
118
+
119
+ # RAM kullanımı
120
+ free -h
121
+
122
+ # Detaylı RAM istatistikleri
123
+ cat /proc/meminfo
124
+
125
+ # Python process RAM kullanımı
126
+ ps aux | grep python | awk '{print $4, $11}'
127
+ ```
128
+
129
+ ## 🔧 Troubleshooting
130
+
131
+ ### RAM yetersizse:
132
+ 1. **Chunk size küçült**: `chunk_size=200`
133
+ 2. **Context length azalt**: `max_context_length=2000`
134
+ 3. **Retrieval sayısı azalt**: `retrieval_k=3`
135
+
136
+ ### VM boyutunu artır:
137
+ ```bash
138
+ # VM'yi durdur
139
+ gcloud compute instances stop fitturkrai-vm --zone=us-central1-a
140
+
141
+ # Makine tipini değiştir
142
+ gcloud compute instances set-machine-type fitturkrai-vm \
143
+ --machine-type=n2-highmem-16 \
144
+ --zone=us-central1-a
145
+
146
+ # VM'yi başlat
147
+ gcloud compute instances start fitturkrai-vm --zone=us-central1-a
148
+ ```
149
+
150
+ ## 💰 Maliyet Optimizasyonu
151
+
152
+ ### 1. Preemptible Instance (75% indirim):
153
+ ```bash
154
+ --preemptible \
155
+ --maintenance-policy=TERMINATE
156
+ ```
157
+
158
+ ### 2. Spot Instance (80% indirim):
159
+ ```bash
160
+ --provisioning-model=SPOT \
161
+ --instance-termination-action=STOP
162
+ ```
163
+
164
+ ### 3. Committed Use Discounts:
165
+ - 1 yıl: %20 indirim
166
+ - 3 yıl: %30 indirim
167
+
168
+ ## 🎯 En İyi Performans için Öneriler
169
+
170
+ ### RAM için:
171
+ - **n2-highmem-8** (64GB) - En optimal
172
+ - **n2-highmem-16** (128GB) - Maksimum pratik
173
+
174
+ ### Disk için:
175
+ - **pd-balanced** - Performans/fiyat dengesi
176
+ - **pd-ssd** - Maksimum hız (pahalı)
177
+
178
+ ### Zone için:
179
+ - **us-central1-a** - En stabil
180
+ - **europe-west1-b** - Avrupa için
requirements.txt ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # CPU-optimized dependencies for FitTürkAI RAG system (Linux Compatible)
2
+ # Core ML libraries - CPU versions with compatible versions
3
+ torch>=2.0.0,<2.2.0 # Stable version for CPU
4
+ transformers>=4.36.0,<4.40.0 # Compatible with PEFT 0.7.x
5
+ sentence-transformers>=2.2.2,<3.0.0 # Lightweight embeddings
6
+ accelerate>=0.24.0,<0.26.0 # For model loading optimization
7
+
8
+ # PEFT with compatible version
9
+ peft>=0.7.0,<0.8.0 # For LoRA adapters - compatible with transformers 4.36-4.39
10
+
11
+ # Text processing
12
+ nltk>=3.8
13
+ regex>=2022.10.31
14
+
15
+ # Vector storage and search
16
+ faiss-cpu>=1.7.4 # CPU-only FAISS
17
+ numpy>=1.24.0,<2.0.0
18
+ scipy>=1.9.0
19
+
20
+ # PDF processing
21
+ PyPDF2>=3.0.0
22
+ PyMuPDF>=1.23.0 # fitz library for robust PDF text extraction
23
+ pymupdf>=1.23.0 # Alternative name for PyMuPDF
24
+
25
+ # Essential utilities
26
+ tqdm>=4.64.0
27
+ requests>=2.28.0
28
+ gdown>=4.7.0 # For Google Drive downloads
29
+ pathlib2>=2.3.0 # Enhanced pathlib for better compatibility
30
+ pickle5>=0.0.11 # Better pickle support
31
+
32
+ # Data handling
33
+ pandas>=1.5.0 # For data manipulation if needed
34
+ datasets>=2.14.0 # For dataset handling
35
+
36
+ # Optional but recommended for better performance
37
+ tokenizers>=0.15.0 # Fast tokenization
38
+ safetensors>=0.3.0 # For safer model loading
39
+
40
+ # Google Colab specific utilities (uncomment if running on Colab)
41
+ # google-colab
42
+ # ipywidgets
43
+
44
+ # System utilities for Linux
45
+ psutil>=5.9.0 # System monitoring
startup-script.sh ADDED
@@ -0,0 +1,339 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ # FitTürkAI RAG System - VM Startup Script
4
+ # CPU Optimized with High RAM Configuration
5
+
6
+ set -e # Exit on any error
7
+
8
+ LOG_FILE="/var/log/fitturkrai-setup.log"
9
+ exec > >(tee -a $LOG_FILE)
10
+ exec 2>&1
11
+
12
+ echo "=================================================="
13
+ echo "🚀 FitTürkAI RAG System Setup Starting..."
14
+ echo "Timestamp: $(date)"
15
+ echo "=================================================="
16
+
17
+ # Update system
18
+ echo "📦 Updating system packages..."
19
+ apt-get update && apt-get upgrade -y
20
+
21
+ # Install essential packages
22
+ echo "🔧 Installing essential packages..."
23
+ apt-get install -y \
24
+ python3 \
25
+ python3-pip \
26
+ python3-venv \
27
+ python3-dev \
28
+ git \
29
+ curl \
30
+ wget \
31
+ htop \
32
+ tree \
33
+ unzip \
34
+ vim \
35
+ build-essential \
36
+ software-properties-common \
37
+ apt-transport-https \
38
+ ca-certificates \
39
+ gnupg \
40
+ lsb-release
41
+
42
+ # Install monitoring tools
43
+ echo "📊 Installing monitoring tools..."
44
+ apt-get install -y \
45
+ iotop \
46
+ nethogs \
47
+ nload \
48
+ glances \
49
+ ncdu
50
+
51
+ # Upgrade pip
52
+ echo "🐍 Setting up Python environment..."
53
+ python3 -m pip install --upgrade pip
54
+
55
+ # Install CPU-optimized PyTorch
56
+ echo "🔥 Installing PyTorch (CPU version)..."
57
+ pip3 install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cpu
58
+
59
+ # Install core ML packages for CPU
60
+ echo "🤖 Installing ML packages..."
61
+ pip3 install \
62
+ transformers>=4.36.0,\<4.40.0 \
63
+ sentence-transformers>=2.2.2,\<3.0.0 \
64
+ accelerate>=0.24.0,\<0.26.0 \
65
+ peft>=0.7.0,\<0.8.0 \
66
+ nltk>=3.8 \
67
+ faiss-cpu>=1.7.4 \
68
+ numpy>=1.24.0,\<2.0.0 \
69
+ scipy>=1.9.0 \
70
+ PyPDF2>=3.0.0 \
71
+ PyMuPDF>=1.23.0 \
72
+ tqdm>=4.64.0 \
73
+ requests>=2.28.0 \
74
+ datasets>=2.14.0
75
+
76
+ # System optimizations for high RAM
77
+ echo "⚡ Configuring system for high RAM usage..."
78
+
79
+ # Swap settings (minimize swap usage)
80
+ echo 'vm.swappiness=1' >> /etc/sysctl.conf
81
+ echo 'vm.vfs_cache_pressure=50' >> /etc/sysctl.conf
82
+ echo 'vm.dirty_ratio=15' >> /etc/sysctl.conf
83
+ echo 'vm.dirty_background_ratio=5' >> /etc/sysctl.conf
84
+
85
+ # Memory overcommit (allow more memory allocation)
86
+ echo 'vm.overcommit_memory=1' >> /etc/sysctl.conf
87
+ echo 'vm.overcommit_ratio=80' >> /etc/sysctl.conf
88
+
89
+ # Network optimizations
90
+ echo 'net.core.rmem_max=16777216' >> /etc/sysctl.conf
91
+ echo 'net.core.wmem_max=16777216' >> /etc/sysctl.conf
92
+
93
+ # Apply system settings
94
+ sysctl -p
95
+
96
+ # Configure user limits for high memory usage
97
+ echo "🔒 Configuring user limits..."
98
+ cat >> /etc/security/limits.conf << EOF
99
+ ubuntu soft memlock unlimited
100
+ ubuntu hard memlock unlimited
101
+ ubuntu soft stack unlimited
102
+ ubuntu hard stack unlimited
103
+ EOF
104
+
105
+ # Create FitTürkAI directory structure
106
+ echo "📁 Creating directory structure..."
107
+ sudo -u ubuntu mkdir -p /home/ubuntu/FitTurkAI-RAG
108
+ sudo -u ubuntu mkdir -p /home/ubuntu/FitTurkAI-RAG/indirilen_pdfler
109
+ sudo -u ubuntu mkdir -p /home/ubuntu/FitTurkAI-RAG/DATA
110
+ sudo -u ubuntu mkdir -p /home/ubuntu/FitTurkAI-RAG/fitness_rag_store_merged
111
+ sudo -u ubuntu mkdir -p /home/ubuntu/FitTurkAI-RAG/fine_tuned_FitTurkAI_QLoRA
112
+
113
+ # Set ownership
114
+ chown -R ubuntu:ubuntu /home/ubuntu/FitTurkAI-RAG
115
+
116
+ # Create demo data
117
+ echo "📝 Creating demo data..."
118
+ sudo -u ubuntu cat > /home/ubuntu/FitTurkAI-RAG/DATA/demo_fitness_data.json << 'EOF'
119
+ [
120
+ {
121
+ "soru": "Sağlıklı kahvaltı için ne önerirsiniz?",
122
+ "cevap": "Sağlıklı bir kahvaltı protein, kompleks karbonhidrat ve sağlıklı yağlar içermelidir. Yumurta, tam tahıllı ekmek, avokado, meyveler ve kuruyemişler iyi seçeneklerdir. Ayrıca bol su içmeyi unutmayın."
123
+ },
124
+ {
125
+ "soru": "Günde kaç bardak su içmeliyim?",
126
+ "cevap": "Genel olarak günde 8-10 bardak (2-2.5 litre) su içmek önerilir. Aktivite düzeyinize, hava durumuna ve vücut ağırlığınıza göre bu miktar artabilir. Egzersiz yaptığınız günlerde daha fazla su tüketmelisiniz."
127
+ },
128
+ {
129
+ "soru": "Egzersiz sonrası ne yemeli?",
130
+ "cevap": "Egzersiz sonrası 30-60 dakika içinde protein ve karbonhidrat içeren besinler tüketin. Protein kas onarımı için, karbonhidrat ise enerji depolarını yenilemek için gereklidir. Örneğin protein smoothie, yoğurt ile meyve veya tavuk göğsü ile pirinç iyi seçeneklerdir."
131
+ },
132
+ {
133
+ "soru": "Kilo vermek için hangi egzersizleri yapmalıyım?",
134
+ "cevap": "Kilo vermek için kardiyovasküler egzersizler (yürüyüş, koşu, bisiklet) ve direnç antrenmanlarını (ağırlık kaldırma) birleştirin. Haftada en az 150 dakika orta yoğunlukta kardiyovasküler aktivite yapın. Ayrıca kas kütlesini korumak için haftada 2-3 gün kuvvet antrenmanı ekleyin."
135
+ }
136
+ ]
137
+ EOF
138
+
139
+ # Create system info script
140
+ echo "ℹ️ Creating system info script..."
141
+ sudo -u ubuntu cat > /home/ubuntu/system_info.sh << 'EOF'
142
+ #!/bin/bash
143
+ echo "=== FitTürkAI VM System Information ==="
144
+ echo "Date: $(date)"
145
+ echo "Uptime: $(uptime)"
146
+ echo ""
147
+ echo "=== CPU Information ==="
148
+ lscpu | grep -E 'Model name|CPU\(s\)|Thread'
149
+ echo ""
150
+ echo "=== Memory Information ==="
151
+ free -h
152
+ echo ""
153
+ echo "=== Disk Usage ==="
154
+ df -h
155
+ echo ""
156
+ echo "=== GPU Information ==="
157
+ if command -v nvidia-smi &> /dev/null; then
158
+ nvidia-smi
159
+ else
160
+ echo "No GPU detected (CPU-only configuration)"
161
+ fi
162
+ echo ""
163
+ echo "=== Python Packages ==="
164
+ pip3 list | grep -E 'torch|transformers|sentence|faiss|peft'
165
+ echo ""
166
+ echo "=== System Load ==="
167
+ top -n 1 -b | head -20
168
+ EOF
169
+
170
+ chmod +x /home/ubuntu/system_info.sh
171
+ chown ubuntu:ubuntu /home/ubuntu/system_info.sh
172
+
173
+ # Create RAM monitoring script
174
+ echo "📊 Creating RAM monitoring script..."
175
+ sudo -u ubuntu cat > /home/ubuntu/monitor_ram.sh << 'EOF'
176
+ #!/bin/bash
177
+ echo "=== Real-time RAM Monitoring ==="
178
+ while true; do
179
+ clear
180
+ echo "FitTürkAI RAM Monitor - $(date)"
181
+ echo "================================"
182
+ free -h
183
+ echo ""
184
+ echo "Top 10 Memory Consuming Processes:"
185
+ ps aux --sort=-%mem | head -11
186
+ echo ""
187
+ echo "Press Ctrl+C to exit"
188
+ sleep 5
189
+ done
190
+ EOF
191
+
192
+ chmod +x /home/ubuntu/monitor_ram.sh
193
+ chown ubuntu:ubuntu /home/ubuntu/monitor_ram.sh
194
+
195
+ # Install performance monitoring alias
196
+ echo "📈 Setting up monitoring aliases..."
197
+ sudo -u ubuntu cat >> /home/ubuntu/.bashrc << 'EOF'
198
+
199
+ # FitTürkAI Monitoring Aliases
200
+ alias sysinfo='/home/ubuntu/system_info.sh'
201
+ alias rammon='/home/ubuntu/monitor_ram.sh'
202
+ alias fitturkrai='cd /home/ubuntu/FitTurkAI-RAG'
203
+ alias pyfree='python3 -c "import psutil; print(f\"Available RAM: {psutil.virtual_memory().available/1024**3:.1f} GB\")"'
204
+
205
+ # Python environment
206
+ export PYTHONPATH=/home/ubuntu/FitTurkAI-RAG:$PYTHONPATH
207
+
208
+ echo "🏋️ Welcome to FitTürkAI High-RAM VM!"
209
+ echo "Available commands:"
210
+ echo " sysinfo - System information"
211
+ echo " rammon - RAM monitoring"
212
+ echo " fitturkrai - Go to project directory"
213
+ echo " pyfree - Check available Python memory"
214
+ EOF
215
+
216
+ # Download NLTK data
217
+ echo "📚 Downloading NLTK data..."
218
+ sudo -u ubuntu python3 -c "
219
+ import nltk
220
+ import ssl
221
+ try:
222
+ _create_unverified_https_context = ssl._create_unverified_context
223
+ except AttributeError:
224
+ pass
225
+ else:
226
+ ssl._create_default_https_context = _create_unverified_https_context
227
+
228
+ try:
229
+ nltk.download('punkt', quiet=True)
230
+ nltk.download('punkt_tab', quiet=True)
231
+ nltk.download('stopwords', quiet=True)
232
+ print('NLTK data downloaded successfully!')
233
+ except Exception as e:
234
+ print(f'NLTK download warning: {e}')
235
+ "
236
+
237
+ # Create performance test script
238
+ echo "🧪 Creating performance test script..."
239
+ sudo -u ubuntu cat > /home/ubuntu/performance_test.py << 'EOF'
240
+ #!/usr/bin/env python3
241
+ """
242
+ FitTürkAI Performance Test Script
243
+ Tests system capabilities for CPU-based RAG operations
244
+ """
245
+
246
+ import time
247
+ import psutil
248
+ import numpy as np
249
+ from sentence_transformers import SentenceTransformer
250
+
251
+ def test_memory():
252
+ """Test available memory"""
253
+ memory = psutil.virtual_memory()
254
+ print(f"💾 Total RAM: {memory.total / 1024**3:.1f} GB")
255
+ print(f"💾 Available RAM: {memory.available / 1024**3:.1f} GB")
256
+ print(f"💾 Used RAM: {memory.percent}%")
257
+ return memory.available > 2 * 1024**3 # At least 2GB free
258
+
259
+ def test_cpu():
260
+ """Test CPU performance"""
261
+ print(f"🔧 CPU Cores: {psutil.cpu_count()}")
262
+ print(f"🔧 CPU Usage: {psutil.cpu_percent(interval=1)}%")
263
+ return True
264
+
265
+ def test_sentence_transformer():
266
+ """Test sentence transformer loading"""
267
+ try:
268
+ print("🤖 Testing Sentence Transformer...")
269
+ model = SentenceTransformer('paraphrase-multilingual-MiniLM-L12-v2')
270
+
271
+ # Test encoding
272
+ texts = ["Bu bir test cümlesidir.", "FitTürkAI sistemi çalışıyor."]
273
+ start_time = time.time()
274
+ embeddings = model.encode(texts)
275
+ encoding_time = time.time() - start_time
276
+
277
+ print(f"✅ Sentence Transformer loaded successfully!")
278
+ print(f"⏱️ Encoding time: {encoding_time:.2f}s")
279
+ print(f"📏 Embedding shape: {embeddings.shape}")
280
+ return True
281
+ except Exception as e:
282
+ print(f"❌ Sentence Transformer test failed: {e}")
283
+ return False
284
+
285
+ def main():
286
+ print("🚀 FitTürkAI Performance Test")
287
+ print("=" * 40)
288
+
289
+ # Test system components
290
+ memory_ok = test_memory()
291
+ cpu_ok = test_cpu()
292
+ transformer_ok = test_sentence_transformer()
293
+
294
+ print("\n" + "=" * 40)
295
+ print("📊 Test Results:")
296
+ print(f"💾 Memory: {'✅ OK' if memory_ok else '❌ INSUFFICIENT'}")
297
+ print(f"🔧 CPU: {'✅ OK' if cpu_ok else '❌ PROBLEM'}")
298
+ print(f"🤖 Transformers: {'✅ OK' if transformer_ok else '❌ FAILED'}")
299
+
300
+ if all([memory_ok, cpu_ok, transformer_ok]):
301
+ print("\n🎉 System ready for FitTürkAI!")
302
+ else:
303
+ print("\n⚠️ System needs optimization!")
304
+
305
+ if __name__ == "__main__":
306
+ main()
307
+ EOF
308
+
309
+ chmod +x /home/ubuntu/performance_test.py
310
+ chown ubuntu:ubuntu /home/ubuntu/performance_test.py
311
+
312
+ # Configure automatic updates
313
+ echo "🔄 Configuring automatic security updates..."
314
+ echo 'Unattended-Upgrade::Automatic-Reboot "false";' >> /etc/apt/apt.conf.d/50unattended-upgrades
315
+
316
+ # Final system status
317
+ echo ""
318
+ echo "=================================================="
319
+ echo "✅ FitTürkAI VM Setup Completed!"
320
+ echo "=================================================="
321
+ echo "📊 System Status:"
322
+ echo " - OS: $(lsb_release -d | cut -f2)"
323
+ echo " - Memory: $(free -h | awk 'NR==2{printf \"%.1f GB total, %.1f GB available\", $2/1024/1024, $7/1024/1024}')"
324
+ echo " - CPU: $(nproc) cores"
325
+ echo " - Python: $(python3 --version)"
326
+ echo ""
327
+ echo "🎯 Next Steps:"
328
+ echo "1. SSH to the VM: gcloud compute ssh [VM_NAME] --zone=[ZONE]"
329
+ echo "2. Run performance test: python3 /home/ubuntu/performance_test.py"
330
+ echo "3. Clone your FitTürkAI repository"
331
+ echo "4. Start the RAG system: python3 test.py"
332
+ echo ""
333
+ echo "📚 Useful Commands:"
334
+ echo " - sysinfo: System information"
335
+ echo " - rammon: RAM monitoring"
336
+ echo " - fitturkrai: Go to project directory"
337
+ echo ""
338
+ echo "Setup completed at: $(date)"
339
+ echo "=================================================="
test.py ADDED
@@ -0,0 +1,561 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # --- MERGED RAG & INTERACTION MODULE (CPU OPTIMIZED FOR LINUX) ---
2
+
3
+ import os
4
+ import json
5
+ import torch
6
+ import pickle
7
+ import logging
8
+ import re
9
+ import time
10
+ from typing import List, Dict, Optional, Tuple
11
+ from pathlib import Path
12
+ from dataclasses import dataclass, field
13
+
14
+ from transformers import AutoTokenizer, AutoModelForCausalLM
15
+ from peft import PeftModel
16
+ import torch
17
+
18
+ # PDF Processing
19
+ import PyPDF2
20
+ import fitz # PyMuPDF
21
+
22
+ # Sentence Transformers & Vector Store
23
+ from sentence_transformers import SentenceTransformer
24
+ import faiss
25
+
26
+ # NLTK for text processing
27
+ import nltk
28
+ from nltk.corpus import stopwords
29
+ from nltk.tokenize import sent_tokenize
30
+
31
+ # Transformers for Language Model Interaction
32
+ from transformers import AutoTokenizer, AutoModelForCausalLM
33
+ from peft import PeftModel
34
+
35
+ # --- Setup Logging ---
36
+ logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
37
+ logger = logging.getLogger(__name__)
38
+
39
+ # --- Configuration ---
40
+ @dataclass
41
+ class RAGConfig:
42
+ """Central configuration for the RAG system."""
43
+ # RAG parameters
44
+ vector_store_path: str = "./fitness_rag_store_merged"
45
+ chunk_size: int = 300 # Words per chunk
46
+ chunk_overlap_sentences: int = 2 # Number of sentences to overlap
47
+ retrieval_k: int = 5
48
+ retrieval_score_threshold: float = 0.2
49
+ max_context_length: int = 3000
50
+
51
+ # Model parameters
52
+ embedding_model_name: str = "paraphrase-multilingual-MiniLM-L12-v2"
53
+ generator_model_name: str = "ytu-ce-cosmos/Turkish-Llama-8b-v0.1"
54
+ peft_model_path: Optional[str] = None # Path to LoRA adapter, e.g., "./fine_tuned_FitTurkAI_LoRA"
55
+
56
+ DEFAULT_SYSTEM_PROMPT = SISTEM_TALIMATI = """
57
+ [ROL]
58
+ Sen "FitTürkAI" adında, bütünsel yaklaşıma sahip, empatik ve proaktif bir kişisel sağlıklı yaşam koçusun. Görevin yalnızca beslenme önerileri vermek değil, aynı zamanda kullanıcının fiziksel, zihinsel ve yaşam tarzına dair tüm faktörleri dikkate alarak uyarlanabilir rehberler sunmaktır. Sağlık profesyoneli değilsin, tıbbi teşhis veya tedavi öneremezsin. Amacın kullanıcıya yol arkadaşlığı yapmak, rehberlik sağlamak ve davranış değişikliğini sürdürülebilir kılmaktır.
59
+
60
+ [GÖREV TANIMI]
61
+ Kullanıcının profil verilerini analiz ederek ona özel, bütünsel ve sürdürülebilir bir "Sağlıklı Yaşam Rehberi" oluştur. Bu rehber:
62
+ - Beslenme planı
63
+ - Egzersiz planı
64
+ - Uyku düzeni
65
+ - Stres yönetimi stratejileri
66
+ - Su tüketim hedefleri
67
+ bileşenlerini içermelidir. Rehberin sonunda kullanıcıyı küçük bir mikro hedef belirlemeye teşvik et.
68
+
69
+ [İLETİŞİM ADIMLARI – ZORUNLU AKIŞ]
70
+ 1. *Tanıtım ve Uyarı:* Kendini "FitTürkAI" olarak tanıt, sağlık uzmanı olmadığını ve verdiğin bilgilerin sadece rehberlik amacı taşıdığını vurgula. Devam izni al.
71
+ 2. *Profil Toplama:* Kullanıcıdan şu verileri iste:
72
+ - Yaş, Cinsiyet, Kilo, Boy
73
+ - Sağlık durumu (diyabet, obezite, hipertansiyon, vb.)
74
+ - Beslenme tercihi/alerji (vejetaryen, glutensiz, vb.)
75
+ - Hedef (kilo vermek, enerji kazanmak, vb.)
76
+ - Fiziksel aktivite düzeyi
77
+ - Uyku süresi, stres düzeyi
78
+ 3. *Prensip Tanıtımı:* Kullanıcının durumuna özel 3–4 temel prensibi (örneğin: dengeli tabak, kan şekeri dengesi, stres ve uykunun etkisi) açıklayarak rehbere zemin hazırla.
79
+ 4. *Kişiselleştirilmiş Sağlıklı Yaşam Rehberi Sun:*
80
+ - *Beslenme*: Haftalık tablo veya örnek öğünler (tahmini kalori ve porsiyon bilgisiyle)
81
+ - *Egzersiz*: Haftalık FITT prensibine dayalı plan
82
+ - *Uyku & Stres*: Pratik iyileştirme önerileri
83
+ - *Su*: Hedef ve içme taktikleri
84
+ 5. *Mikro Hedef Belirleme:* Kullanıcıya küçük, uygulanabilir bir hedef seçtir ("Bu hafta neye odaklanalım?").
85
+ 6. *Kapanış:* Rehberin sonunda doktor desteğinin önemini tekrar vurgula. Net ve cesaret verici bir mesajla bitir.
86
+
87
+ [KURALLAR VE KISITLAR]
88
+ - ❌ *Yasaklı Terimler:* "Tedavi", "reçete", "kesin sonuç", "garanti", "zayıflama diyeti"
89
+ - ✅ *İzinli Terimler:* "Öneri", "yaklaşık plan", "rehber", "eğitim amaçlı"
90
+ - 🔎 *Kalori ve Porsiyonlar:* Daima "tahmini" ya da "yaklaşık" gibi ifadelerle sun. Öğünler sade, dengeli ve kültürel olarak uygun olmalı.
91
+ - 🚫 *Teşhis/Tedavi:* Teşhis koyamazsın, ilaç öneremezsin.
92
+ - ✅ *Üslup:* Nazik, empatik, motive edici. Net ve profesyonel. Markdown ile netlik sağla (*kalın, *italik, tablolar).
93
+
94
+ [DİNAMİK ADAPTASYON VE PROAKTİFLİK]
95
+ - Alerji/tercih bildirildiğinde otomatik alternatif öner.
96
+ - Plandan sapıldığında kullanıcıyı motive et, çözüme odaklan, ardından planı revize et (örneğin: "gofret yedim" diyorsa → daha hafif akşam öner).
97
+ - Her zaman kriz anlarını büyütmeden yönet.
98
+
99
+ [EGZERSİZ PLANI – KURALLAR]
100
+ 1. *Uyarı:* Egzersiz önerilerinin öncesinde doktor onayı gerektiğini açıkla.
101
+ 2. *FITT Analizi:* Egzersizleri profile göre planla (Sıklık, Yoğunluk, Süre, Tür).
102
+ 3. *Plan Formatı:* Haftalık tablo, güvenli hareketler, tekrar sayısı (örneğin: "formun bozulana kadar", ağırl��ksız öneri).
103
+ 4. *Gelişim Prensibi:* Kolaylaştıkça artırılabilecek yollar sun.
104
+
105
+ [EK YETENEKLER]
106
+ - Haftalık değerlendirme ("Geçen hafta nasıldı?")
107
+ - Tarif oluşturma
108
+ - Alışveriş listesi çıkarma
109
+ - "Neden bu yemek?" sorularını bilimsel ama sade cevaplama
110
+
111
+ [FEW-SHOT PROMPT – ÖRNEK]
112
+ *Kullanıcı:* Merhaba, kilo vermek istiyorum.
113
+ *FitTürkAI:* Merhaba! Ben FitTürkAI, yol arkadaşınız... [güvenlik uyarısı + devam onayı]
114
+ *Kullanıcı:* 35 yaş, erkek, obezite + hipertansiyon, memur, stresli, 5 saat uyuyor.
115
+ *FitTürkAI:* (Teşekkür + prensipler + beslenme tablosu + egzersiz planı + su + uyku + stres + mikro hedef + kapanış)
116
+
117
+ """
118
+
119
+ # --- Data Structures ---
120
+ @dataclass
121
+ class Document:
122
+ """Represents a document chunk with metadata."""
123
+ content: str
124
+ source: str
125
+ doc_type: str # 'pdf' or 'json'
126
+ chunk_id: str
127
+ metadata: Dict = field(default_factory=dict)
128
+
129
+ # --- Core RAG Components ---
130
+
131
+ class TurkishTextProcessor:
132
+ """Handles advanced Turkish text preprocessing, cleaning, and chunking."""
133
+ def __init__(self):
134
+ self.turk_to_ascii_map = str.maketrans('ğüşıöçĞÜŞİÖÇ', 'gusiocGUSIOC')
135
+ self.turkish_stopwords = {'ve', 'ile', 'bir', 'bu', 'da', 'de', 'için'}
136
+ self._download_nltk_data() # Call the corrected downloader
137
+ try:
138
+ self.turkish_stopwords = set(stopwords.words('turkish'))
139
+ except Exception:
140
+ logger.warning("Could not load Turkish stopwords, using a basic set.")
141
+
142
+ def _download_nltk_data(self):
143
+ """
144
+ Robustly downloads required NLTK data with proper error handling.
145
+ Handles both old (punkt) and new (punkt_tab) NLTK versions.
146
+ """
147
+ logger.info("Checking/downloading NLTK data...")
148
+
149
+ # List of packages to download with their alternatives
150
+ packages_to_try = [
151
+ ['punkt_tab', 'punkt'], # Try new version first, then old
152
+ ['stopwords']
153
+ ]
154
+
155
+ for package_group in packages_to_try:
156
+ success = False
157
+
158
+ if isinstance(package_group, list):
159
+ # Try each package in the group until one succeeds
160
+ for package in package_group:
161
+ try:
162
+ nltk.download(package, quiet=True)
163
+ logger.info(f"Successfully downloaded NLTK package: {package}")
164
+ success = True
165
+ break
166
+ except Exception as e:
167
+ logger.debug(f"Failed to download {package}: {e}")
168
+ continue
169
+ else:
170
+ # Single package
171
+ try:
172
+ nltk.download(package_group, quiet=True)
173
+ logger.info(f"Successfully downloaded NLTK package: {package_group}")
174
+ success = True
175
+ except Exception as e:
176
+ logger.debug(f"Failed to download {package_group}: {e}")
177
+
178
+ if not success:
179
+ package_name = package_group[0] if isinstance(package_group, list) else package_group
180
+ logger.warning(f"Failed to download any variant of {package_name}")
181
+
182
+ # Test if sentence tokenization works
183
+ try:
184
+ test_sentences = sent_tokenize("Bu bir test cümlesidir. Bu ikinci cümledir.", language='turkish')
185
+ if len(test_sentences) >= 2:
186
+ logger.info("NLTK sentence tokenization is working correctly.")
187
+ else:
188
+ logger.warning("NLTK sentence tokenization may not be working optimally.")
189
+ except Exception as e:
190
+ logger.warning(f"NLTK sentence tokenization test failed: {e}")
191
+ logger.info("System will fall back to regex-based sentence splitting.")
192
+
193
+
194
+ def turkish_lower(self, text: str) -> str:
195
+ """Correctly lowercases Turkish text."""
196
+ return text.replace('I', 'ı').replace('İ', 'i').lower()
197
+
198
+ def clean_text(self, text: str) -> str:
199
+ """Clean and normalize text."""
200
+ text = text.strip()
201
+ text = text.replace('fi', 'fi').replace('fl', 'fl')
202
+ text = re.sub(r'\s+', ' ', text)
203
+ text = re.sub(r'[^\w\sğüşıöçĞÜŞİÖÇ.,!?-]', '', text)
204
+ return text
205
+
206
+ def preprocess_for_embedding(self, text: str) -> str:
207
+ """Prepares text for embedding."""
208
+ text = self.clean_text(text)
209
+ text = self.turkish_lower(text)
210
+ return text
211
+
212
+ def chunk_text(self, text: str, chunk_size: int, overlap_sentences: int) -> List[str]:
213
+ """Split text into overlapping chunks based on sentences."""
214
+ try:
215
+ sentences = sent_tokenize(text, language='turkish')
216
+ except Exception as e:
217
+ logger.warning(f"NLTK sentence tokenization failed ({e}), falling back to basic splitting.")
218
+ sentences = re.split(r'[.!?]+', text)
219
+ sentences = [s.strip() for s in sentences if s.strip()]
220
+
221
+ if not sentences: return []
222
+
223
+ chunks, current_chunk_words = [], []
224
+ for i, sentence in enumerate(sentences):
225
+ sentence_words = sentence.split()
226
+ if len(current_chunk_words) + len(sentence_words) > chunk_size and current_chunk_words:
227
+ chunks.append(" ".join(current_chunk_words))
228
+ overlap_start_index = max(0, i - overlap_sentences)
229
+ overlapped_sentences = sentences[overlap_start_index:i]
230
+ current_chunk_words = " ".join(overlapped_sentences).split()
231
+ current_chunk_words.extend(sentence_words)
232
+ if current_chunk_words: chunks.append(" ".join(current_chunk_words))
233
+ return chunks
234
+
235
+ class PDFProcessor:
236
+ """Handles PDF document processing."""
237
+ def __init__(self, text_processor: TurkishTextProcessor, config: RAGConfig):
238
+ self.text_processor = text_processor
239
+ self.config = config
240
+
241
+ def extract_text_from_pdf(self, pdf_path: str) -> str:
242
+ """Extract text from a PDF using PyMuPDF with a fallback."""
243
+ text = ""
244
+ try:
245
+ with fitz.open(pdf_path) as doc:
246
+ text = "".join(page.get_text() for page in doc)
247
+ if text.strip(): return self.text_processor.clean_text(text)
248
+ except Exception as e:
249
+ logger.warning(f"PyMuPDF failed for {pdf_path}: {e}. Falling back.")
250
+ try:
251
+ with open(pdf_path, 'rb') as file:
252
+ reader = PyPDF2.PdfReader(file)
253
+ text = "".join(page.extract_text() for page in reader.pages if page.extract_text())
254
+ return self.text_processor.clean_text(text)
255
+ except Exception as e:
256
+ logger.error(f"Failed to extract text from {pdf_path}: {e}")
257
+ return ""
258
+
259
+ def process_directory(self, pdf_directory: str) -> List[Document]:
260
+ """Process all PDFs in a directory."""
261
+ documents = []
262
+ pdf_files = list(Path(pdf_directory).rglob("*.pdf"))
263
+ logger.info(f"Found {len(pdf_files)} PDF files in '{pdf_directory}'.")
264
+ for pdf_path in pdf_files:
265
+ text = self.extract_text_from_pdf(str(pdf_path))
266
+ if not text: continue
267
+ chunks = self.text_processor.chunk_text(text, self.config.chunk_size, self.config.chunk_overlap_sentences)
268
+ for i, chunk in enumerate(chunks):
269
+ if len(chunk.strip()) > 50:
270
+ documents.append(Document(
271
+ content=chunk, source=str(pdf_path), doc_type='pdf',
272
+ chunk_id=f"pdf_{pdf_path.stem}_{i}", metadata={'file_name': pdf_path.name}
273
+ ))
274
+ return documents
275
+
276
+ class JSONProcessor:
277
+ """Handles JSON/JSONL data processing."""
278
+ def __init__(self, text_processor: TurkishTextProcessor, config: RAGConfig):
279
+ self.text_processor = text_processor
280
+ self.config = config
281
+
282
+ def process_directory(self, json_directory: str) -> List[Document]:
283
+ """Process all JSON/JSONL files in a directory."""
284
+ all_docs = []
285
+ json_files = list(Path(json_directory).rglob("*.json")) + list(Path(json_directory).rglob("*.jsonl"))
286
+ logger.info(f"Found {len(json_files)} JSON files in '{json_directory}'.")
287
+ for json_path in json_files:
288
+ try:
289
+ with open(json_path, 'r', encoding='utf-8') as f:
290
+ data = [json.loads(line) for line in f] if str(json_path).endswith('.jsonl') else json.load(f)
291
+ if not isinstance(data, list): data = [data]
292
+ for i, item in enumerate(data):
293
+ content = f"Soru: {item.get('soru', '')}\nCevap: {item.get('cevap', '')}" if 'soru' in item else item.get('text', '') or item.get('content', '') or ' '.join(str(v) for v in item.values() if isinstance(v, str))
294
+ if content and len(content.strip()) > 20:
295
+ all_docs.append(Document(
296
+ content=self.text_processor.clean_text(content), source=str(json_path),
297
+ doc_type='json', chunk_id=f"json_{Path(json_path).stem}_{i}",
298
+ metadata={'original_index': i}
299
+ ))
300
+ except Exception as e:
301
+ logger.error(f"Failed to process JSON file {json_path}: {e}")
302
+ return all_docs
303
+
304
+ class VectorStore:
305
+ """Manages document embeddings and FAISS-based similarity search."""
306
+ def __init__(self, config: RAGConfig, text_processor: TurkishTextProcessor):
307
+ self.config = config
308
+ self.text_processor = text_processor
309
+ self.model = SentenceTransformer(config.embedding_model_name)
310
+ self.documents: List[Document] = []
311
+ self.index: Optional[faiss.Index] = None
312
+
313
+ def build(self, documents: List[Document]):
314
+ """Build the vector store from documents."""
315
+ if not documents:
316
+ logger.warning("No documents provided to build vector store.")
317
+ return
318
+ self.documents = documents
319
+ logger.info(f"Encoding {len(self.documents)} documents...")
320
+ texts = [self.text_processor.preprocess_for_embedding(doc.content) for doc in self.documents]
321
+ embeddings = self.model.encode(texts, show_progress_bar=True, normalize_embeddings=True)
322
+ self.index = faiss.IndexFlatIP(embeddings.shape[1])
323
+ self.index.add(embeddings.astype('float32'))
324
+ logger.info(f"Built FAISS index with {self.index.ntotal} vectors.")
325
+
326
+ def search(self, query: str) -> List[Tuple[Document, float]]:
327
+ """Search for similar documents."""
328
+ if not self.index or not self.documents: return []
329
+ processed_query = self.text_processor.preprocess_for_embedding(query)
330
+ query_embedding = self.model.encode([processed_query], normalize_embeddings=True)
331
+ scores, indices = self.index.search(query_embedding.astype('float32'), self.config.retrieval_k)
332
+ results = [(self.documents[idx], float(score)) for score, idx in zip(scores[0], indices[0]) if idx != -1 and score >= self.config.retrieval_score_threshold]
333
+ return results
334
+
335
+ def save(self):
336
+ """Save the vector store to disk."""
337
+ path = Path(self.config.vector_store_path)
338
+ path.mkdir(parents=True, exist_ok=True)
339
+ if self.index: faiss.write_index(self.index, str(path / 'faiss_index.bin'))
340
+ with open(path / 'documents.pkl', 'wb') as f: pickle.dump(self.documents, f)
341
+ logger.info(f"Vector store saved to {path}")
342
+
343
+ def load(self) -> bool:
344
+ """Load the vector store from disk."""
345
+ path = Path(self.config.vector_store_path)
346
+ if not (path / 'faiss_index.bin').exists() or not (path / 'documents.pkl').exists():
347
+ return False
348
+ self.index = faiss.read_index(str(path / 'faiss_index.bin'))
349
+ with open(path / 'documents.pkl', 'rb') as f: self.documents = pickle.load(f)
350
+ logger.info(f"Loaded vector store with {len(self.documents)} documents from {path}")
351
+ return True
352
+
353
+ # --- Main Application Class ---
354
+
355
+ class FitnessRAG:
356
+ """Orchestrates the entire RAG and generation process."""
357
+ def __init__(self, config: RAGConfig):
358
+ self.config = config
359
+ self.text_processor = TurkishTextProcessor()
360
+ self.pdf_processor = PDFProcessor(self.text_processor, self.config)
361
+ self.json_processor = JSONProcessor(self.text_processor, self.config)
362
+ self.vector_store = VectorStore(self.config, self.text_processor)
363
+
364
+ self.model, self.tokenizer = self._load_generator_model()
365
+
366
+ if not self.vector_store.load():
367
+ logger.info("No existing knowledge base found. Please build it.")
368
+
369
+ def _load_generator_model(self):
370
+ """Loads the causal language model and tokenizer optimized for CPU."""
371
+ logger.info(f"Loading base model for CPU: {self.config.generator_model_name}")
372
+
373
+ # Force CPU usage and use float32 for better CPU compatibility
374
+ device = torch.device("cpu")
375
+
376
+ # Load the base model with CPU-optimized settings
377
+ model = AutoModelForCausalLM.from_pretrained(
378
+ self.config.generator_model_name,
379
+ torch_dtype=torch.float32, # Use float32 for CPU
380
+ device_map="cpu", # Force CPU usage
381
+ trust_remote_code=True,
382
+ low_cpu_mem_usage=True, # Enable memory optimization for CPU
383
+ )
384
+
385
+ tokenizer = AutoTokenizer.from_pretrained(self.config.generator_model_name)
386
+
387
+ # Set padding token if not present
388
+ if tokenizer.pad_token is None:
389
+ tokenizer.pad_token = tokenizer.eos_token
390
+
391
+ # Check for the PEFT adapter path and load the adapter
392
+ if self.config.peft_model_path and Path(self.config.peft_model_path).exists():
393
+ logger.info(f"Loading PEFT adapter from: {self.config.peft_model_path}")
394
+ try:
395
+ # Load the LoRA adapter onto the base model
396
+ model = PeftModel.from_pretrained(
397
+ model,
398
+ self.config.peft_model_path,
399
+ is_trainable=False # Important for inference
400
+ )
401
+
402
+ # Merge adapter for faster inference on CPU
403
+ logger.info("Merging adapter weights into the base model for CPU optimization...")
404
+ model = model.merge_and_unload()
405
+ except Exception as e:
406
+ logger.warning(f"Failed to load PEFT adapter: {e}. Using base model.")
407
+ else:
408
+ logger.warning("PEFT adapter path not found. Using the base model without fine-tuning.")
409
+
410
+ # Ensure model is on CPU and in eval mode
411
+ model = model.to(device)
412
+ model.eval()
413
+
414
+ # Optional: Enable CPU optimizations
415
+ try:
416
+ model = torch.jit.script(model) # JIT compilation for CPU speedup
417
+ logger.info("Model JIT compiled for CPU optimization.")
418
+ except Exception as e:
419
+ logger.info(f"JIT compilation not available or failed: {e}")
420
+
421
+ return model, tokenizer
422
+
423
+ def build_knowledge_base(self, pdf_dir: str = None, json_dir: str = None):
424
+ """Builds the knowledge base from source files."""
425
+ all_docs = []
426
+ if pdf_dir and Path(pdf_dir).exists():
427
+ all_docs.extend(self.pdf_processor.process_directory(pdf_dir))
428
+ if json_dir and Path(json_dir).exists():
429
+ all_docs.extend(self.json_processor.process_directory(json_dir))
430
+
431
+ if not all_docs:
432
+ logger.warning("No new documents found. Knowledge base not built.")
433
+ return
434
+
435
+ self.vector_store.build(all_docs)
436
+ self.vector_store.save()
437
+
438
+ def retrieve_context(self, query: str) -> str:
439
+ """Retrieve and format context for a given query."""
440
+ results = self.vector_store.search(query)
441
+ if not results: return ""
442
+
443
+ context_parts = []
444
+ current_len = 0
445
+ for doc, score in results:
446
+ content = f"[Kaynak: {Path(doc.source).name}, Skor: {score:.2f}] {doc.content}"
447
+ if current_len + len(content) > self.config.max_context_length: break
448
+ context_parts.append(content)
449
+ current_len += len(content)
450
+
451
+ return "\n\n---\n\n".join(context_parts)
452
+
453
+ def ask(self, user_query: str, system_prompt: str = DEFAULT_SYSTEM_PROMPT) -> str:
454
+ """Main method to ask a question and get a generated answer."""
455
+ start_time = time.time()
456
+ context = self.retrieve_context(user_query)
457
+ retrieval_time = time.time() - start_time
458
+ logger.info(f"Context retrieval took {retrieval_time:.2f}s.")
459
+
460
+ if context:
461
+ prompt = f"{system_prompt}\n\n### BAĞLAMSAL BİLGİ KAYNAKLARI\n{context}\n\n### KULLANICI SORUSU\n\"{user_query}\"\n\n### CEVAP"
462
+ else:
463
+ prompt = f"{system_prompt}\n\n### KULLANICI SORUSU\n\"{user_query}\"\n\n### CEVAP"
464
+
465
+ inputs = self.tokenizer(prompt, return_tensors="pt", padding=True, truncation=True, max_length=2048)
466
+
467
+ with torch.no_grad():
468
+ outputs = self.model.generate(
469
+ **inputs,
470
+ max_new_tokens=512,
471
+ do_sample=True,
472
+ temperature=0.7,
473
+ top_k=50,
474
+ top_p=0.95,
475
+ pad_token_id=self.tokenizer.eos_token_id,
476
+ num_return_sequences=1,
477
+ )
478
+
479
+ response = self.tokenizer.decode(outputs[0][inputs['input_ids'].shape[1]:], skip_special_tokens=True)
480
+ return response.strip()
481
+
482
+ def interactive_chat(self):
483
+ """Starts an interactive chat session."""
484
+ print("\n" + "="*60)
485
+ print("🏋️ FitTürkAI RAG Sistemi - İnteraktif Sohbet Modu (CPU)")
486
+ print("="*60)
487
+ if not self.vector_store.documents:
488
+ print("❌ Bilgi tabanı boş. Lütfen önce `build_knowledge_base` çalıştırın.")
489
+ return
490
+
491
+ print("💡 Sorularınızı yazın (çıkmak için 'quit' veya 'q' yazın)")
492
+ print("-" * 60)
493
+
494
+ while True:
495
+ try:
496
+ user_query = input("\n🤔 Sorunuz: ").strip()
497
+ if user_query.lower() in ['quit', 'exit', 'çık', 'q']:
498
+ print("👋 Görüşmek üzere!")
499
+ break
500
+ if not user_query: continue
501
+
502
+ print("\n⏳ Düşünüyorum ve kaynakları tarıyorum...")
503
+ start_time = time.time()
504
+
505
+ final_answer = self.ask(user_query)
506
+
507
+ total_time = time.time() - start_time
508
+
509
+ print("\n" + "-"*15 + f" FitTürkAI'nin Cevabı ({total_time:.2f}s) " + "-"*15)
510
+ print(final_answer)
511
+ print("-" * 60)
512
+
513
+ except KeyboardInterrupt:
514
+ print("\n\n👋 Program sonlandırıldı!")
515
+ break
516
+ except Exception as e:
517
+ print(f"❌ Bir hata oluştu: {e}")
518
+ logger.error(f"Error in interactive chat: {e}", exc_info=True)
519
+
520
+ # --- Main Execution ---
521
+ def main():
522
+ """Main function to run the RAG system."""
523
+ # ---! IMPORTANT !---
524
+ # Set the correct paths for your data and models here.
525
+ PDF_DATA_DIRECTORY = "./indirilen_pdfler" # Folder with your PDF files
526
+ JSON_DATA_DIRECTORY = "./DATA" # Folder with your JSON/JSONL files
527
+ # Set this to the path of your fine-tuned LoRA if you have one.
528
+ # Otherwise, set it to None to use the base model.
529
+ PEFT_ADAPTER_PATH = "./fine_tuned_FitTurkAI_QLoRA"
530
+
531
+ config = RAGConfig(peft_model_path=PEFT_ADAPTER_PATH)
532
+
533
+ # Initialize the entire system (including loading the LLM)
534
+ print("🚀 FitTürkAI RAG Sistemi Başlatılıyor... (CPU Mode)")
535
+ rag_system = FitnessRAG(config)
536
+
537
+ # Check if the knowledge base needs to be built
538
+ vector_store_path = Path(config.vector_store_path)
539
+ if not vector_store_path.exists():
540
+ print(f"\n🔨 Bilgi tabanı '{vector_store_path}' bulunamadı, yeniden oluşturuluyor...")
541
+ rag_system.build_knowledge_base(
542
+ pdf_dir=PDF_DATA_DIRECTORY,
543
+ json_dir=JSON_DATA_DIRECTORY
544
+ )
545
+ else:
546
+ print(f"\n✅ Mevcut bilgi tabanı '{vector_store_path}' yüklendi.")
547
+ rebuild = input("Bilgi tabanını yeniden oluşturmak ister misiniz? (y/N): ").strip().lower()
548
+ if rebuild == 'y':
549
+ import shutil
550
+ shutil.rmtree(vector_store_path)
551
+ print("🔄 Bilgi tabanı yeniden oluşturuluyor...")
552
+ rag_system.build_knowledge_base(
553
+ pdf_dir=PDF_DATA_DIRECTORY,
554
+ json_dir=JSON_DATA_DIRECTORY
555
+ )
556
+
557
+ # Start interactive mode
558
+ rag_system.interactive_chat()
559
+
560
+ if __name__ == "__main__":
561
+ main()
vm_setup_guide.md ADDED
@@ -0,0 +1,326 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚀 FitTürkAI VM Kurulum Rehberi - SSH Bağlantısı Sonrası
2
+
3
+ Tebrikler! VM'nize başarıyla bağlandınız. Şimdi FitTürkAI sistemini kuralım.
4
+
5
+ ## 🔍 **Adım 1: Sistem Durumunu Kontrol Et**
6
+
7
+ ```bash
8
+ # Sistem bilgilerini kontrol et
9
+ sysinfo
10
+
11
+ # RAM durumunu kontrol et
12
+ free -h
13
+
14
+ # Disk alanını kontrol et
15
+ df -h
16
+
17
+ # Startup script'in çalışıp çalışmadığını kontrol et
18
+ cat /var/log/fitturkrai-setup.log | tail -20
19
+ ```
20
+
21
+ ## 📦 **Adım 2: Repository'yi Klonla ve Dosyaları Kopyala**
22
+
23
+ ### Seçenek A: GitHub'dan klonla (eğer repository'niz varsa)
24
+ ```bash
25
+ cd /home/ubuntu
26
+ git clone https://github.com/YOUR_USERNAME/FitTurkAI-RAG.git
27
+ cd FitTurkAI-RAG
28
+ ```
29
+
30
+ ### Seçenek B: Dosyaları manuel olarak oluştur
31
+ ```bash
32
+ cd /home/ubuntu/FitTurkAI-RAG
33
+
34
+ # Ana dosyaları oluştur
35
+ nano test.py
36
+ ```
37
+
38
+ **test.py içeriğini kopyalayın** (mevcut CPU optimize edilmiş kodu)
39
+
40
+ ```bash
41
+ # Requirements dosyasını oluştur
42
+ nano requirements.txt
43
+ ```
44
+
45
+ **requirements.txt içeriğini kopyalayın**
46
+
47
+ ```bash
48
+ # Colab setup scriptini oluştur (opsiyonel)
49
+ nano colab_setup_and_run.py
50
+ ```
51
+
52
+ ## 🐍 **Adım 3: Python Environment ve Paketleri Kontrol Et**
53
+
54
+ ```bash
55
+ # Python versiyonunu kontrol et
56
+ python3 --version
57
+
58
+ # Pip'i güncelle
59
+ python3 -m pip install --upgrade pip
60
+
61
+ # PyTorch'un kurulduğunu kontrol et
62
+ python3 -c "import torch; print(f'PyTorch: {torch.__version__}'); print(f'CPU Available: {torch.cuda.is_available() == False}')"
63
+
64
+ # Gerekli paketleri kur (eksik varsa)
65
+ pip3 install -r requirements.txt
66
+ ```
67
+
68
+ ## 📚 **Adım 4: NLTK Verilerini Kontrol Et**
69
+
70
+ ```bash
71
+ # NLTK verilerinin kurulduğunu kontrol et
72
+ python3 -c "
73
+ import nltk
74
+ try:
75
+ from nltk.tokenize import sent_tokenize
76
+ test = sent_tokenize('Bu bir test. Bu ikinci cümle.', language='turkish')
77
+ print(f'✅ NLTK Turkish tokenization working: {len(test)} sentences')
78
+ except:
79
+ print('❌ NLTK needs setup')
80
+ nltk.download('punkt')
81
+ nltk.download('punkt_tab')
82
+ nltk.download('stopwords')
83
+ "
84
+ ```
85
+
86
+ ## 📁 **Adım 5: Veri Klasörlerini Hazırla**
87
+
88
+ ```bash
89
+ # Klasör yapısını kontrol et
90
+ ls -la
91
+
92
+ # Gerekli klasörlerin varlığını kontrol et
93
+ mkdir -p indirilen_pdfler DATA fitness_rag_store_merged fine_tuned_FitTurkAI_QLoRA
94
+
95
+ # Demo verinin oluşturulduğunu kontrol et
96
+ cat DATA/demo_fitness_data.json
97
+ ```
98
+
99
+ ## 🧪 **Adım 6: Performance Test Çalıştır**
100
+
101
+ ```bash
102
+ # Sistem performansını test et
103
+ python3 /home/ubuntu/performance_test.py
104
+ ```
105
+
106
+ Bu test şunları kontrol eder:
107
+ - ✅ RAM yeterliliği (>2GB)
108
+ - ✅ CPU durumu
109
+ - ✅ Sentence Transformer yüklenmesi
110
+
111
+ ## 🎯 **Adım 7: FitTürkAI Sistemini İlk Kez Çalıştır**
112
+
113
+ ```bash
114
+ # Ana dizine git
115
+ cd /home/ubuntu/FitTurkAI-RAG
116
+
117
+ # İlk çalıştırma (modelleri indirecek)
118
+ python3 test.py
119
+ ```
120
+
121
+ **İlk çalıştırmada**:
122
+ - Turkish LLaMA model indirilecek (~15-20 dakika)
123
+ - Sentence transformer model indirilecek (~2-5 dakika)
124
+ - Demo bilgi tabanı oluşturulacak
125
+
126
+ ## 🔧 **Adım 8: Sorun Giderme (Gerekirse)**
127
+
128
+ ### Model indirme sorunu varsa:
129
+ ```bash
130
+ # Hugging Face cache temizle
131
+ rm -rf ~/.cache/huggingface/
132
+
133
+ # Manuel model indirme
134
+ python3 -c "
135
+ from transformers import AutoTokenizer, AutoModelForCausalLM
136
+ model_name = 'ytu-ce-cosmos/Turkish-Llama-8b-v0.1'
137
+ print('Downloading tokenizer...')
138
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
139
+ print('Downloading model...')
140
+ model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype='float32')
141
+ print('Models downloaded successfully!')
142
+ "
143
+ ```
144
+
145
+ ### RAM sorunu varsa:
146
+ ```bash
147
+ # Swap'i kontrol et
148
+ free -h
149
+
150
+ # RAM kullanımını izle
151
+ watch -n 2 free -h
152
+ ```
153
+
154
+ ### Konfigürasyonu değiştir (test.py'de):
155
+ ```python
156
+ # Düşük RAM için
157
+ config = RAGConfig(
158
+ chunk_size=200,
159
+ retrieval_k=3,
160
+ max_context_length=2000
161
+ )
162
+
163
+ # Yüksek RAM için (64GB+)
164
+ config = RAGConfig(
165
+ chunk_size=500,
166
+ retrieval_k=10,
167
+ max_context_length=8000
168
+ )
169
+ ```
170
+
171
+ ## 📊 **Adım 9: Sistem İzleme ve Optimizasyon**
172
+
173
+ ```bash
174
+ # RAM kullanımını izle
175
+ rammon
176
+
177
+ # CPU kullanımını izle
178
+ htop
179
+
180
+ # GPU kullanımının olmadığını kontrol et (CPU mode)
181
+ python3 -c "import torch; print(f'CUDA Available: {torch.cuda.is_available()}')"
182
+ ```
183
+
184
+ ## 🎮 **Adım 10: İnteraktif Kullanım**
185
+
186
+ Sistem çalıştığında:
187
+
188
+ ```bash
189
+ # İnteraktif chat başlat
190
+ python3 test.py
191
+ ```
192
+
193
+ **Örnek sorular**:
194
+ ```
195
+ 🤔 Sorunuz: Sağlıklı kahvaltı için ne önerirsiniz?
196
+ 🤔 Sorunuz: Günde kaç bardak su içmeliyim?
197
+ 🤔 Sorunuz: Egzersiz sonrası ne yemeli?
198
+ ```
199
+
200
+ ## 📥 **Adım 11: Kendi Verilerinizi Ekleyin**
201
+
202
+ ### PDF dosyaları için:
203
+ ```bash
204
+ # PDF'lerinizi yükleyin (scp veya başka yöntemle)
205
+ # Örnek:
206
+ # scp your_fitness_pdfs/*.pdf username@VM_IP:/home/ubuntu/FitTurkAI-RAG/indirilen_pdfler/
207
+
208
+ # Veya wget ile indirin
209
+ cd indirilen_pdfler
210
+ wget https://example.com/your_fitness_pdf.pdf
211
+ ```
212
+
213
+ ### JSON verileri için:
214
+ ```bash
215
+ # JSON verilerinizi DATA klasörüne koyun
216
+ cd DATA
217
+ nano your_fitness_data.json
218
+
219
+ # Örnek format:
220
+ # [
221
+ # {
222
+ # "soru": "Protein kaynakları nelerdir?",
223
+ # "cevap": "Protein kaynakları arasında et, balık, yumurta, baklagiller, kuruyemişler bulunur..."
224
+ # }
225
+ # ]
226
+ ```
227
+
228
+ ### Bilgi tabanını yeniden oluştur:
229
+ ```bash
230
+ # Yeni verilerle bilgi tabanını güncelle
231
+ python3 -c "
232
+ from test import FitnessRAG, RAGConfig
233
+ config = RAGConfig()
234
+ rag = FitnessRAG(config)
235
+ rag.build_knowledge_base(pdf_dir='./indirilen_pdfler', json_dir='./DATA')
236
+ print('Knowledge base updated!')
237
+ "
238
+ ```
239
+
240
+ ## 🔥 **Adım 12: Gelişmiş Kullanım**
241
+
242
+ ### Script olarak çalıştır:
243
+ ```bash
244
+ # Otomatik sorular
245
+ python3 -c "
246
+ from test import FitnessRAG, RAGConfig
247
+ config = RAGConfig()
248
+ rag = FitnessRAG(config)
249
+
250
+ questions = [
251
+ 'Sağlıklı kahvaltı önerileri',
252
+ 'Egzersiz programı nasıl olmalı',
253
+ 'Su tüketimi ne kadar olmalı'
254
+ ]
255
+
256
+ for q in questions:
257
+ print(f'Soru: {q}')
258
+ answer = rag.ask(q)
259
+ print(f'Cevap: {answer}\n')
260
+ "
261
+ ```
262
+
263
+ ### API olarak kullan:
264
+ ```bash
265
+ # Basit Flask API
266
+ nano fitness_api.py
267
+ ```
268
+
269
+ ```python
270
+ from flask import Flask, request, jsonify
271
+ from test import FitnessRAG, RAGConfig
272
+
273
+ app = Flask(__name__)
274
+ config = RAGConfig()
275
+ rag = FitnessRAG(config)
276
+
277
+ @app.route('/ask', methods=['POST'])
278
+ def ask_question():
279
+ data = request.json
280
+ question = data.get('question', '')
281
+ answer = rag.ask(question)
282
+ return jsonify({'answer': answer})
283
+
284
+ if __name__ == '__main__':
285
+ app.run(host='0.0.0.0', port=8080)
286
+ ```
287
+
288
+ ```bash
289
+ # API'yi çalıştır
290
+ pip3 install flask
291
+ python3 fitness_api.py
292
+ ```
293
+
294
+ ## 🎯 **Başarı Kontrol Listesi**
295
+
296
+ - [ ] ✅ SSH bağlantısı kuruldu
297
+ - [ ] ✅ Sistem durumu kontrol edildi
298
+ - [ ] ✅ Python paketleri kuruldu
299
+ - [ ] ✅ NLTK verileri hazır
300
+ - [ ] ✅ Performance test geçti
301
+ - [ ] ✅ İlk model indirmesi tamamlandı
302
+ - [ ] ✅ Demo sorular çalışıyor
303
+ - [ ] ✅ Kendi veriler eklendi (opsiyonel)
304
+ - [ ] ✅ Sistem izleme kuruldu
305
+
306
+ ## 🆘 **Acil Durum Komutları**
307
+
308
+ ```bash
309
+ # Sistem restart (gerekirse)
310
+ sudo reboot
311
+
312
+ # Python process'leri öldür
313
+ pkill -f python3
314
+
315
+ # Disk alanı temizle
316
+ sudo apt autoremove
317
+ docker system prune -a # Eğer Docker varsa
318
+
319
+ # Log'ları kontrol et
320
+ tail -f /var/log/syslog
321
+ tail -f /var/log/fitturkrai-setup.log
322
+ ```
323
+
324
+ ---
325
+
326
+ **🎉 Kurulum tamamlandığında FitTürkAI sisteminiz maksimum RAM ile CPU'da çalışıyor olacak!**