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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/usr/bin/env python3
|
2 |
+
"""
|
3 |
+
app.py – Quranic Data Training Pipeline Endpoint for ZeroGPU Spaces
|
4 |
+
--------------------------------------------------------------------
|
5 |
+
This script integrates a full Quranic data processing and training pipeline
|
6 |
+
into a Gradio interface endpoint. It is optimized for CPU-based training on
|
7 |
+
Hugging Face ZeroGPU (using the Gradio SDK) and uses chunked incremental
|
8 |
+
training, memory management, and gradient checkpointing to efficiently update
|
9 |
+
Google’s Gemma-2B model with Quranic data.
|
10 |
+
|
11 |
+
Requirements:
|
12 |
+
- Hugging Face Transformers, Gradio, PyTorch, psutil
|
13 |
+
- Hugging Face PRO account with ZeroGPU enabled (make sure to add your HF token
|
14 |
+
as a secret named HF_TOKEN in your Space settings)
|
15 |
+
- Ubuntu CPU/Linux with access to ZeroGPU hardware via Spaces
|
16 |
+
- Input data files (quranic-corpus-morphology-0.4.txt, en.sample.quran-maududi.txt,
|
17 |
+
en.w4w.qurandev.txt) placed in the project root.
|
18 |
+
- Sufficient storage in "working_directory"
|
19 |
+
|
20 |
+
Author: [M-Saddam Hussain]
|
21 |
+
Date: February 2025
|
22 |
+
Data References: [Tanzil.net, IslamSource, QuranicCorpus]
|
23 |
+
"""
|
24 |
+
|
25 |
+
import json
|
26 |
+
import logging
|
27 |
+
import os
|
28 |
+
import sys
|
29 |
+
import traceback
|
30 |
+
import gc
|
31 |
+
import time
|
32 |
+
import psutil
|
33 |
+
import math
|
34 |
+
from datetime import datetime
|
35 |
+
from typing import Dict, List, Optional
|
36 |
+
from dataclasses import dataclass, asdict
|
37 |
+
|
38 |
+
import torch
|
39 |
+
# Limit PyTorch threads for CPU stability.
|
40 |
+
torch.set_num_threads(8)
|
41 |
+
|
42 |
+
from torch.utils.data import Dataset
|
43 |
+
from transformers import (
|
44 |
+
AutoTokenizer,
|
45 |
+
AutoModelForCausalLM,
|
46 |
+
TrainingArguments,
|
47 |
+
Trainer,
|
48 |
+
DataCollatorForLanguageModeling
|
49 |
+
)
|
50 |
+
from threading import Lock
|
51 |
+
|
52 |
+
# Import Gradio and spaces module for ZeroGPU.
|
53 |
+
import gradio as gr
|
54 |
+
import spaces
|
55 |
+
|
56 |
+
# Configure logging
|
57 |
+
logging.basicConfig(
|
58 |
+
level=logging.INFO,
|
59 |
+
format='%(asctime)s - %(levelname)s - %(message)s',
|
60 |
+
handlers=[
|
61 |
+
logging.FileHandler('pipeline.log'),
|
62 |
+
logging.StreamHandler()
|
63 |
+
]
|
64 |
+
)
|
65 |
+
logger = logging.getLogger(__name__)
|
66 |
+
|
67 |
+
def manage_memory(threshold_percent: int = 90, min_available_mb: int = 500, sleep_duration: int = 10):
|
68 |
+
"""
|
69 |
+
Check memory usage; if usage is high or available memory is low,
|
70 |
+
force garbage collection and sleep briefly.
|
71 |
+
"""
|
72 |
+
vm = psutil.virtual_memory()
|
73 |
+
used_percent = vm.percent
|
74 |
+
available_mb = vm.available / (1024 * 1024)
|
75 |
+
logger.info(f"Memory usage: {used_percent}% used, {available_mb:.2f} MB available")
|
76 |
+
if used_percent > threshold_percent or available_mb < min_available_mb:
|
77 |
+
logger.warning("High memory usage detected, forcing garbage collection and sleeping...")
|
78 |
+
gc.collect()
|
79 |
+
time.sleep(sleep_duration)
|
80 |
+
|
81 |
+
@dataclass
|
82 |
+
class WordAnalysis:
|
83 |
+
"""Structured representation of word-level analysis"""
|
84 |
+
arabic: str
|
85 |
+
translation: str
|
86 |
+
position: str
|
87 |
+
morphology: Dict
|
88 |
+
features: List[str]
|
89 |
+
root: str
|
90 |
+
location: str
|
91 |
+
metadata: Dict
|
92 |
+
|
93 |
+
@dataclass
|
94 |
+
class VerseData:
|
95 |
+
"""Structured representation of verse-level data"""
|
96 |
+
chapter: int
|
97 |
+
verse: int
|
98 |
+
arabic_text: str
|
99 |
+
translation: str
|
100 |
+
words: List[WordAnalysis]
|
101 |
+
metadata: Dict
|
102 |
+
|
103 |
+
class QuranicDataset(Dataset):
|
104 |
+
"""Custom dataset for Quranic text training."""
|
105 |
+
def __init__(self, processed_data: List[Dict], tokenizer):
|
106 |
+
self.examples = []
|
107 |
+
self.tokenizer = tokenizer
|
108 |
+
for verse_data in processed_data:
|
109 |
+
self.examples.extend(self._create_training_examples(verse_data))
|
110 |
+
|
111 |
+
def _create_training_examples(self, verse_data: Dict) -> List[Dict]:
|
112 |
+
examples = []
|
113 |
+
text_block = (
|
114 |
+
f"[VERSE {verse_data['chapter']}:{verse_data['verse']}]\n"
|
115 |
+
f"Arabic: {verse_data['arabic_text']}\n"
|
116 |
+
f"Translation: {verse_data['translation']}\n"
|
117 |
+
"Morphological Analysis:\n"
|
118 |
+
)
|
119 |
+
for word in verse_data['words']:
|
120 |
+
text_block += (
|
121 |
+
f"[WORD] {word['arabic']}\n"
|
122 |
+
f"Root: {word['root']}\n"
|
123 |
+
f"Features: {', '.join(word['features'])}\n"
|
124 |
+
)
|
125 |
+
examples.append(self._format_example(text_block))
|
126 |
+
return examples
|
127 |
+
|
128 |
+
def _format_example(self, text: str) -> Dict:
|
129 |
+
encodings = self.tokenizer(
|
130 |
+
text,
|
131 |
+
truncation=True,
|
132 |
+
max_length=64, # Reduced length to lower memory usage.
|
133 |
+
padding="max_length",
|
134 |
+
return_tensors="pt"
|
135 |
+
)
|
136 |
+
return {
|
137 |
+
"input_ids": encodings["input_ids"][0],
|
138 |
+
"attention_mask": encodings["attention_mask"][0]
|
139 |
+
}
|
140 |
+
|
141 |
+
def __len__(self):
|
142 |
+
return len(self.examples)
|
143 |
+
|
144 |
+
def __getitem__(self, idx):
|
145 |
+
return self.examples[idx]
|
146 |
+
|
147 |
+
class QuranicDataProcessor:
|
148 |
+
"""Processes Quranic data into structured training examples."""
|
149 |
+
def __init__(self, source_dir: str, output_dir: str):
|
150 |
+
# Here, source_dir is set to project root.
|
151 |
+
self.source_dir = source_dir
|
152 |
+
self.output_dir = output_dir
|
153 |
+
self.morphological_data: Dict[str, Dict] = {}
|
154 |
+
self.word_by_word_data: Dict[str, List[str]] = {}
|
155 |
+
self.translation_data: Dict[str, str] = {}
|
156 |
+
self.processed_verses = set()
|
157 |
+
self.processing_lock = Lock()
|
158 |
+
os.makedirs(output_dir, exist_ok=True)
|
159 |
+
os.makedirs(os.path.join(output_dir, 'json'), exist_ok=True)
|
160 |
+
os.makedirs(os.path.join(output_dir, 'txt'), exist_ok=True)
|
161 |
+
os.makedirs(os.path.join(output_dir, 'checkpoints'), exist_ok=True)
|
162 |
+
logger.info(f"Initialized processor with source dir: {source_dir}")
|
163 |
+
|
164 |
+
def load_source_files(self) -> bool:
|
165 |
+
"""Loads morphological, translation, and word-by-word data from project root."""
|
166 |
+
try:
|
167 |
+
logger.info("Loading morphological data...")
|
168 |
+
morph_path = os.path.join(self.source_dir, 'quranic-corpus-morphology-0.4.txt')
|
169 |
+
with open(morph_path, 'r', encoding='utf-8') as f:
|
170 |
+
next(f)
|
171 |
+
for line in f:
|
172 |
+
if line.strip() and not line.startswith('#'):
|
173 |
+
parts = line.strip().split('\t')
|
174 |
+
if len(parts) >= 4:
|
175 |
+
location = parts[0].strip('()')
|
176 |
+
self.morphological_data[location] = {
|
177 |
+
'form': parts[1],
|
178 |
+
'tag': parts[2],
|
179 |
+
'features': parts[3]
|
180 |
+
}
|
181 |
+
logger.info(f"Loaded {len(self.morphological_data)} morphological entries")
|
182 |
+
logger.info("Loading translation data...")
|
183 |
+
trans_path = os.path.join(self.source_dir, 'en.sample.quran-maududi.txt')
|
184 |
+
with open(trans_path, 'r', encoding='utf-8') as f:
|
185 |
+
next(f)
|
186 |
+
for line in f:
|
187 |
+
if line.strip():
|
188 |
+
parts = line.strip().split('|')
|
189 |
+
if len(parts) >= 3:
|
190 |
+
key = f"{parts[0]}:{parts[1]}"
|
191 |
+
self.translation_data[key] = parts[2].strip()
|
192 |
+
logger.info(f"Loaded {len(self.translation_data)} verse translations")
|
193 |
+
logger.info("Loading word-by-word data...")
|
194 |
+
word_path = os.path.join(self.source_dir, 'en.w4w.qurandev.txt')
|
195 |
+
with open(word_path, 'r', encoding='utf-8-sig') as f:
|
196 |
+
lines = [line.strip() for line in f if line.strip()]
|
197 |
+
sorted_keys = sorted(self.translation_data.keys(), key=lambda x: (int(x.split(':')[0]), int(x.split(':')[1])))
|
198 |
+
if len(lines) != len(sorted_keys):
|
199 |
+
logger.warning("Mismatch between word-by-word file and translation data")
|
200 |
+
for i, verse_key in enumerate(sorted_keys):
|
201 |
+
if i < len(lines):
|
202 |
+
words = [w.strip() for w in lines[i].split('|') if w.strip()]
|
203 |
+
self.word_by_word_data[verse_key] = words
|
204 |
+
logger.info(f"Loaded word-by-word data for {len(self.word_by_word_data)} verses")
|
205 |
+
return True
|
206 |
+
except Exception as e:
|
207 |
+
logger.error(f"Error loading source files: {str(e)}")
|
208 |
+
logger.error(traceback.format_exc())
|
209 |
+
return False
|
210 |
+
|
211 |
+
def process_verse(self, chapter: int, verse: int) -> Optional[VerseData]:
|
212 |
+
"""Processes a single verse into structured format."""
|
213 |
+
try:
|
214 |
+
verse_ref = f"{chapter}:{verse}"
|
215 |
+
logger.info(f"Processing verse {verse_ref}")
|
216 |
+
translation = self.translation_data.get(verse_ref)
|
217 |
+
if not translation:
|
218 |
+
logger.warning(f"No translation for verse {verse_ref}")
|
219 |
+
return None
|
220 |
+
verse_word_list = self.word_by_word_data.get(verse_ref, [])
|
221 |
+
if not verse_word_list:
|
222 |
+
logger.warning(f"No word-by-word data for verse {verse_ref}")
|
223 |
+
return None
|
224 |
+
verse_words: List[WordAnalysis] = []
|
225 |
+
arabic_text = ""
|
226 |
+
for pos in range(1, len(verse_word_list) + 1):
|
227 |
+
pattern = f"{chapter}:{verse}:{pos}:"
|
228 |
+
matching_entries = [data for loc, data in self.morphological_data.items() if loc.startswith(pattern)]
|
229 |
+
if not matching_entries:
|
230 |
+
logger.debug(f"No morphological data for {pattern}")
|
231 |
+
continue
|
232 |
+
combined_form = " ".join(entry['form'] for entry in matching_entries)
|
233 |
+
combined_features = []
|
234 |
+
root = ""
|
235 |
+
for entry in matching_entries:
|
236 |
+
features = entry['features'].split('|')
|
237 |
+
combined_features.extend(features)
|
238 |
+
if not root:
|
239 |
+
for f in features:
|
240 |
+
if 'ROOT:' in f:
|
241 |
+
root = f.split('ROOT:')[1]
|
242 |
+
break
|
243 |
+
word_translation = verse_word_list[pos - 1]
|
244 |
+
word = WordAnalysis(
|
245 |
+
arabic=combined_form,
|
246 |
+
translation=word_translation,
|
247 |
+
position=str(pos),
|
248 |
+
morphology=matching_entries[0],
|
249 |
+
features=combined_features,
|
250 |
+
root=root,
|
251 |
+
location=f"{chapter}:{verse}:{pos}",
|
252 |
+
metadata={}
|
253 |
+
)
|
254 |
+
verse_words.append(word)
|
255 |
+
arabic_text += f" {combined_form}"
|
256 |
+
verse_data = VerseData(
|
257 |
+
chapter=chapter,
|
258 |
+
verse=verse,
|
259 |
+
arabic_text=arabic_text.strip(),
|
260 |
+
translation=translation,
|
261 |
+
words=verse_words,
|
262 |
+
metadata={
|
263 |
+
"processed_timestamp": datetime.now().isoformat(),
|
264 |
+
"word_count": len(verse_words)
|
265 |
+
}
|
266 |
+
)
|
267 |
+
self._save_verse_data(verse_data)
|
268 |
+
return verse_data
|
269 |
+
except Exception as e:
|
270 |
+
logger.error(f"Error processing verse {chapter}:{verse}: {str(e)}")
|
271 |
+
logger.error(traceback.format_exc())
|
272 |
+
return None
|
273 |
+
|
274 |
+
def _save_verse_data(self, verse_data: VerseData):
|
275 |
+
"""Saves processed verse data as JSON and TXT."""
|
276 |
+
try:
|
277 |
+
verse_ref = f"{verse_data.chapter}:{verse_data.verse}"
|
278 |
+
json_path = os.path.join(self.output_dir, 'json', f'verse_{verse_ref.replace(":", "_")}.json')
|
279 |
+
with open(json_path, 'w', encoding='utf-8') as f:
|
280 |
+
json.dump(asdict(verse_data), f, ensure_ascii=False, indent=2)
|
281 |
+
txt_path = os.path.join(self.output_dir, 'txt', f'verse_{verse_ref.replace(":", "_")}.txt')
|
282 |
+
with open(txt_path, 'w', encoding='utf-8') as f:
|
283 |
+
f.write(f"=== Verse {verse_ref} ===\n\n")
|
284 |
+
f.write(f"Arabic Text:\n{verse_data.arabic_text}\n\n")
|
285 |
+
f.write(f"Translation:\n{verse_data.translation}\n\n")
|
286 |
+
f.write("Word Analysis:\n")
|
287 |
+
for i, word in enumerate(verse_data.words, 1):
|
288 |
+
f.write(f"\nWord {i}:\n")
|
289 |
+
f.write(f" Arabic: {word.arabic}\n")
|
290 |
+
f.write(f" Translation: {word.translation}\n")
|
291 |
+
f.write(f" Root: {word.root}\n")
|
292 |
+
f.write(" Features:\n")
|
293 |
+
for feature in word.features:
|
294 |
+
f.write(f" - {feature}\n")
|
295 |
+
f.write("\n")
|
296 |
+
logger.info(f"Saved verse data to {json_path} and {txt_path}")
|
297 |
+
except Exception as e:
|
298 |
+
logger.error(f"Error saving verse data: {str(e)}")
|
299 |
+
logger.error(traceback.format_exc())
|
300 |
+
|
301 |
+
class QuranicModelTrainer:
|
302 |
+
"""Trains the Gemma-2B model on Quranic data using chunked incremental updates."""
|
303 |
+
def __init__(self,
|
304 |
+
model_name: str = "google/gemma-2-2b",
|
305 |
+
processed_data_dir: str = "processed_data",
|
306 |
+
checkpoint_dir: str = "checkpoints"):
|
307 |
+
self.processed_data_dir = processed_data_dir
|
308 |
+
self.checkpoint_dir = checkpoint_dir
|
309 |
+
self.device = "cpu" # Training on CPU; ZeroGPU will handle GPU access.
|
310 |
+
logger.info("Loading tokenizer and model...")
|
311 |
+
self.tokenizer = AutoTokenizer.from_pretrained(
|
312 |
+
model_name,
|
313 |
+
use_auth_token=os.environ.get("HF_TOKEN"),
|
314 |
+
additional_special_tokens=["[VERSE]", "[WORD]", "[ROOT]", "[FEATURES]"],
|
315 |
+
trust_remote_code=True
|
316 |
+
)
|
317 |
+
self.tokenizer.add_special_tokens({"pad_token": "[PAD]"})
|
318 |
+
self.model = AutoModelForCausalLM.from_pretrained(
|
319 |
+
model_name,
|
320 |
+
use_auth_token=os.environ.get("HF_TOKEN"),
|
321 |
+
torch_dtype=torch.float32,
|
322 |
+
low_cpu_mem_usage=True,
|
323 |
+
trust_remote_code=True
|
324 |
+
)
|
325 |
+
self.model.resize_token_embeddings(len(self.tokenizer))
|
326 |
+
self.model.train()
|
327 |
+
# Disable caching and enable gradient checkpointing for memory savings.
|
328 |
+
self.model.config.use_cache = False
|
329 |
+
self.model.gradient_checkpointing_enable()
|
330 |
+
|
331 |
+
def prepare_training_data(self, chapter_data: List[Dict]) -> Dataset:
|
332 |
+
"""Creates a QuranicDataset from processed chapter data."""
|
333 |
+
return QuranicDataset(chapter_data, self.tokenizer)
|
334 |
+
|
335 |
+
def train_chapter(self,
|
336 |
+
chapter_num: int,
|
337 |
+
processed_verses: List[Dict],
|
338 |
+
chunk_size: int = 10,
|
339 |
+
num_train_epochs: int = 10,
|
340 |
+
per_device_train_batch_size: int = 1,
|
341 |
+
learning_rate: float = 3e-5,
|
342 |
+
weight_decay: float = 0.01,
|
343 |
+
gradient_accumulation_steps: int = 64) -> bool:
|
344 |
+
"""
|
345 |
+
Splits chapter data into chunks and trains incrementally to reduce memory usage.
|
346 |
+
"""
|
347 |
+
try:
|
348 |
+
total_examples = len(processed_verses)
|
349 |
+
total_chunks = math.ceil(total_examples / chunk_size)
|
350 |
+
logger.info(f"Chapter {chapter_num}: {total_examples} examples, {total_chunks} chunks.")
|
351 |
+
for chunk_index in range(total_chunks):
|
352 |
+
chunk_data = processed_verses[chunk_index * chunk_size: (chunk_index + 1) * chunk_size]
|
353 |
+
dataset = self.prepare_training_data(chunk_data)
|
354 |
+
chunk_output_dir = os.path.join(self.checkpoint_dir, f"chapter_{chapter_num}", f"chunk_{chunk_index}")
|
355 |
+
os.makedirs(chunk_output_dir, exist_ok=True)
|
356 |
+
training_args = TrainingArguments(
|
357 |
+
output_dir=chunk_output_dir,
|
358 |
+
overwrite_output_dir=True,
|
359 |
+
num_train_epochs=num_train_epochs,
|
360 |
+
per_device_train_batch_size=per_device_train_batch_size,
|
361 |
+
learning_rate=learning_rate,
|
362 |
+
weight_decay=weight_decay,
|
363 |
+
gradient_accumulation_steps=gradient_accumulation_steps,
|
364 |
+
fp16=False,
|
365 |
+
remove_unused_columns=False,
|
366 |
+
logging_steps=50,
|
367 |
+
report_to="none",
|
368 |
+
evaluation_strategy="no",
|
369 |
+
no_cuda=True,
|
370 |
+
dataloader_num_workers=0,
|
371 |
+
dataloader_pin_memory=False
|
372 |
+
)
|
373 |
+
data_collator = DataCollatorForLanguageModeling(
|
374 |
+
tokenizer=self.tokenizer,
|
375 |
+
mlm=False
|
376 |
+
)
|
377 |
+
trainer = Trainer(
|
378 |
+
model=self.model,
|
379 |
+
args=training_args,
|
380 |
+
train_dataset=dataset,
|
381 |
+
tokenizer=self.tokenizer,
|
382 |
+
data_collator=data_collator
|
383 |
+
)
|
384 |
+
logger.info(f"Training chunk {chunk_index+1}/{total_chunks} for Chapter {chapter_num}...")
|
385 |
+
trainer.train()
|
386 |
+
trainer.save_model(chunk_output_dir)
|
387 |
+
del trainer, dataset
|
388 |
+
gc.collect()
|
389 |
+
manage_memory()
|
390 |
+
logger.info(f"Completed training for Chapter {chapter_num}")
|
391 |
+
return True
|
392 |
+
except Exception as e:
|
393 |
+
logger.error(f"Error training chapter {chapter_num}: {str(e)}")
|
394 |
+
logger.error(traceback.format_exc())
|
395 |
+
return False
|
396 |
+
|
397 |
+
class QuranicPipeline:
|
398 |
+
"""Integrates data processing and incremental model training for all chapters."""
|
399 |
+
def __init__(self,
|
400 |
+
source_dir: str = ".",
|
401 |
+
working_dir: str = "working_directory",
|
402 |
+
start_chapter: int = 1,
|
403 |
+
end_chapter: int = 114):
|
404 |
+
# Here source_dir is set to the project root.
|
405 |
+
self.source_dir = source_dir
|
406 |
+
self.working_dir = working_dir
|
407 |
+
self.start_chapter = start_chapter
|
408 |
+
self.end_chapter = end_chapter
|
409 |
+
self.setup_directories()
|
410 |
+
global logger
|
411 |
+
logger = logging.getLogger(__name__)
|
412 |
+
self.state = {
|
413 |
+
"last_processed_chapter": 0,
|
414 |
+
"last_trained_chapter": 0,
|
415 |
+
"current_state": "initialized",
|
416 |
+
"errors": [],
|
417 |
+
"start_time": datetime.now().isoformat()
|
418 |
+
}
|
419 |
+
self.load_state()
|
420 |
+
try:
|
421 |
+
logger.info("Initializing Quranic Data Processor...")
|
422 |
+
self.processor = QuranicDataProcessor(
|
423 |
+
source_dir=self.source_dir,
|
424 |
+
output_dir=os.path.join(self.working_dir, "processed_data")
|
425 |
+
)
|
426 |
+
logger.info("Initializing Quranic Model Trainer...")
|
427 |
+
self.trainer = QuranicModelTrainer(
|
428 |
+
model_name="google/gemma-2-2b",
|
429 |
+
processed_data_dir=os.path.join(self.working_dir, "processed_data"),
|
430 |
+
checkpoint_dir=os.path.join(self.working_dir, "checkpoints")
|
431 |
+
)
|
432 |
+
self.state["current_state"] = "ready"
|
433 |
+
self.save_state()
|
434 |
+
except Exception as e:
|
435 |
+
self.handle_error("Initialization failed", e)
|
436 |
+
raise
|
437 |
+
|
438 |
+
def setup_directories(self):
|
439 |
+
dirs = [
|
440 |
+
self.working_dir,
|
441 |
+
os.path.join(self.working_dir, "processed_data"),
|
442 |
+
os.path.join(self.working_dir, "checkpoints"),
|
443 |
+
os.path.join(self.working_dir, "logs"),
|
444 |
+
os.path.join(self.working_dir, "state")
|
445 |
+
]
|
446 |
+
for d in dirs:
|
447 |
+
os.makedirs(d, exist_ok=True)
|
448 |
+
|
449 |
+
def load_state(self):
|
450 |
+
state_file = os.path.join(self.working_dir, "state", "pipeline_state.json")
|
451 |
+
if os.path.exists(state_file):
|
452 |
+
try:
|
453 |
+
with open(state_file, 'r') as f:
|
454 |
+
saved_state = json.load(f)
|
455 |
+
self.state.update(saved_state)
|
456 |
+
logger.info(f"Loaded previous state: Last processed chapter {self.state.get('last_processed_chapter')}, "
|
457 |
+
f"last trained chapter {self.state.get('last_trained_chapter')}")
|
458 |
+
except Exception as e:
|
459 |
+
logger.warning(f"Could not load previous state: {str(e)}")
|
460 |
+
|
461 |
+
def save_state(self):
|
462 |
+
state_file = os.path.join(self.working_dir, "state", "pipeline_state.json")
|
463 |
+
with open(state_file, 'w') as f:
|
464 |
+
json.dump(self.state, f, indent=2)
|
465 |
+
|
466 |
+
def handle_error(self, context: str, error: Exception):
|
467 |
+
error_detail = {
|
468 |
+
"timestamp": datetime.now().isoformat(),
|
469 |
+
"context": context,
|
470 |
+
"error": str(error),
|
471 |
+
"traceback": traceback.format_exc()
|
472 |
+
}
|
473 |
+
self.state.setdefault("errors", []).append(error_detail)
|
474 |
+
logger.error(f"{context}: {str(error)}")
|
475 |
+
self.save_state()
|
476 |
+
|
477 |
+
def run_pipeline(self):
|
478 |
+
"""Runs processing and training for chapters sequentially."""
|
479 |
+
logger.info("Starting pipeline execution")
|
480 |
+
try:
|
481 |
+
if not self.processor.load_source_files():
|
482 |
+
raise Exception("Failed to load source files")
|
483 |
+
for chapter in range(self.start_chapter, self.end_chapter + 1):
|
484 |
+
logger.info(f"=== Processing Chapter {chapter} ===")
|
485 |
+
processed_chapter_data = []
|
486 |
+
verse = 1
|
487 |
+
while True:
|
488 |
+
verse_data = self.processor.process_verse(chapter, verse)
|
489 |
+
if verse_data is None:
|
490 |
+
break
|
491 |
+
processed_chapter_data.append(asdict(verse_data))
|
492 |
+
verse += 1
|
493 |
+
if processed_chapter_data:
|
494 |
+
success = self.trainer.train_chapter(chapter, processed_chapter_data)
|
495 |
+
if not success:
|
496 |
+
logger.error(f"Training failed for Chapter {chapter}. Stopping pipeline.")
|
497 |
+
break
|
498 |
+
self.state["last_trained_chapter"] = chapter
|
499 |
+
self.save_state()
|
500 |
+
else:
|
501 |
+
logger.warning(f"No processed data for Chapter {chapter}")
|
502 |
+
self.state["last_processed_chapter"] = chapter
|
503 |
+
self.save_state()
|
504 |
+
manage_memory()
|
505 |
+
logger.info("Pipeline execution completed")
|
506 |
+
except Exception as e:
|
507 |
+
self.handle_error("Pipeline execution failed", e)
|
508 |
+
raise
|
509 |
+
|
510 |
+
# Define a Gradio endpoint function that triggers the training pipeline.
|
511 |
+
@spaces.GPU() # Request ZeroGPU hardware.
|
512 |
+
def start_pipeline():
|
513 |
+
try:
|
514 |
+
pipeline = QuranicPipeline(
|
515 |
+
source_dir=".", # Now using project root for input files.
|
516 |
+
working_dir="working_directory",
|
517 |
+
start_chapter=1,
|
518 |
+
end_chapter=114
|
519 |
+
)
|
520 |
+
pipeline.run_pipeline()
|
521 |
+
return "Pipeline execution completed successfully."
|
522 |
+
except Exception as e:
|
523 |
+
return f"Pipeline execution failed: {str(e)}"
|
524 |
+
|
525 |
+
# Create a Gradio Interface with no inputs and a text output.
|
526 |
+
iface = gr.Interface(
|
527 |
+
fn=start_pipeline,
|
528 |
+
inputs=[],
|
529 |
+
outputs="text",
|
530 |
+
title="Quranic Training Pipeline",
|
531 |
+
description="Click 'Submit' to trigger the Quranic data processing and training pipeline on ZeroGPU."
|
532 |
+
)
|
533 |
+
|
534 |
+
if __name__ == "__main__":
|
535 |
+
iface.launch()
|