mohammed.aldaraji commited on
Commit
ea3d866
·
1 Parent(s): e6e6075

Initial commit: Adding Iraqi dialect LLM model and code

Browse files
.gitattributes CHANGED
@@ -1,35 +0,0 @@
1
- *.7z filter=lfs diff=lfs merge=lfs -text
2
- *.arrow filter=lfs diff=lfs merge=lfs -text
3
- *.bin filter=lfs diff=lfs merge=lfs -text
4
- *.bz2 filter=lfs diff=lfs merge=lfs -text
5
- *.ckpt filter=lfs diff=lfs merge=lfs -text
6
- *.ftz filter=lfs diff=lfs merge=lfs -text
7
- *.gz filter=lfs diff=lfs merge=lfs -text
8
- *.h5 filter=lfs diff=lfs merge=lfs -text
9
- *.joblib filter=lfs diff=lfs merge=lfs -text
10
- *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
- *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
- *.model filter=lfs diff=lfs merge=lfs -text
13
- *.msgpack filter=lfs diff=lfs merge=lfs -text
14
- *.npy filter=lfs diff=lfs merge=lfs -text
15
- *.npz filter=lfs diff=lfs merge=lfs -text
16
- *.onnx filter=lfs diff=lfs merge=lfs -text
17
- *.ot filter=lfs diff=lfs merge=lfs -text
18
- *.parquet filter=lfs diff=lfs merge=lfs -text
19
- *.pb filter=lfs diff=lfs merge=lfs -text
20
- *.pickle filter=lfs diff=lfs merge=lfs -text
21
- *.pkl filter=lfs diff=lfs merge=lfs -text
22
- *.pt filter=lfs diff=lfs merge=lfs -text
23
- *.pth filter=lfs diff=lfs merge=lfs -text
24
- *.rar filter=lfs diff=lfs merge=lfs -text
25
- *.safetensors filter=lfs diff=lfs merge=lfs -text
26
- saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
- *.tar.* filter=lfs diff=lfs merge=lfs -text
28
- *.tar filter=lfs diff=lfs merge=lfs -text
29
- *.tflite filter=lfs diff=lfs merge=lfs -text
30
- *.tgz filter=lfs diff=lfs merge=lfs -text
31
- *.wasm filter=lfs diff=lfs merge=lfs -text
32
- *.xz filter=lfs diff=lfs merge=lfs -text
33
- *.zip filter=lfs diff=lfs merge=lfs -text
34
- *.zst filter=lfs diff=lfs merge=lfs -text
35
- *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
.gitignore ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Ignore Python cache files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *.pyo
5
+ *.pyd
6
+
7
+ # Ignore Jupyter Notebook checkpoints
8
+ .ipynb_checkpoints
9
+
10
+ # Ignore virtual environments and dependencies
11
+ venv/
12
+ env/
13
+ iraqi_arabic_llm_env/
14
+
15
+ # Ignore system-specific files
16
+ .DS_Store
17
+ Thumbs.db
18
+
19
+ # Ignore model training artifacts
20
+ *.bin
21
+ *.safetensors
22
+ *.h5
23
+ *.ckpt
24
+ *.pt
25
+
26
+ # Ignore dataset files if you don't want to push them
27
+ data/
28
+ datasets/
29
+ logs/
30
+
31
+ # Ignore Hugging Face cache files
32
+ huggingface/
33
+ .cache/
34
+ hf_cache/
35
+
36
+ # Ignore any temporary or debug files
37
+ *.log
38
+ *.tmp
39
+ *.swp
40
+ *.bak
41
+
42
+ # Ignore environment variables or configuration files containing secrets
43
+ .env
44
+ config.json
45
+
46
+ # Ignore Gradio or Streamlit deployment files (if using locally for testing)
47
+ app.db
48
+ __pycache__/
49
+ static/
README.md ADDED
File without changes
app.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # app.py
2
+ import os
3
+ from flask import Flask, request, jsonify
4
+ from transformers import pipeline, AutoModelForCausalLM, AutoTokenizer
5
+
6
+ app = Flask(__name__)
7
+
8
+ # Set up the model path as a raw string to avoid Windows path issues
9
+ model_path = r"C:\Users\moham\iraqi_arabic_llm_project\models\text_generation_model"
10
+
11
+ # Print model_path to confirm correctness
12
+ print("Model path:", model_path)
13
+
14
+ # Check if the model path exists
15
+ if not os.path.exists(model_path):
16
+ raise ValueError(f"Model path does not exist: {model_path}")
17
+
18
+ # Load the model and tokenizer directly
19
+ model = AutoModelForCausalLM.from_pretrained(model_path)
20
+ tokenizer = AutoTokenizer.from_pretrained(model_path)
21
+ text_generator = pipeline("text-generation", model=model, tokenizer=tokenizer)
22
+
23
+ # Endpoint for text generation
24
+ @app.route('/generate_text', methods=['POST'])
25
+ def generate_text():
26
+ input_text = request.json.get("text")
27
+ generated_text = text_generator(input_text, max_length=50, num_return_sequences=1)
28
+ return jsonify(generated_text)
29
+
30
+ # Endpoint for sentiment analysis (if you have a sentiment model saved similarly)
31
+ # Uncomment and set up sentiment analyzer as needed
32
+ # from transformers import AutoModelForSequenceClassification
33
+ # sentiment_model_path = r"C:\Users\moham\iraqi_arabic_llm_project\models\sentiment_analysis_model"
34
+ # sentiment_model = AutoModelForSequenceClassification.from_pretrained(sentiment_model_path)
35
+ # sentiment_analyzer = pipeline("sentiment-analysis", model=sentiment_model, tokenizer=tokenizer)
36
+
37
+ @app.route('/analyze_sentiment', methods=['POST'])
38
+ def analyze_sentiment():
39
+ input_text = request.json.get("text")
40
+ sentiment = sentiment_analyzer(input_text) # Uncomment once you have sentiment model loaded
41
+ return jsonify(sentiment)
42
+
43
+ if __name__ == '__main__':
44
+ app.run(debug=True)
iraqi_data.txt ADDED
The diff for this file is too large to render. See raw diff
 
iraqi_proverbs.pdf ADDED
Binary file (762 kB). View file
 
iraqi_proverbs.txt ADDED
The diff for this file is too large to render. See raw diff
 
models/checkpoint-4341/generation_config.json ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 0,
4
+ "eos_token_id": 0,
5
+ "transformers_version": "4.46.1"
6
+ }
models/checkpoint-4341/rng_state.pth ADDED
Binary file (14 kB). View file
 
models/checkpoint-4341/trainer_state.json ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "best_metric": null,
3
+ "best_model_checkpoint": null,
4
+ "epoch": 3.0,
5
+ "eval_steps": 500,
6
+ "global_step": 4341,
7
+ "is_hyper_param_search": false,
8
+ "is_local_process_zero": true,
9
+ "is_world_process_zero": true,
10
+ "log_history": [
11
+ {
12
+ "epoch": 0.3455425017277125,
13
+ "grad_norm": 2.7930502891540527,
14
+ "learning_rate": 4.424095830453813e-05,
15
+ "loss": 1.8711,
16
+ "step": 500
17
+ },
18
+ {
19
+ "epoch": 0.691085003455425,
20
+ "grad_norm": 3.2233235836029053,
21
+ "learning_rate": 3.848191660907625e-05,
22
+ "loss": 1.2259,
23
+ "step": 1000
24
+ },
25
+ {
26
+ "epoch": 1.0366275051831375,
27
+ "grad_norm": 2.0669665336608887,
28
+ "learning_rate": 3.272287491361438e-05,
29
+ "loss": 1.1263,
30
+ "step": 1500
31
+ },
32
+ {
33
+ "epoch": 1.38217000691085,
34
+ "grad_norm": 1.8985625505447388,
35
+ "learning_rate": 2.69638332181525e-05,
36
+ "loss": 1.0713,
37
+ "step": 2000
38
+ },
39
+ {
40
+ "epoch": 1.7277125086385625,
41
+ "grad_norm": 1.88094961643219,
42
+ "learning_rate": 2.1204791522690624e-05,
43
+ "loss": 1.0282,
44
+ "step": 2500
45
+ },
46
+ {
47
+ "epoch": 2.073255010366275,
48
+ "grad_norm": 2.1321468353271484,
49
+ "learning_rate": 1.5445749827228752e-05,
50
+ "loss": 1.0091,
51
+ "step": 3000
52
+ },
53
+ {
54
+ "epoch": 2.4187975120939877,
55
+ "grad_norm": 2.1656711101531982,
56
+ "learning_rate": 9.686708131766875e-06,
57
+ "loss": 0.9872,
58
+ "step": 3500
59
+ },
60
+ {
61
+ "epoch": 2.7643400138217,
62
+ "grad_norm": 1.986304521560669,
63
+ "learning_rate": 3.927666436304999e-06,
64
+ "loss": 0.9691,
65
+ "step": 4000
66
+ }
67
+ ],
68
+ "logging_steps": 500,
69
+ "max_steps": 4341,
70
+ "num_input_tokens_seen": 0,
71
+ "num_train_epochs": 3,
72
+ "save_steps": 10000,
73
+ "stateful_callbacks": {
74
+ "TrainerControl": {
75
+ "args": {
76
+ "should_epoch_stop": false,
77
+ "should_evaluate": false,
78
+ "should_log": false,
79
+ "should_save": true,
80
+ "should_training_stop": true
81
+ },
82
+ "attributes": {}
83
+ }
84
+ },
85
+ "total_flos": 567134355456000.0,
86
+ "train_batch_size": 2,
87
+ "trial_name": null,
88
+ "trial_params": null
89
+ }
models/iraqi_proverb_model/added_tokens.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ {
2
+ "[PAD]": 64000
3
+ }
models/iraqi_proverb_model/generation_config.json ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 0,
4
+ "eos_token_id": 0,
5
+ "transformers_version": "4.46.1"
6
+ }
models/iraqi_proverb_model/merges.txt ADDED
The diff for this file is too large to render. See raw diff
 
models/iraqi_proverb_model/special_tokens_map.json ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": "<|endoftext|>",
3
+ "eos_token": "<|endoftext|>",
4
+ "pad_token": {
5
+ "content": "[PAD]",
6
+ "lstrip": false,
7
+ "normalized": false,
8
+ "rstrip": false,
9
+ "single_word": false
10
+ },
11
+ "unk_token": "<|endoftext|>"
12
+ }
models/iraqi_proverb_model/tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
models/iraqi_proverb_model/tokenizer_config.json ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_prefix_space": false,
3
+ "added_tokens_decoder": {
4
+ "0": {
5
+ "content": "<|endoftext|>",
6
+ "lstrip": false,
7
+ "normalized": false,
8
+ "rstrip": false,
9
+ "single_word": false,
10
+ "special": true
11
+ },
12
+ "1": {
13
+ "content": "<s>",
14
+ "lstrip": false,
15
+ "normalized": false,
16
+ "rstrip": false,
17
+ "single_word": false,
18
+ "special": true
19
+ },
20
+ "2": {
21
+ "content": "<pad>",
22
+ "lstrip": false,
23
+ "normalized": false,
24
+ "rstrip": false,
25
+ "single_word": false,
26
+ "special": true
27
+ },
28
+ "3": {
29
+ "content": "</s>",
30
+ "lstrip": false,
31
+ "normalized": false,
32
+ "rstrip": false,
33
+ "single_word": false,
34
+ "special": true
35
+ },
36
+ "64000": {
37
+ "content": "[PAD]",
38
+ "lstrip": false,
39
+ "normalized": false,
40
+ "rstrip": false,
41
+ "single_word": false,
42
+ "special": true
43
+ }
44
+ },
45
+ "bos_token": "<|endoftext|>",
46
+ "clean_up_tokenization_spaces": false,
47
+ "eos_token": "<|endoftext|>",
48
+ "model_max_length": 1000000000000000019884624838656,
49
+ "pad_token": "[PAD]",
50
+ "tokenizer_class": "GPT2Tokenizer",
51
+ "unk_token": "<|endoftext|>"
52
+ }
models/iraqi_proverb_model/vocab.json ADDED
The diff for this file is too large to render. See raw diff
 
notebooks/data_preprocessing.ipynb ADDED
File without changes
notebooks/fine_tuning.ipynb ADDED
File without changes
process_proverbs.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+
3
+ def process_proverbs(input_path, output_path):
4
+ try:
5
+ # Attempt to open the input file and read lines
6
+ with open(input_path, 'r', encoding='utf-8') as file:
7
+ lines = file.readlines()
8
+ print("Successfully read the input file.")
9
+ except FileNotFoundError:
10
+ print(f"File not found: {input_path}")
11
+ return
12
+
13
+ proverbs = []
14
+ current_proverb = ""
15
+
16
+ for line in lines:
17
+ # Clean the line by stripping leading/trailing whitespace
18
+ line = line.strip()
19
+ print(f"Processing line: {line}") # Debug output for each line
20
+
21
+ # Identify proverbs or meanings based on specific patterns, e.g., numbers at the start
22
+ if re.match(r'^\d+', line): # This line has a number, possibly a new entry
23
+ if current_proverb:
24
+ # Save the accumulated proverb/meaning pair
25
+ proverbs.append(current_proverb.strip())
26
+ current_proverb = line
27
+ else:
28
+ # Continue accumulating lines for the current entry
29
+ current_proverb += " " + line
30
+
31
+ # Save any remaining proverb
32
+ if current_proverb:
33
+ proverbs.append(current_proverb.strip())
34
+
35
+ # Write formatted proverbs to the output file
36
+ try:
37
+ with open(output_path, 'w', encoding='utf-8') as f:
38
+ for entry in proverbs:
39
+ f.write(entry + '\n')
40
+ print(f"Writing line to file: {entry}") # Debug print for each line written
41
+ print(f"Data successfully saved to {output_path}")
42
+ except Exception as e:
43
+ print(f"Error writing to file: {e}")
44
+
45
+ # Example usage
46
+ input_path = "iraqi_proverbs.txt" # Replace with the path to your text file
47
+ output_path = "data/raw_data/iraqi_data.txt" # Adjust this path if necessary
48
+ process_proverbs(input_path, output_path)
requirements.txt ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ torch
2
+ transformers
3
+ datasets
4
+ flask
5
+ beautifulsoup4
6
+ requests
7
+ pandas
8
+ scikit-learn
scripts/extract_from_pdf.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # scripts/extract_from_pdf.py
2
+ import pdfplumber
3
+ import os
4
+
5
+ def extract_text_from_pdf(pdf_path, output_path):
6
+ # Open the file for writing in append mode to ensure each page's content is saved immediately
7
+ os.makedirs(os.path.dirname(output_path), exist_ok=True)
8
+ with open(output_path, 'w', encoding='utf-8') as f:
9
+ with pdfplumber.open(pdf_path) as pdf:
10
+ for page_num, page in enumerate(pdf.pages, start=1):
11
+ # Define bounding boxes for each column
12
+ right_column = (page.width * 0.7, 0, page.width, page.height)
13
+
14
+ # Extract text from the right column
15
+ right_text = page.within_bbox(right_column).extract_text(x_tolerance=3, y_tolerance=3, layout=True)
16
+
17
+ # Debug output to check extracted text
18
+ print(f"\n--- Page {page_num} ---")
19
+ print("Right column (proverbs):")
20
+ print(right_text if right_text else "No text found in right column")
21
+
22
+ # Write each line from the right column directly to the file
23
+ if right_text:
24
+ right_lines = right_text.split('\n')
25
+ for line in right_lines:
26
+ # Check and print each line before writing to verify it has content
27
+ line = line.strip()
28
+ if line:
29
+ print(f"Writing line to file: {line}")
30
+ f.write(line + '\n')
31
+
32
+ print(f"Data successfully saved to {output_path}")
33
+
34
+ if __name__ == "__main__":
35
+ # Path to your PDF file
36
+ pdf_path = r"C:\Users\moham\iraqi_arabic_llm_project\iraqi_proverbs.pdf"
37
+
38
+ # Output path for the extracted proverbs
39
+ output_path = "../data/raw_data/iraqi_data.txt"
40
+
41
+ extract_text_from_pdf(pdf_path, output_path)
scripts/extract_from_pdf_with_ocr.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # scripts/extract_from_pdf_with_ocr_right_column.py
2
+ import pytesseract
3
+ from pdf2image import convert_from_path
4
+ import os
5
+ import re
6
+ from PIL import Image
7
+
8
+ # Update the Tesseract OCR path if necessary
9
+ pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe'
10
+
11
+ # Regular expression to match lines with Arabic characters
12
+ arabic_char_pattern = re.compile(r'[\u0600-\u06FF]+')
13
+
14
+ def extract_text_from_pdf_with_ocr(pdf_path, output_path):
15
+ # Open the output file in write mode
16
+ os.makedirs(os.path.dirname(output_path), exist_ok=True)
17
+ with open(output_path, 'w', encoding='utf-8') as f:
18
+ # Convert PDF pages to images
19
+ pages = convert_from_path(pdf_path, dpi=300)
20
+
21
+ for page_num, page_image in enumerate(pages, start=1):
22
+ # Define the bounding box for the right column (proverbs)
23
+ width, height = page_image.size
24
+ right_column = page_image.crop((width * 0.7, 0, width, height))
25
+
26
+ # Perform OCR on the right column with custom configuration
27
+ custom_config = r'--psm 6' # Treat the right column as a single block of text
28
+ right_text = pytesseract.image_to_string(right_column, lang="ara", config=custom_config)
29
+
30
+ # Debug output for the right column
31
+ print(f"\n--- Page {page_num} --- Right column (proverbs) ---")
32
+ print(right_text if right_text else "No text found in right column")
33
+
34
+ # Process and save only lines with Arabic text
35
+ if right_text:
36
+ right_lines = right_text.split('\n')
37
+ for line in right_lines:
38
+ line = line.strip()
39
+ if arabic_char_pattern.search(line): # Ensure line contains Arabic text
40
+ print(f"Writing line to file: {line}") # Debug output for each line
41
+ f.write(line + '\n')
42
+
43
+ print(f"Data successfully saved to {output_path}")
44
+
45
+ if __name__ == "__main__":
46
+ # Path to your PDF file
47
+ pdf_path = r"C:\Users\moham\iraqi_arabic_llm_project\iraqi_proverbs.pdf"
48
+
49
+ # Output path for the extracted proverbs
50
+ output_path = "../data/raw_data/iraqi_data.txt"
51
+
52
+ extract_text_from_pdf_with_ocr(pdf_path, output_path)
scripts/extract_from_pdf_with_ocr_right_column.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # scripts/extract_from_pdf_with_ocr_right_column.py
2
+ import pytesseract
3
+ from pdf2image import convert_from_path
4
+ import os
5
+ import re
6
+ from PIL import Image
7
+
8
+ # Update the Tesseract OCR path if necessary
9
+ pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe'
10
+
11
+ # Regular expression to match lines with Arabic characters
12
+ arabic_char_pattern = re.compile(r'[\u0600-\u06FF]+')
13
+
14
+ def extract_text_from_pdf_with_ocr(pdf_path, output_path):
15
+ # Open the output file in write mode
16
+ os.makedirs(os.path.dirname(output_path), exist_ok=True)
17
+ with open(output_path, 'w', encoding='utf-8') as f:
18
+ # Convert PDF pages to images
19
+ pages = convert_from_path(pdf_path, dpi=300)
20
+
21
+ for page_num, page_image in enumerate(pages, start=1):
22
+ # Define the bounding box for the right column (proverbs)
23
+ width, height = page_image.size
24
+ right_column = page_image.crop((width * 0.7, 0, width, height))
25
+
26
+ # Perform OCR on the right column with custom configuration
27
+ custom_config = r'--psm 6' # Treat the right column as a single block of text
28
+ right_text = pytesseract.image_to_string(right_column, lang="ara", config=custom_config)
29
+
30
+ # Debug output for the right column
31
+ print(f"\n--- Page {page_num} --- Right column (proverbs) ---")
32
+ print(right_text if right_text else "No text found in right column")
33
+
34
+ # Process and save only lines with Arabic text
35
+ if right_text:
36
+ right_lines = right_text.split('\n')
37
+ for line in right_lines:
38
+ line = line.strip()
39
+ if arabic_char_pattern.search(line): # Ensure line contains Arabic text
40
+ print(f"Writing line to file: {line}") # Debug output for each line
41
+ f.write(line + '\n')
42
+
43
+ print(f"Data successfully saved to {output_path}")
44
+
45
+ if __name__ == "__main__":
46
+ # Path to your PDF file
47
+ pdf_path = r"C:\Users\moham\iraqi_arabic_llm_project\iraqi_proverbs.pdf"
48
+
49
+ # Output path for the extracted proverbs
50
+ output_path = "../data/raw_data/iraqi_data.txt"
51
+
52
+ extract_text_from_pdf_with_ocr(pdf_path, output_path)
scripts/generate_text.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ from transformers import AutoTokenizer, AutoModelForCausalLM
3
+
4
+ def generate_text(prompt, model_name="models/iraqi_proverb_model", max_length=50):
5
+ # Load the trained model and tokenizer
6
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
7
+ model = AutoModelForCausalLM.from_pretrained(model_name)
8
+
9
+ # Encode the prompt and generate text
10
+ inputs = tokenizer.encode(prompt, return_tensors="pt")
11
+ outputs = model.generate(
12
+ inputs,
13
+ max_length=max_length,
14
+ num_return_sequences=1,
15
+ do_sample=True,
16
+ top_k=50,
17
+ pad_token_id=tokenizer.eos_token_id # Set pad_token_id to eos_token_id to avoid warnings
18
+ )
19
+
20
+ # Decode the output and print the generated text
21
+ generated_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
22
+ return generated_text
23
+
24
+ # Main script
25
+ if __name__ == "__main__":
26
+ # Get prompt from command-line arguments, default to an example prompt if none provided
27
+ prompt = sys.argv[1] if len(sys.argv) > 1 else "في العراق، يقولون"
28
+ print("Generated text:", generate_text(prompt))
scripts/inference.py ADDED
File without changes
scripts/preprocess.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # scripts/preprocess.py
2
+ import re
3
+
4
+ def clean_text(text):
5
+ text = re.sub(r'[^\u0621-\u064A\s]', '', text) # Arabic letters only
6
+ text = re.sub(r'\s+', ' ', text).strip()
7
+ return text
8
+
9
+ if __name__ == "__main__":
10
+ with open('../data/raw_data/iraqi_data.txt', 'r') as f:
11
+ raw_data = f.readlines()
12
+
13
+ cleaned_data = [clean_text(line) for line in raw_data]
14
+ with open('../data/cleaned_data/iraqi_data_cleaned.txt', 'w') as f:
15
+ for line in cleaned_data:
16
+ f.write(line + '\n')
scripts/preprocess_data.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pandas as pd
2
+
3
+ def preprocess_data(input_file, output_file):
4
+ data = []
5
+ with open(input_file, "r", encoding="utf-8") as f:
6
+ for line in f:
7
+ if " - " in line:
8
+ proverb, meaning = line.split(" - ", 1)
9
+ data.append({"proverb": proverb.strip(), "meaning": meaning.strip()})
10
+
11
+ # Save as a DataFrame
12
+ df = pd.DataFrame(data)
13
+ df.to_csv(output_file, index=False)
14
+ print(f"Data saved to {output_file}")
15
+
16
+ # Example usage
17
+ input_file = "data/raw_data/iraqi_data.txt"
18
+ output_file = "data/processed_data.csv"
19
+ preprocess_data(input_file, output_file)
scripts/scrape_data.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # scripts/scrape_data.py
2
+ import requests
3
+ from bs4 import BeautifulSoup
4
+ import os
5
+
6
+ def scrape_iraqi_arabic_text(url):
7
+ response = requests.get(url)
8
+ response.raise_for_status() # Check if the request was successful
9
+
10
+ soup = BeautifulSoup(response.content, "html.parser")
11
+
12
+ # Update these to match the actual tag and class on the website
13
+ proverbs = soup.find_all("p", class_="proverb-text") # Replace with the correct tag and class
14
+
15
+ iraqi_text = []
16
+ for proverb in proverbs:
17
+ text = proverb.get_text().strip()
18
+ if text: # Only add non-empty lines
19
+ iraqi_text.append(text)
20
+
21
+ if not iraqi_text:
22
+ print("No proverbs found. Check the tag and class names in the code.")
23
+ return iraqi_text
24
+
25
+ def save_text_to_file(text_list, relative_filepath):
26
+ project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
27
+ absolute_filepath = os.path.join(project_root, relative_filepath)
28
+ os.makedirs(os.path.dirname(absolute_filepath), exist_ok=True)
29
+
30
+ with open(absolute_filepath, 'w', encoding='utf-8') as f:
31
+ for line in text_list:
32
+ f.write(line + '\n')
33
+ print(f"Data saved to {absolute_filepath}")
34
+
35
+ if __name__ == "__main__":
36
+ url = "https://ar.mo3jam.com/dialect/Iraqi"
37
+ iraqi_data = scrape_iraqi_arabic_text(url)
38
+
39
+ # Check if any data was scraped
40
+ if iraqi_data:
41
+ save_text_to_file(iraqi_data, "data/raw_data/iraqi_data.txt")
42
+ else:
43
+ print("No data found. Please check the scraping criteria.")
scripts/train_model.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import AutoTokenizer, AutoModelForCausalLM, Trainer, TrainingArguments, TextDataset, DataCollatorForLanguageModeling
2
+ import torch
3
+
4
+ # Load the tokenizer and model
5
+ model_name = "aubmindlab/aragpt2-base" # Arabic GPT-2 model
6
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
7
+ model = AutoModelForCausalLM.from_pretrained(model_name)
8
+
9
+ # Add a padding token if not present
10
+ if tokenizer.pad_token is None:
11
+ tokenizer.add_special_tokens({'pad_token': '[PAD]'}) # Adds a [PAD] token if it's not defined
12
+ model.resize_token_embeddings(len(tokenizer)) # Resize model's embeddings to account for the new token
13
+
14
+ # Load and prepare the data for training
15
+ def load_dataset(file_path, tokenizer, block_size=128):
16
+ # Read the text data from the file
17
+ with open(file_path, "r", encoding="utf-8") as f:
18
+ text = f.read()
19
+
20
+ # Tokenize the text data
21
+ inputs = tokenizer(text, return_tensors="pt", truncation=True, padding=True, max_length=block_size)
22
+
23
+ # Return as a PyTorch dataset
24
+ dataset = TextDataset(tokenizer=tokenizer, file_path=file_path, block_size=block_size)
25
+ return dataset
26
+
27
+ # Define the path to your text data file
28
+ data_file = "data/raw_data/iraqi_data.txt" # Update this path if necessary
29
+ train_dataset = load_dataset(data_file, tokenizer)
30
+
31
+ # Set up training arguments
32
+ training_args = TrainingArguments(
33
+ output_dir="./models",
34
+ overwrite_output_dir=True,
35
+ num_train_epochs=3,
36
+ per_device_train_batch_size=2,
37
+ save_steps=10_000,
38
+ save_total_limit=2,
39
+ )
40
+
41
+ # Define the data collator for language modeling
42
+ data_collator = DataCollatorForLanguageModeling(tokenizer=tokenizer, mlm=False)
43
+
44
+ # Initialize the Trainer
45
+ trainer = Trainer(
46
+ model=model,
47
+ args=training_args,
48
+ train_dataset=train_dataset,
49
+ data_collator=data_collator,
50
+ )
51
+
52
+ # Save the trained model and tokenizer
53
+ trainer.save_model("models/iraqi_proverb_model")
54
+ tokenizer.save_pretrained("models/iraqi_proverb_model")
55
+ print("Training complete. Model and tokenizer saved to 'models/iraqi_proverb_model'.")
56
+
scripts/train_sentiment_analysis.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # scripts/train_sentiment_analysis.py
2
+ from transformers import AutoTokenizer, AutoModelForSequenceClassification, Trainer, TrainingArguments
3
+ from datasets import load_dataset
4
+
5
+ # Load the tokenizer and model
6
+ tokenizer = AutoTokenizer.from_pretrained("CAMeL-Lab/bert-base-camelbert-mix")
7
+ model = AutoModelForSequenceClassification.from_pretrained("CAMeL-Lab/bert-base-camelbert-mix", num_labels=3)
8
+
9
+ # Load and tokenize dataset
10
+ dataset = load_dataset("csv", data_files="../data/sentiment_data.csv")
11
+
12
+ def preprocess_function(examples):
13
+ return tokenizer(examples["text"], truncation=True)
14
+
15
+ tokenized_dataset = dataset.map(preprocess_function, batched=True)
16
+
17
+ # Training arguments
18
+ training_args = TrainingArguments(
19
+ output_dir="../models/sentiment_analysis_model",
20
+ evaluation_strategy="epoch",
21
+ per_device_train_batch_size=4,
22
+ num_train_epochs=3
23
+ )
24
+
25
+ trainer = Trainer(
26
+ model=model,
27
+ args=training_args,
28
+ train_dataset=tokenized_dataset["train"],
29
+ eval_dataset=tokenized_dataset["test"]
30
+ )
31
+
32
+ trainer.train()
scripts/train_text_generation.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # scripts/train_text_generation.py
2
+ from transformers import AutoTokenizer, AutoModelForCausalLM, Trainer, TrainingArguments
3
+ from datasets import load_dataset
4
+
5
+ # Replace with a public model available on Hugging Face
6
+ tokenizer = AutoTokenizer.from_pretrained("aubmindlab/bert-base-arabertv2")
7
+ model = AutoModelForCausalLM.from_pretrained("aubmindlab/bert-base-arabertv2")
8
+
9
+ # Load and tokenize dataset
10
+ dataset = load_dataset("text", data_files="../data/cleaned_data/iraqi_data_cleaned.txt")
11
+
12
+ def tokenize_function(examples):
13
+ return tokenizer(examples["text"], return_tensors="pt", truncation=True)
14
+
15
+ tokenized_dataset = dataset.map(tokenize_function, batched=True)
16
+
17
+ # Training arguments
18
+ training_args = TrainingArguments(
19
+ output_dir="../models/text_generation_model",
20
+ evaluation_strategy="epoch",
21
+ per_device_train_batch_size=2,
22
+ num_train_epochs=3
23
+ )
24
+
25
+ trainer = Trainer(
26
+ model=model,
27
+ args=training_args,
28
+ train_dataset=tokenized_dataset['train']
29
+ )
30
+
31
+ # Train the model
32
+ trainer.train()
33
+
34
+ # Save the model after training
35
+ trainer.save_model("../models/text_generation_model")
36
+ tokenizer.save_pretrained("../models/text_generation_model")