eBlessings commited on
Commit
40e2e3f
·
verified ·
1 Parent(s): 560177a

Update app.py

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