hmusman2804045-max commited on
Commit
ea54a5a
·
1 Parent(s): b31728c

Phase 2 and 3: Dataset collection scripts and tokenization pipeline

Browse files
Files changed (3) hide show
  1. inspect_ruemocorp.py +72 -0
  2. scripts/phase2_collect.py +177 -0
  3. test_models.py +4 -1
inspect_ruemocorp.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datasets import load_dataset
2
+ import pandas as pd
3
+ from sklearn .model_selection import train_test_split
4
+ import os
5
+ import re
6
+
7
+
8
+ DATA_DIR ='data'
9
+ os .makedirs (DATA_DIR ,exist_ok =True )
10
+
11
+
12
+ print ("Downloading RUEmoCorp...")
13
+ ds =load_dataset ("Khubaib01/RUEmoCorp","ruemocorp-annotated")
14
+ df =ds ['train'].to_pandas ()
15
+ print (f"Downloaded {len (df )} rows")
16
+
17
+
18
+ df =df .rename (columns ={
19
+ 'message':'text',
20
+ 'emotion_label':'label'
21
+ })
22
+
23
+
24
+
25
+
26
+ label_map ={
27
+ 'happy':'joy',
28
+ 'sad':'sadness',
29
+ 'anger':'anger',
30
+ 'fear':'fear',
31
+ }
32
+ df ['label']=df ['label'].map (label_map )
33
+
34
+
35
+ before =len (df )
36
+ df =df .dropna (subset =['label'])
37
+ print (f"Dropped {before -len (df )} rows (none/surprise/disgust)")
38
+
39
+
40
+ def clean_text (text ):
41
+ if not isinstance (text ,str ):
42
+ return ""
43
+ text =re .sub (r'http\S+','',text )
44
+ text =re .sub (r'@\w+','',text )
45
+ text =re .sub (r'#\w+','',text )
46
+ text =re .sub (r'\s+',' ',text )
47
+ return text .strip ()
48
+
49
+ df ['text']=df ['text'].apply (clean_text )
50
+
51
+
52
+ df =df .dropna (subset =['text'])
53
+ df =df [df ['text'].str .len ()>2 ].reset_index (drop =True )
54
+ print (f"Final clean dataset: {len (df )} rows")
55
+ print (f"Class distribution:\n{df ['label'].value_counts ()}")
56
+
57
+
58
+ train ,temp =train_test_split (
59
+ df ,test_size =0.20 ,random_state =42 ,stratify =df ['label']
60
+ )
61
+ val ,test =train_test_split (
62
+ temp ,test_size =0.50 ,random_state =42 ,stratify =temp ['label']
63
+ )
64
+
65
+
66
+ for split_name ,data in [('train',train ),('val',val ),('test',test )]:
67
+ path =os .path .join (DATA_DIR ,f'roman_urdu_emotion_{split_name }.csv')
68
+ data .to_csv (path ,index =False ,encoding ='utf-8-sig')
69
+ print (f"Saved {path } ({len (data )} rows)")
70
+
71
+ print ("\nDone! RUEmoCorp cleaned and split.")
72
+ print ("Now combine with SemEval and retrain emotion model on Kaggle.")
scripts/phase2_collect.py ADDED
@@ -0,0 +1,177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import os
3
+ import re
4
+ import sys
5
+ import requests
6
+ import pandas as pd
7
+ from datasets import load_dataset
8
+ from sklearn .model_selection import train_test_split
9
+
10
+ DATA_DIR =os .path .dirname (os .path .abspath (__file__ ))
11
+
12
+ def separator (title ):
13
+ print ("\n"+"="*60 )
14
+ print (f" {title }")
15
+ print ("="*60 )
16
+
17
+ def clean_text (text ):
18
+ if not isinstance (text ,str ):
19
+ return ""
20
+ text =re .sub (r'http\S+','',text )
21
+ text =re .sub (r'@\w+','',text )
22
+ text =re .sub (r'#\w+','',text )
23
+ text =re .sub (r'\s+',' ',text )
24
+ return text .strip ()
25
+
26
+ def split_and_save (df ,name ,text_col ,label_col ):
27
+ df =df [[text_col ,label_col ]].rename (columns ={text_col :'text',label_col :'label'})
28
+ df =df .dropna (subset =['text','label'])
29
+ df ['text']=df ['text'].apply (clean_text )
30
+ df =df [df ['text'].str .len ()>2 ].reset_index (drop =True )
31
+
32
+ train ,temp =train_test_split (df ,test_size =0.20 ,random_state =42 ,stratify =df ['label'])
33
+ val ,test =train_test_split (temp ,test_size =0.50 ,random_state =42 ,stratify =temp ['label'])
34
+
35
+ for split ,data in [('train',train ),('val',val ),('test',test )]:
36
+ path =os .path .join (DATA_DIR ,f'{name }_{split }.csv')
37
+ data .to_csv (path ,index =False ,encoding ='utf-8-sig')
38
+ print (f" Saved {path } ({len (data )} rows)")
39
+
40
+ return train ,val ,test
41
+
42
+ separator ("DATASET 1: Roman Urdu Sentiment (HuggingFace)")
43
+ try :
44
+ ds1 =load_dataset ('community-datasets/roman_urdu',trust_remote_code =True )
45
+ print ("Available splits:",list (ds1 .keys ()))
46
+ df1 =ds1 ['train'].to_pandas ()
47
+ print (f"Columns : {df1 .columns .tolist ()}")
48
+ print (f"Shape : {df1 .shape }")
49
+ print (f"Sample row :\n{df1 .iloc [0 ]}")
50
+ print (f"\nLabel dist. :\n{df1 .iloc [:,-1 ].value_counts ()}")
51
+
52
+ text_col =df1 .columns [0 ]
53
+ label_col =df1 .columns [-1 ]
54
+ print (f"\nUsing text='{text_col }' label='{label_col }'")
55
+ split_and_save (df1 ,'roman_urdu_sentiment',text_col ,label_col )
56
+ print ("Dataset 1 DONE")
57
+ except Exception as e :
58
+ print (f"ERROR loading Dataset 1: {e }")
59
+
60
+ separator ("DATASET 2: SemEval 2018 Task 1 - Emotion (HuggingFace)")
61
+ try :
62
+ ds2 =load_dataset ('SemEvalWorkshop/sem_eval_2018_task_1','subtask5.english',trust_remote_code =True )
63
+ print ("Available splits:",list (ds2 .keys ()))
64
+
65
+ frames =[]
66
+ for split_name in ds2 .keys ():
67
+ tmp =ds2 [split_name ].to_pandas ()
68
+ frames .append (tmp )
69
+ df2_all =pd .concat (frames ,ignore_index =True )
70
+
71
+ print (f"Columns : {df2_all .columns .tolist ()}")
72
+ print (f"Shape : {df2_all .shape }")
73
+ print (f"Sample :\n{df2_all .iloc [0 ]}")
74
+
75
+ emotion_cols =['anger','anticipation','disgust','fear','joy',
76
+ 'love','optimism','pessimism','sadness','surprise','trust']
77
+ target_emotions =['joy','anger','fear','sadness']
78
+ available =[c for c in target_emotions if c in df2_all .columns ]
79
+
80
+ if available :
81
+ df2_all ['label']=df2_all [available ].idxmax (axis =1 )
82
+ df2_all ['max_score']=df2_all [available ].max (axis =1 )
83
+ df2_all =df2_all [df2_all ['max_score']>0 ]
84
+ text_col2 ='Tweet'if 'Tweet'in df2_all .columns else df2_all .columns [0 ]
85
+ print (f"\nEmotion dist.:\n{df2_all ['label'].value_counts ()}")
86
+ split_and_save (df2_all ,'semeval_emotion',text_col2 ,'label')
87
+ print ("Dataset 2 DONE")
88
+ else :
89
+ print (f"Emotion columns not found. Available: {df2_all .columns .tolist ()}")
90
+ except Exception as e :
91
+ print (f"ERROR loading Dataset 2: {e }")
92
+ print ("Trying alternate config...")
93
+ try :
94
+ print ("Available configs:")
95
+ from datasets import get_dataset_config_names
96
+ configs =get_dataset_config_names ('SemEvalWorkshop/sem_eval_2018_task_1')
97
+ print (configs )
98
+ except Exception as e2 :
99
+ print (f"Could not list configs: {e2 }")
100
+
101
+ separator ("DATASET 3: mirfan899 Urdu Sentiment TSV (GitHub Download)")
102
+ tar_path =os .path .join (DATA_DIR ,'urdu.tsv.tar.gz')
103
+ tsv_path =os .path .join (DATA_DIR ,'urdu_v1.tsv')
104
+ try :
105
+ if not os .path .exists (tsv_path ):
106
+ url ='https://raw.githubusercontent.com/mirfan899/Urdu/master/sentiment/urdu.tsv.tar.gz'
107
+ print (f"Downloading from: {url }")
108
+ r =requests .get (url ,timeout =30 )
109
+ r .raise_for_status ()
110
+ with open (tar_path ,'wb')as f :
111
+ f .write (r .content )
112
+ print (f"Downloaded successfully ({len (r .content )} bytes)")
113
+
114
+ import tarfile
115
+ with tarfile .open (tar_path ,"r:gz")as tar :
116
+ tar .extractall (path =DATA_DIR )
117
+ print ("Extracted urdu_v1.tsv")
118
+
119
+ for sep in ['\t',',',';']:
120
+ try :
121
+ df3 =pd .read_csv (tsv_path ,sep =sep ,header =0 ,encoding ='utf-8')
122
+ if df3 .shape [1 ]>=2 :
123
+ break
124
+ except :
125
+ continue
126
+
127
+ print (f"Columns : {df3 .columns .tolist ()}")
128
+ print (f"Shape : {df3 .shape }")
129
+ print (f"\nLabel dist.:\n{df3 .iloc [:,-1 ].value_counts ()}")
130
+
131
+ split_and_save (df3 ,'mirfan_urdu_sentiment',df3 .columns [0 ],df3 .columns [-1 ])
132
+ print ("Dataset 3 DONE")
133
+ except Exception as e :
134
+ print (f"ERROR loading Dataset 3: {e }")
135
+
136
+ separator ("DATASET 4: Urdu Sentiment Corpus (GitHub Download)")
137
+ tsv4_path =os .path .join (DATA_DIR ,'urdu-sentiment-corpus-v1.tsv')
138
+ try :
139
+ if not os .path .exists (tsv4_path ):
140
+ url4 ='https://raw.githubusercontent.com/MuhammadYaseenKhan/Urdu-Sentiment-Corpus/master/urdu-sentiment-corpus-v1.tsv'
141
+ print (f"Downloading from: {url4 }")
142
+ r4 =requests .get (url4 ,timeout =30 )
143
+ r4 .raise_for_status ()
144
+ with open (tsv4_path ,'wb')as f :
145
+ f .write (r4 .content )
146
+ print (f"Downloaded successfully ({len (r4 .content )} bytes)")
147
+
148
+ for enc in ['utf-8','utf-8-sig','cp1252','latin-1']:
149
+ try :
150
+ df4 =pd .read_csv (tsv4_path ,sep ='\t',encoding =enc )
151
+ break
152
+ except :
153
+ continue
154
+
155
+ print (f"Columns : {df4 .columns .tolist ()}")
156
+ print (f"Shape : {df4 .shape }")
157
+
158
+ text_col4 =df4 .columns [0 ]
159
+ label_col4 =df4 .columns [-1 ]
160
+ print (f"\nLabel dist.:\n{df4 [label_col4 ].value_counts ()}")
161
+ split_and_save (df4 ,'urdu_sentiment_corpus',text_col4 ,label_col4 )
162
+ print ("Dataset 4 DONE")
163
+ except Exception as e :
164
+ print (f"ERROR loading Dataset 4: {e }")
165
+
166
+ separator ("PHASE 2 COMPLETE — Summary of saved files")
167
+ all_files =[f for f in os .listdir (DATA_DIR )if f .endswith ('.csv')]
168
+ print (f"{'File':<45} {'Rows':>6}")
169
+ print ("-"*55 )
170
+ for f in sorted (all_files ):
171
+ path =os .path .join (DATA_DIR ,f )
172
+ try :
173
+ n =len (pd .read_csv (path ,encoding ='utf-8-sig'))
174
+ print (f"{f :<45} {n :>6}")
175
+ except :
176
+ print (f"{f :<45} (error reading)")
177
+ print ("\nAll datasets collected, cleaned, and split. Ready for Phase 3.")
test_models.py CHANGED
@@ -1,8 +1,11 @@
1
  import os
 
2
  import torch
3
  import numpy as np
4
  from transformers import AutoTokenizer ,AutoModelForSequenceClassification
5
 
 
 
6
  def main ():
7
  print ("="*60 )
8
  print (" Loading Urdu Sentiment & Emotion Models...")
@@ -31,7 +34,7 @@ def main ():
31
  print (f"Error loading models. Are you sure they finished training? ({e })")
32
  return
33
 
34
- print ("\n✅ Models loaded successfully!")
35
  print ("Type an Urdu sentence (Roman or Script) to test them. Type 'exit' to quit.\n")
36
 
37
 
 
1
  import os
2
+ import sys
3
  import torch
4
  import numpy as np
5
  from transformers import AutoTokenizer ,AutoModelForSequenceClassification
6
 
7
+ sys .stdout .reconfigure (encoding ='utf-8')
8
+
9
  def main ():
10
  print ("="*60 )
11
  print (" Loading Urdu Sentiment & Emotion Models...")
 
34
  print (f"Error loading models. Are you sure they finished training? ({e })")
35
  return
36
 
37
+ print ("\nModels loaded successfully!")
38
  print ("Type an Urdu sentence (Roman or Script) to test them. Type 'exit' to quit.\n")
39
 
40