SunnyHamm commited on
Commit
1212e16
·
1 Parent(s): ddfd5fe

sm UI v1.11

Browse files
Files changed (3) hide show
  1. UI_input_output.py +102 -0
  2. requirements.txt +10 -0
  3. sm_ui.py +223 -0
UI_input_output.py ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pandas as pd
2
+ import numpy as np
3
+ from scipy.sparse import csr_matrix
4
+ import gensim.downloader as api
5
+ from sentence_transformers import SentenceTransformer, util
6
+ from sklearn.feature_extraction.text import CountVectorizer
7
+ from gensim.utils import simple_preprocess
8
+ from concurrent.futures import ThreadPoolExecutor
9
+ import torch
10
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
11
+
12
+ from sentence_transformers import SentenceTransformer
13
+
14
+
15
+ def read_clean_model(input_df, mdr_df, model_path):
16
+
17
+ input_columns_to_check = ["variable", "description"]
18
+ mdr_columns_to_check = ["name", "definition"]
19
+
20
+ # drop missing, drop dups
21
+ input_df = input_df.dropna(subset=input_columns_to_check)
22
+ mdr_df = mdr_df.dropna(subset=mdr_columns_to_check)
23
+
24
+ input_df = input_df.drop_duplicates(subset=['variable'])
25
+ mdr_df = mdr_df.drop_duplicates(subset=['name'])
26
+
27
+ # Remove place holders like TBD
28
+
29
+ placeholder_vars = ['tbd'] # lower case
30
+
31
+ for var in placeholder_vars:
32
+ for col in mdr_columns_to_check:
33
+ to_drop = mdr_df[mdr_df[col].str.lower()==var].index
34
+ mdr_df = mdr_df.drop(to_drop)
35
+
36
+ for var in placeholder_vars:
37
+ for col in input_columns_to_check:
38
+ to_drop = input_df[input_df[col].str.lower()==var].index
39
+ input_df = input_df.drop(to_drop)
40
+
41
+ # removed derived
42
+ derived_data_type_list = ['_DVAL', '_DSUM']
43
+
44
+ mdr_df['derived'] = 'no'
45
+ mask_derived = (mdr_df['name'].str.contains('|'.join(derived_data_type_list), case=False, na=False))
46
+ mdr_df.loc[mask_derived, 'derived'] = 'yes'
47
+ mdr_df = mdr_df[mdr_df['derived'] == 'no']
48
+
49
+ input_df['derived'] = 'no'
50
+ mask_derived = (input_df['variable'].str.contains('|'.join(derived_data_type_list), case=False, na=False))
51
+ input_df.loc[mask_derived, 'derived'] = 'yes'
52
+ input_df = input_df[input_df['derived'] == 'no']
53
+
54
+ print(input_df.shape)
55
+ print(mdr_df.shape)
56
+
57
+ ## Model learning ...
58
+ # model = SentenceTransformer('all-MiniLM-L6-v2').to(device)
59
+ # mannually load the model due to not able to connect to huggingface.co at running time from census laptop :
60
+ model = SentenceTransformer(f'{model_path}/all-MiniLM-L6-v2').to(device)
61
+
62
+ # Encode the existing descriptions from the MDR dataset into embeddings
63
+ definitionEmbeddingsB = model.encode(input_df['description'].tolist(), convert_to_tensor=True).to(device)
64
+ definitionEmbeddingsA = model.encode(mdr_df["definition"].tolist(), convert_to_tensor=True).to(device)
65
+
66
+ # Initialize a list to store results
67
+ results = []
68
+
69
+ for i, embeddingA in enumerate(definitionEmbeddingsA):
70
+ similarities = util.pytorch_cos_sim(embeddingA, definitionEmbeddingsB)
71
+ most_similar_idx = similarities.argmax().item()
72
+ similarity_score = round(similarities[0][most_similar_idx].item() * 100, 1)
73
+ result = {
74
+ "input_name": input_df.iloc[most_similar_idx][["variable"][0]] if ["variable"] and ["variable"][0] in input_df.columns else None,
75
+ "input_descr": input_df['description'].iloc[most_similar_idx],
76
+ "mdr_name": mdr_df.iloc[i][["name"][0]] if ["name"] and ["name"][0] in mdr_df.columns else None,
77
+ "mdr_descr": mdr_df["definition"].iloc[i],
78
+ "similarity_score": similarity_score
79
+ }
80
+
81
+ results.append(result)
82
+
83
+ results_df = pd.DataFrame(results)
84
+ sorted_df = results_df.sort_values(by=['similarity_score'], ascending=[False])
85
+ # sorted_df['similarity_score'] = sorted_df['similarity_score'].apply(lambda x: str(x) + '%') not converting to string, otherwise slider function doesn't work
86
+ sorted_df = sorted_df.drop_duplicates(subset=["input_descr", "mdr_descr"]).reset_index(drop=True)
87
+
88
+ return sorted_df
89
+
90
+
91
+ if __name__ == '__main__':
92
+
93
+ print('something')
94
+
95
+ # # Load datasets
96
+ # file_path_input = "data/raw/ABS-MOPS Variables - December 11 2024.xlsm"
97
+ # file_path_mdr = "data/raw/mdr Variables 1.xlsx"
98
+
99
+ # input_df = pd.read_excel(file_path_input, sheet_name="Data Sheet", header=12).rename(columns={'Unnamed: 3':'Legacy Variable'})
100
+ # mdr_df = pd.read_excel(file_path_mdr)
101
+
102
+ # output_df = read_clean_model(input_df, mdr_df)
requirements.txt ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ pandas==2.2.3
2
+ numpy==1.26.4
3
+ torch==2.6.0
4
+ sentence_transformers==4.1.0
5
+ scipy==1.13.1
6
+ scikit-learn==1.6.1
7
+ openpyxl==3.1.5
8
+ gradio==5.27.1
9
+ chardet==5.2.0
10
+ gensim==4.3.3
sm_ui.py ADDED
@@ -0,0 +1,223 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # coding: utf-8
3
+
4
+ # In[1]:
5
+
6
+
7
+ import pandas as pd
8
+ import numpy as np
9
+ import gradio as gr
10
+
11
+ import os, tempfile
12
+ from scipy.sparse import csr_matrix
13
+ import gensim.downloader as api
14
+ from sentence_transformers import SentenceTransformer, util
15
+ from sklearn.feature_extraction.text import CountVectorizer
16
+ from gensim.utils import simple_preprocess
17
+ from concurrent.futures import ThreadPoolExecutor
18
+ import chardet
19
+ import torch
20
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
21
+
22
+ from UI_input_output import read_clean_model
23
+ pd.set_option('display.max_columns', None)
24
+ pd.set_option('display.max_colwidth',500)
25
+
26
+ # In[2]:
27
+
28
+ # where we saved the models. due to not able to connect to huggingface.co, we are running the models offline mode
29
+ model_path = './models'
30
+
31
+ # Declare global placeholder for dataframes
32
+ input_df = pd.DataFrame()
33
+ mdr_df = pd.DataFrame()
34
+ result_df = pd.DataFrame()
35
+
36
+ # to load the csv files as input and mdr file; return a list of columns for users to select
37
+ def load_csvs(file_path_input, file_path_mdr):
38
+ global input_df, mdr_df
39
+
40
+ file_missing_msg = """<p>
41
+ <span style="font-weight:bold; color:red; font-size:20px;">At least one of the files is missing from upload</span>.
42
+ </p>"""
43
+
44
+ if file_path_input is None or file_path_mdr is None:
45
+ return None, None, file_missing_msg
46
+
47
+ # Read both files into DataFrames with their own encoding
48
+ with open(file_path_input, 'rb') as f:
49
+ result = chardet.detect(f.read())
50
+ encoding_input = result['encoding']
51
+
52
+ with open(file_path_mdr, 'rb') as f:
53
+ result = chardet.detect(f.read())
54
+ encoding_mdr = result['encoding']
55
+
56
+ input_df = pd.read_csv(file_path_input, encoding=encoding_input)
57
+ mdr_df = pd.read_csv(file_path_mdr, encoding=encoding_mdr)
58
+
59
+ return gr.update(choices=input_df.columns.tolist(), value=None), gr.update(choices=input_df.columns.tolist(), value=None), gr.update(choices=mdr_df.columns.tolist(), value=None), gr.update(choices=mdr_df.columns.tolist(), value=None), None
60
+
61
+
62
+ # Once files are ready, users to select the columns from each, to run through the models to create a final dataframe with similarity scores
63
+ ## will prompt users to select at least the key columns from each file. because the models will use the key columns
64
+ def process_two_csvs(input_cols1, input_cols2, mdr_cols1, mdr_cols2):
65
+ global input_df, mdr_df, result_df
66
+
67
+ # # the key columns from input and mdr. we will rename whatever users selected to these names later
68
+ # input_key_columns: 'variable','description'
69
+ # mdr_key_columns: 'name','definition'
70
+
71
+ select_2_msg = """<p>Please select:
72
+ <span style="font-weight:bold; color:red; font-size:20px;">1 column (only 1)</span>
73
+ for each dropdown
74
+ </p>"""
75
+
76
+ if not input_cols1 or not input_cols2 or not mdr_cols1 or not mdr_cols2:
77
+ return None, None, select_2_msg
78
+
79
+ else:
80
+ if len(input_cols1)>1 or len(input_cols2)>1 or len(mdr_cols1)>1 or len(mdr_cols2)>1:
81
+ return None, None, select_2_msg
82
+
83
+ try:
84
+
85
+ # print('\n input selected columns:')
86
+ # print(input_cols1[0], type(input_cols1[0]))
87
+ # print(input_cols2[0], type(input_cols2[0]))
88
+ # print('\n mdr selected columns:')
89
+ # print(mdr_cols1[0], type(mdr_cols1[0]))
90
+ # print(mdr_cols2[0], type(mdr_cols2[0]))
91
+
92
+ # print(input_df[[input_cols1[0], input_cols2[0]]].head())
93
+ # print(mdr_df[[mdr_cols1[0], mdr_cols2[0]]].head())
94
+
95
+ # input col1 is the equivalent of variable, input col2 is equivalent of description
96
+ # mdr col1 is the equivalent of name, mdr col2 is equivalent of definition
97
+ input_df = input_df[[input_cols1[0], input_cols2[0]]].rename(columns={input_cols1[0]:'variable',input_cols2[0]:'description'})
98
+ mdr_df = mdr_df[[mdr_cols1[0], mdr_cols2[0]]].rename(columns={mdr_cols1[0]:'name',mdr_cols2[0]:'definition'})
99
+ # print('\n')
100
+ # print(input_df.head())
101
+ # print(mdr_df.head())
102
+
103
+ print('\n')
104
+ print(input_df.shape)
105
+ print(mdr_df.shape)
106
+
107
+ # clean and run through models
108
+ result_df = read_clean_model(input_df, mdr_df, model_path)
109
+
110
+ # result_df = pd.read_csv(r"C:\Users\hamme040\Documents\work\ECON\sematch\data_for_testing\tmpmwtn5lgn_abs_num.csv") # for demo, faster display
111
+
112
+ # # flag where one input variable matched multiple name from MDR
113
+ result_df['Flag'] = (result_df['input_name'].duplicated(keep=False) | result_df['mdr_name'].duplicated(keep=False)) \
114
+ .map(lambda x: '🔴 Duplicate' if x else '✅ Unique')
115
+
116
+ # sort for displaying table
117
+ result_df = result_df.sort_values(by=['input_name','mdr_name'])
118
+
119
+ # Use the system temp directory to save result dataframe as a CSV temp file
120
+ temp_dir = tempfile.gettempdir()
121
+ custom_filename = "cos_similarity.csv"
122
+ file_path = os.path.join(temp_dir, custom_filename)
123
+ result_df.to_csv(file_path, index=False)
124
+
125
+ return result_df, file_path, None
126
+
127
+ except Exception as e:
128
+ return None, None, f"Error during processing: {e}"
129
+
130
+
131
+ # silder: to filter the similarity score based on a threshold
132
+ def filter_data(threshold):
133
+ global result_df
134
+ df = result_df.copy()
135
+ df["similarity_score"] = df["similarity_score"].astype(float)
136
+ filtered_df = df[df["similarity_score"] >= threshold]
137
+ return filtered_df
138
+
139
+
140
+ ######################################## APP ###########################################
141
+ with gr.Blocks() as demo:
142
+
143
+ ################## app layout ####################
144
+ gr.Markdown("# Semantic Matching between Input and MDR")
145
+
146
+ with gr.Row():
147
+
148
+ # box to load the input file
149
+ l1 = gr.Markdown(
150
+ """
151
+ Upload Input file
152
+ (file must contains at least two columns (not case sensitive): **variable** and **description**)
153
+ """)
154
+ csv_input = gr.File(label="Upload Input File",
155
+ file_types=[".csv"])
156
+
157
+ # box to load the MDR file
158
+ l2 = gr.Markdown(
159
+ """
160
+ Upload MDR file
161
+ (file must contains at least two columns (not case sensitive): **name** and **definition**)
162
+ """)
163
+ csv_mdr = gr.File(label="Upload MDR File",
164
+ file_types=[".csv"])
165
+
166
+ errmsg_load = gr.HTML(label="Error message") # to display error message for load csvs
167
+
168
+ # button to click and initiate loading the files
169
+ load_button = gr.Button("Load CSVs")
170
+
171
+ # dropdowns for users to select the columns from their uploaded files, for further processing
172
+ with gr.Row():
173
+
174
+ input_cols_dropdown1 = gr.Dropdown(label="Select VAR column from Input", choices=[], multiselect=True, interactive=True) # mutiselect=True automatically return a list
175
+ input_cols_dropdown2 = gr.Dropdown(label="Select Description column from Input", choices=[], multiselect=True, interactive=True) # mutiselect=True automatically return a list
176
+
177
+ mdr_cols_dropdown1 = gr.Dropdown(label="Select VAR column from MDR", choices=[], multiselect=True, interactive=True)
178
+ mdr_cols_dropdown2 = gr.Dropdown(label="Select Description column from MDR", choices=[], multiselect=True, interactive=True)
179
+
180
+
181
+ errmsg_proc = gr.HTML(label="Error message") # to display error message for process csvs
182
+
183
+ # button to click and initiate processing the files, i.e. clean the data sets, run through models
184
+ process_btn = gr.Button("Process Files")
185
+
186
+ # table that displays the final result dataframe
187
+ output_table = gr.Dataframe(
188
+ interactive=True, # True Enables sorting, and editing; need False in order to do the filtering
189
+ row_count=10,
190
+ column_widths="auto"
191
+ )
192
+
193
+ # the link that enables download of this result table
194
+ download_link = gr.File(label="⬇️ Download Result CSV")
195
+
196
+ # slider, for filtering similarity score as a threshold
197
+ slider = gr.Slider(minimum=0, maximum=100, step=1, value=70, label="Similarity Score")
198
+
199
+
200
+ ################## app functions ####################
201
+ # link load button to its function and input output
202
+ load_button.click(
203
+ fn=load_csvs,
204
+ inputs=[csv_input, csv_mdr],
205
+ outputs=[input_cols_dropdown1, input_cols_dropdown2, mdr_cols_dropdown1, mdr_cols_dropdown2, errmsg_load]
206
+ )
207
+
208
+ # link process button to its function and input output
209
+ process_btn.click(
210
+ fn=process_two_csvs,
211
+ inputs=[input_cols_dropdown1, input_cols_dropdown2, mdr_cols_dropdown1, mdr_cols_dropdown2],
212
+ outputs=[output_table, download_link, errmsg_proc]
213
+ )
214
+
215
+ # link slider to its function and input output
216
+ slider.change(fn=filter_data, inputs=slider, outputs=output_table)
217
+
218
+
219
+ demo.launch()
220
+
221
+
222
+
223
+ # watchmedo auto-restart --patterns="*.py" -- python sm_ui.py