File size: 10,878 Bytes
76bfb75
bddf29f
 
2d6a87c
2d48be5
7f91fc3
 
8cac918
7f91fc3
8cac918
 
 
 
 
 
7f91fc3
8cac918
 
7f91fc3
8cac918
7f91fc3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8cac918
 
7f91fc3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7e1f943
 
4119a04
 
7f91fc3
4119a04
61e6b62
 
443053b
8c3b0f0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
443053b
8c3b0f0
d2b24d8
8c3b0f0
 
 
 
 
 
 
d2b24d8
443053b
bddf29f
e4d07f2
 
 
 
 
443053b
61e6b62
3fca7f2
3d103e2
f7bb109
3d103e2
3fca7f2
3d103e2
443053b
e4d07f2
 
bddf29f
1398651
 
 
 
 
21e8468
 
 
 
 
 
de38b62
 
 
 
 
bddf29f
 
 
99fe899
1398651
 
 
0b34e59
8d1b0ca
0b34e59
 
1bf26c9
4119a04
1bf26c9
4119a04
5c957ad
5946b43
81c73a1
 
de38b62
 
81c73a1
5946b43
4119a04
294c24c
4119a04
 
fa36f72
db05398
e9c524f
5c957ad
 
8c3b0f0
60cbd2f
5946b43
8c3b0f0
5c957ad
77698e2
7f91fc3
4119a04
d95655c
 
76bfb75
 
0b34e59
1446dbe
7e1f943
 
21e8468
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
import gradio as gr
import pandas as pd

def data_pre_processing(file_responses):
    # Financial Weights can be anything (ultimately the row-wise weights are aggregated and the corresponding fractions are obtained from that rows' total tax payed)
    
    try: # Define the columns to be processed
        
        # Developing Numeric Columns
        # Convert columns to numeric and fill NaN values with 0
        file_responses['Personal_TaxDirection_1_TaxWeightageAllocated'] = pd.to_numeric(file_responses['Personal_TaxDirection_1_TaxWeightageAllocated'], errors='coerce').fillna(0)
        file_responses['Personal_TaxDirection_2_TaxWeightageAllocated'] = pd.to_numeric(file_responses['Personal_TaxDirection_2_TaxWeightageAllocated'], errors='coerce').fillna(0)
        file_responses['Personal_TaxDirection_3_TaxWeightageAllocated'] = pd.to_numeric(file_responses['Personal_TaxDirection_3_TaxWeightageAllocated'], errors='coerce').fillna(0)
        file_responses['Latest estimated Tax payment?'] = pd.to_numeric(file_responses['Latest estimated Tax payment?'], errors='coerce').fillna(0)
        
        # Adding a new column 'TotalWeightageAllocated' by summing specific columns by their names
        file_responses['TotalWeightageAllocated'] = file_responses['Personal_TaxDirection_1_TaxWeightageAllocated'] + file_responses['Personal_TaxDirection_2_TaxWeightageAllocated'] + file_responses['Personal_TaxDirection_3_TaxWeightageAllocated']

        

        # Creating Datasets (we assume everything has been provided to us in English, or the translations have been done already)
        # Renaming the datasets into similar column headings
        initial_dataset_1 = file_responses.rename(columns={
            'Personal_TaxDirection_1_Wish': 'Problem_Description',
            'Personal_TaxDirection_1_GeographicalLocation': 'Geographical_Location',
            'Personal_TaxDirection_1_TaxWeightageAllocated': 'Financial_Weight'
        })[['Problem_Description', 'Geographical_Location', 'Financial_Weight']]
        
        initial_dataset_2 = file_responses.rename(columns={
            'Personal_TaxDirection_2_Wish': 'Problem_Description',
            'Personal_TaxDirection_2_GeographicalLocation': 'Geographical_Location',
            'Personal_TaxDirection_2_TaxWeightageAllocated': 'Financial_Weight'
        })[['Problem_Description', 'Geographical_Location', 'Financial_Weight']]
        
        initial_dataset_3 = file_responses.rename(columns={
            'Personal_TaxDirection_3_Wish': 'Problem_Description',
            'Personal_TaxDirection_3_GeographicalLocation': 'Geographical_Location',
            'Personal_TaxDirection_3_TaxWeightageAllocated': 'Financial_Weight'
        })[['Problem_Description', 'Geographical_Location', 'Financial_Weight']]


        
        # Calculating the actual TaxAmount to be allocated against each WISH (by overwriting the newly created columns)
        initial_dataset_1['Financial_Weight'] = file_responses['Personal_TaxDirection_1_TaxWeightageAllocated'] * file_responses['Latest estimated Tax payment?'] / file_responses['TotalWeightageAllocated']
        initial_dataset_2['Financial_Weight'] = file_responses['Personal_TaxDirection_2_TaxWeightageAllocated'] * file_responses['Latest estimated Tax payment?'] / file_responses['TotalWeightageAllocated']
        initial_dataset_3['Financial_Weight'] = file_responses['Personal_TaxDirection_3_TaxWeightageAllocated'] * file_responses['Latest estimated Tax payment?'] / file_responses['TotalWeightageAllocated']
        
        # Removing useless rows
        # Drop rows where Problem_Description is NaN or an empty string
        initial_dataset_1 = initial_dataset_1.dropna(subset=['Problem_Description'], axis=0)
        initial_dataset_2 = initial_dataset_2.dropna(subset=['Problem_Description'], axis=0)
        initial_dataset_3 = initial_dataset_3.dropna(subset=['Problem_Description'], axis=0)
        
        # Convert 'Problem_Description' column to string type
        initial_dataset_1['Problem_Description'] = initial_dataset_1['Problem_Description'].astype(str)
        initial_dataset_2['Problem_Description'] = initial_dataset_2['Problem_Description'].astype(str)
        initial_dataset_3['Problem_Description'] = initial_dataset_3['Problem_Description'].astype(str)
        
        # Merging the Datasets
        # Vertically concatenating (merging) the 3 DataFrames
        merged_dataset = pd.concat([initial_dataset_1, initial_dataset_2, initial_dataset_3], ignore_index=True)

        
        # Different return can be used to check the processing
        # return file_responses
        return merged_dataset
        
    except Exception as e:
        return str(e)






import spacy
from transformers import AutoTokenizer, AutoModel
import torch

# Load SpaCy model
nlp = spacy.load('en_core_web_sm')

# Load Hugging Face Transformers model
tokenizer = AutoTokenizer.from_pretrained("sentence-transformers/all-mpnet-base-v2")
model = AutoModel.from_pretrained("sentence-transformers/all-mpnet-base-v2")

# def combined_text_processing(text):
#     # Basic NLP processing using SpaCy
#     doc = nlp(text)
#     lemmatized_text = ' '.join([token.lemma_ for token in doc])
    
#     # Advanced text representation using Hugging Face Transformers
#     inputs = tokenizer(lemmatized_text, return_tensors="pt", truncation=False, padding=True)
#     with torch.no_grad():
#         outputs = model(**inputs)
    
#     return outputs.last_hidden_state.mean(dim=1).squeeze().numpy()


import re
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize

def combined_text_processing(text):
    # Remove punctuation, numbers, URLs, and special characters
    text = re.sub(r'[^\w\s]', '', text)  # Remove punctuation and special characters
    text = re.sub(r'\d+', '', text)  # Remove numbers
    text = re.sub(r'http\S+', '', text)  # Remove URLs
    
    # Tokenize and remove stopwords
    tokens = word_tokenize(text.lower())  # Convert to lowercase
    stop_words = set(stopwords.words('english'))
    tokens = [word for word in tokens if word not in stop_words]
    
    # Lemmatize tokens using SpaCy
    doc = nlp(' '.join(tokens))
    lemmatized_text = ' '.join([token.lemma_ for token in doc])
    
    # Apply Hugging Face Transformers
    inputs = tokenizer(lemmatized_text, return_tensors="pt", truncation=False, padding=True)
    with torch.no_grad():
        outputs = model(**inputs)
    
    return outputs.last_hidden_state.mean(dim=1).squeeze().numpy()

















def nlp_pipeline(original_df):
    # Data Preprocessing
    processed_df = data_pre_processing(original_df)
    
    
    # Apply the combined function to your DataFrame
    processed_df['Processed_ProblemDescription'] = processed_df['Problem_Description'].apply(combined_text_processing)
    
    
    
    return processed_df

def process_excel(file):
    try:
        # Ensure the file path is correct
        file_path = file.name if hasattr(file, 'name') else file
        # Read the Excel file
        df = pd.read_excel(file_path)
        
        # Process the DataFrame
        result_df = nlp_pipeline(df)

        output_file = "Output_ProjectProposals.xlsx"
        result_df.to_excel(output_file, index=False)
        
        return output_file  # Return the processed DataFrame as Excel file
        
    except Exception as e:
        return str(e)  # Return the error message






example_files = ['#TaxDirection (Responses)_BasicExample.xlsx',
                 '#TaxDirection (Responses)_IntermediateExample.xlsx',
                 '#TaxDirection (Responses)_UltimateExample.xlsx'
                ]


import random
a_random_object = random.choice(["⇒", "↣", "↠", "→"])



# Define the Gradio interface
interface = gr.Interface(
    fn=process_excel,  # The function to process the uploaded file
    inputs=gr.File(type="filepath", label="Upload Excel File here. \t Be sure to check that the column headings in your upload are the same as in the Example files below. \t (Otherwise there will be Error during the processing)"),  # File upload input
    
    examples=example_files,  # Add the example files
    
    # outputs=gr.File(label="Download Processed Excel File"),  # File download output
    outputs=gr.File(label="Download the processed Excel File containing the ** Project Proposals ** for each Location~Problem paired combination"),  # File download output
    
    
    # title="Excel File Uploader",
    # title="Upload Excel file containing #TaxDirections → Download HyperLocal Project Proposals\n",
    
    title = (
        "<p style='font-weight: bold; font-size: 25px; text-align: center;'>"
        "<span style='color: blue;'>Upload Excel file containing #TaxDirections</span> "
        
        # "<span style='color: brown; font-size: 35px;'>&rarr; </span>"
        # "<span style='color: brown; font-size: 35px;'>&rArr;  &rarrtl; &Rarr; </span>"
        "<span style='color: brown; font-size: 35px;'> " +a_random_object +" </span>"
        
        "<span style='color: green;'>Download HyperLocal Project Proposals</span>"
        "</p>\n"
    ),



    description=(
        "<p style='font-size: 12px; color: gray; text-align: center'>This tool allows for the systematic evaluation and proposal of solutions tailored to specific location-problem pairs, ensuring efficient resource allocation and project planning. For more information, visit <a href='https://santanban.github.io/TaxDirection/' target='_blank'>#TaxDirection weblink</a>.</p>"
        
        "<p style='font-weight: bold; font-size: 16px; color: blue;'>Upload an Excel file to process and download the result or use the Example files:</p>"
        "<p style='font-weight: bold; font-size: 15px; color: blue;'>(click on any of them to directly process the file and Download the result)</p>"
        
        "<p style='font-weight: bold; font-size: 14px; color: green; text-align: right;'>Processed output contains a Project Proposal for each Location~Problem paired combination (i.e. each cell).</p>"
        "<p style='font-weight: bold; font-size: 13px; color: green; text-align: right;'>Corresponding Budget Allocation and estimated Project Completion Time are provided in different sheets.</p>"

        
        "<p style='font-size: 12px; color: gray; text-align: center'>Note: The example files provided above are for demonstration purposes. Feel free to upload your own Excel files to see the results. If you have any questions, refer to the documentation-links or contact <a href='https://www.change.org/p/democracy-evolution-ensuring-humanity-s-eternal-existence-through-taxdirection' target='_blank'>support</a>.</p>"
        
    )  # Solid description with right-aligned second sentence

)



# Launch the interface
if __name__ == "__main__":
    interface.launch()