make a pro GUI for below python code:
import os, sys, re
import shutil
import zipfile
import pandas as pd
import glob
import random
from numpy import NaN
ch = ["!","@","#","$","%","&","⌛"]
root_dir = '..\ExportResult'
csv_dir = 'CSV'
lte_dir = 'LTE'
umts_dir = 'UMTS'
gsm_dir = 'GSM'
data_dir = 'Data'
def error_handle(msg: str) -> None:
exc_type, exc_obj, exc_tb = sys.exc_info()
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
# print(str(fname) + '-' + str(exc_tb.tb_lineno) + '\t' + msg)
def write_to_excel(output_data, output_file_path):
try:
output_df = pd.DataFrame(output_data)
sort_columns = ['City', 'MNC', 'Ch_From','Ch_To']
output_df = output_df.sort_values(by=sort_columns, ascending=True)
output_df.to_excel(output_file_path, index=False)
# print("output file created.")
print(" #", ' '.join(random.choice(ch) for _ in range(10)), "#", end="\r")
except Exception as e:
error_handle(f"Error in writing on output excel file: {e}")
def read_excel_file(file_path):
try:
df = pd.read_excel(file_path)
return df
except Exception as e:
error_handle(f"Error in writing on output excel file: {e}")
return None
def extract_city_name(filename):
city_name = filename.split('_')[0]
return city_name
def delete_file(f:str, msg:str=None):
if msg:
print(msg)
os.system('cmd /c "del /f '+f+'"')
def clear_garbage_chr(text):
return re.sub(r'[^a-zA-Z\s]', '', text)
def merge_excel_files(folder_path, output_file):
excel_files = glob.glob(folder_path + "/*.xlsx")
if not excel_files:
print(f"Excel files not founded in {folder_path}")
return
merged_df = pd.DataFrame()
for file in excel_files:
try:
# print("Read", file,"->", output_file)
# print("Reading ", file)
print(" #", ' '.join(random.choice(ch) for _ in range(10)), "#", end="\r")
df = pd.read_excel(file)
merged_df = pd.concat([merged_df, df])
except Exception as e:
error_handle(f"An error occurred reading or processing file {file}: {str(e)}")
try:
required_columns = ['MNC', 'City', 'Frequency']
merged_df = merged_df.sort_values(by=required_columns, ascending=True)
merged_df['City'] = merged_df['City'].apply(clear_garbage_chr)
merged_df['New_Column'] = merged_df.iloc[:, 0].astype(str) + merged_df.iloc[:, 1].astype(str) + merged_df.iloc[:, 3].astype(str) + merged_df.iloc[:, 5].astype(str)
merged_df = merged_df.drop_duplicates(subset=['New_Column'], keep='first')
merged_df = merged_df.drop(columns=['New_Column'])
merged_df.to_excel(output_file, index=False)
# print(f"Output file successfully saved to {output_file}.")
print(" #", ' '.join(random.choice(ch) for _ in range(10)), "#", end="\r")
except Exception as e:
error_handle(f"Error saving output file: {str(e)}")
*****************************************************************************************
*****************************************************************************************
******** ********
******** First Step ********
******** Make Directories. Extract CSV files and copy them into working ********
******** Directory and create primitive excel files(GSM, UMTS, LTE, CSV) ********
******** ********
*****************************************************************************************
*****************************************************************************************
root_dir = input('\nEnter path of "ExportResult" folder: (Def: ..\ExportResult)') or root_dir
for dir in [lte_dir, umts_dir, gsm_dir, data_dir, csv_dir]:
if not os.path.exists(dir):
os.makedirs(dir)
for root, dirs, files in os.walk(root_dir):
for file in files:
file_path = os.path.join(root, file)
if 'LTE_TecRaw' in file:
# print(f"Copy\t{file_path} -> {lte_dir}")
# print(f"Reading\t{file_path}")
print(" #", ' '.join(random.choice(ch) for _ in range(10)), "#", end="\r")
shutil.copy(file_path, lte_dir)
elif 'UMTS_TecRaw' in file:
# print(f"Copy\t{file_path} -> {umts_dir}")
# print(f"Reading\t{file_path}")
print(" #", ' '.join(random.choice(ch) for _ in range(10)), "#", end="\r")
shutil.copy(file_path, umts_dir)
elif 'GSM_TecRaw' in file:
# print(f"Copy\t{file_path} -> {gsm_dir}")
# print(f"Reading\t{file_path}")
print(" #", ' '.join(random.choice(ch) for _ in range(10)), "#", end="\r")
shutil.copy(file_path, gsm_dir)
if 'R&S LTE Scanner' in file and 'trans_tree' in file and 'TSMW' not in file:
prefix = os.path.basename(root)
target_file = f'{os.getcwd()}\{data_dir}\{prefix}_{file}'
# print(f"Copy\t{file_path} -> {data_dir}")
# print(f"Reading\t{file_path}")
print(" #", ' '.join(random.choice(ch) for _ in range(10)), "#", end="\r")
shutil.copy(file_path, target_file)
def process_csv_to_excel(dir):
# print("Process ", dir)
for file in os.listdir(dir):
if file.endswith('.csv'):
file_path = os.path.join(dir, file)
try:
with open(file_path, 'r') as f:
content = f.read()
start_index = content.find('Date;Time;UTC;Latitude;Longitude;')
if start_index!= -1:
data_content = content[start_index:]
with open(".\\CSV\\"+file, "w") as csv_out:
csv_out.write(data_content.replace(" ",""))
csv_out.close()
if 'UMTS' in file:
data = []
with open(".\\CSV\\"+file, 'r', encoding='utf-8') as f:
column_labels = f.readline().strip().split(';')
for line in f:
data.append(line.strip().split(';')[:30])
df = pd.DataFrame(data, columns=column_labels, )
else:
df = pd.read_csv(".\\CSV\\"+file, delimiter=';')
inserted_tech = ""
if 'LTE' in file:
columns_to_keep = ['Date', 'EARFCN', 'Frequency', 'MNC']
inserted_tech = 'LTE'
elif 'GSM'in file:
columns_to_keep = ['Date', 'ARFCN', 'Frequency', 'MNC']
inserted_tech = 'GSM'
elif 'UMTS' in file:
columns_to_keep = ['Date', 'UARFCN', 'Frequency', 'MNC']
inserted_tech = 'UMTS'
df = df[columns_to_keep]
# df = df[~df['MNC'].isin([0, ' ', '', None])]
df = df[
~( # Negation to select the opposite of the conditions below
df['MNC'].isnull() | # Catch NaN, None
(df['MNC'].astype(str).str.strip() == '') | # Empty strings after stripping whitespace
(df['MNC'] == 0) # Exact zero match for numeric types
)
]
df.insert(0, 'Tech', inserted_tech)
df.insert(0, 'City', extract_city_name(file))
excel_file_path = file_path.replace('.csv', '.xlsx')
# print("Delete ", file_path)
print(" #", ' '.join(random.choice(ch) for _ in range(10)), "#", end="\r")
# delete_file(file_path)
os.system(f'cmd /c "del /q /f {file_path}"')
df.to_excel(excel_file_path, index=False)
# print(f"{file} saved in {dir}")
print(" #", ' '.join(random.choice(ch) for _ in range(10)), "#", end="\r")
except Exception as e:
error_handle(f"error in {file} process in {dir}: {str(e)}")
for dir in [lte_dir, umts_dir, gsm_dir]:
process_csv_to_excel(dir)
for dir in [lte_dir, umts_dir, gsm_dir]:
folder_path = '.\'+dir
output_file = dir.upper()+'.xlsx'
merge_excel_files(folder_path, output_file)
*****************************************************************************************
*****************************************************************************************
******** ********
******** Second Step ********
******** Analyze GSM ********
******** ********
*****************************************************************************************
*****************************************************************************************
def analyze_gsm_data(df):
try:
output_data = []
cities = df['City'].unique()
for city in cities:
city_df = df[df['City'] == city]
techs = city_df['Tech'].unique()
for tech in techs:
tech_df = city_df[city_df['Tech'] == tech]
dates = tech_df['Date'].unique()
for date in dates:
date_df = tech_df[tech_df['Date'] == date]
mncs = date_df['MNC'].unique()
for mnc in mncs:
mnc_df = date_df[date_df['MNC'] == mnc]
arfcns = mnc_df['ARFCN'].tolist()
freqs = mnc_df['Frequency'].tolist()
if len(arfcns) > 0:
arfcns.sort()
freqs.sort()
seq = [arfcns[0]]
freq = [freqs[0]]
for i in range(1, len(arfcns)):
if arfcns[i] - arfcns[i-1] == 1:
seq.append(arfcns[i])
else:
# dl_band_from= 934.9+0.2*seq[0] if 900000000<=freq[0]<=1000000000 else 1805.1+0.2*(seq[0]-512)
# dl_band_to = 934.9+0.2*seq[-1] if 900000000<=freq[0]<=1000000000 else 1805.1+0.2*(seq[0]-512)
# چون در محاسبات نهایی 0.2 کم می آید دستی برای رفع مشکل آن را اضافه کردیم
dl_band_from = 934.9+0.2*seq[0] if 900000000<=freq[0]<=1000000000 else 1805.1+0.2*(seq[0]-512)
dl_band_to = 0.2+934.9+0.2*seq[-1] if 900000000<=freq[0]<=1000000000 else 0.2+1805.1+0.2*(seq[0]-512)
output_data.append({
'City': city,
'Date': date,
'MNC': mnc,
'Tech': tech,
'Ch_From': seq[0],
# 'until': 'تا',
'Ch_To': seq[-1],
'dl_band_from': dl_band_from,
'dl_band_to' : dl_band_to,
'up_band_from' : dl_band_from - 45,
'up_band_to': dl_band_to-45,
'Center F(MHZ)' : round((dl_band_from+dl_band_to)/2,1),
'Used Frequency' : dl_band_from if dl_band_to - dl_band_from==0 else dl_band_to - dl_band_from
})
seq = [arfcns[i]]
return output_data
except Exception as E:
error_handle(str(E))
input_file_path = 'GSM.xlsx'
output_file_path = 'gsm_out.xlsx'
df = read_excel_file(input_file_path)
try:
if df is not None:
output_data = analyze_gsm_data(df)
output_data = pd.DataFrame(output_data)
write_to_excel(output_data, output_file_path)
except Exception as E:
error_handle(str(E))
*****************************************************************************************
*****************************************************************************************
******** ********
******** Third Step ********
******** Analyze UMTS ********
******** ********
*****************************************************************************************
*****************************************************************************************
def analyze_umts_data(df):
try:
new_df = pd.DataFrame()
new_df['City'] = df['City']
new_df['Date'] = df['Date']
new_df['MNC'] = df['MNC']
new_df['Tech'] = df['Tech']
new_df['Ch_From'] = df['UARFCN']
# new_df['until'] = 'تا'
new_df['Ch_To'] = ""
new_df['dl_band_from'] =""
new_df['dl_band_to'] = ""
new_df['up_band_from'] = ""
new_df['up_band_to'] = ""
new_df['Center F(MHZ)'] = ""
new_df['Used Frequency'] = 4.2
for index, row in df.iterrows():
try:
if 900000000<=row['Frequency']<1000000000:
new_df.loc[index, 'Center F(MHZ)'] = 927.4+(0.2*(float(new_df.loc[index, 'Ch_From'])-2937))
new_df.loc[index, 'dl_band_from'] = new_df.loc[index, 'Center F(MHZ)'] - (new_df.loc[index, 'Used Frequency']/2)
new_df.loc[index, 'dl_band_to'] = new_df.loc[index, 'Center F(MHZ)'] + (new_df.loc[index, 'Used Frequency']/2)
new_df.loc[index, 'up_band_from'] = new_df.loc[index, 'dl_band_from']-45
new_df.loc[index, 'up_band_to'] = new_df.loc[index, 'dl_band_to']-45
else:
new_df.loc[index, 'Center F(MHZ)'] = 2112.4+(0.2*(float(new_df.loc[index, 'Ch_From'])-10562))
new_df.loc[index, 'dl_band_from'] = new_df.loc[index, 'Center F(MHZ)'] - (new_df.loc[index, 'Used Frequency']/2)
new_df.loc[index, 'dl_band_to'] = new_df.loc[index, 'Center F(MHZ)'] + (new_df.loc[index, 'Used Frequency']/2)
new_df.loc[index, 'up_band_from'] = new_df.loc[index, 'dl_band_from']-190
new_df.loc[index, 'up_band_to'] = new_df.loc[index, 'dl_band_to']-190
except Exception as E:
error_handle(str(E))
return new_df
except Exception as E:
error_handle(str(E))
input_file_path = 'UMTS.xlsx'
output_file_path = 'umts_out.xlsx'
df = read_excel_file(input_file_path)
try:
if df is not None:
output_data = analyze_umts_data(df)
output_data = pd.DataFrame(output_data)
write_to_excel(output_data, output_file_path)
except Exception as E:
error_handle(str(E))
*****************************************************************************************
*****************************************************************************************
******** ********
******** forth Step ********
******** Analyze LTE ********
******** ********
*****************************************************************************************
*****************************************************************************************
def analyze_lte_data(df:pd.DataFrame):
try:
city_column = 'City'
earfcn_column = 'EARFCN'
for index, row in df.iterrows():
city = row[city_column]
earfcn = str(row[earfcn_column])
for root, dirs, files in os.walk(data_dir):
for file in files:
if city in file.split('_'):
with open(root+'\\'+file,'r', encoding='utf-8') as f:
lines = f.readlines()
pattern_earfcn_band = r"EARFCN@Band:\s*(\d+)@(\d+)"
pattern_dl_bandwidth = r"dl_Bandwidth\[MHz\]\s*\((\d+)\)\s*(\d+)"
for i in range(0, len(lines), 2):
if i + 1 < len(lines):
line1 = lines[i].strip()
line2 = lines[i + 1].strip()
match_earfcn_band = re.search(pattern_earfcn_band, line1)
if match_earfcn_band:
match_earfcn = match_earfcn_band.group(1)
match_band = match_earfcn_band.group(2)
match_dl_bandwidth = re.search(pattern_dl_bandwidth, line2)
if match_dl_bandwidth and match_earfcn==earfcn:
match_dl_bandwidth = match_dl_bandwidth.group(2)
df.loc[index, 'Used Frequency'] = int(match_dl_bandwidth)
df.loc[index, 'Ch_From'] = int(earfcn)
new_df = pd.DataFrame()
new_df['City'] = df['City']
new_df['Date'] = df['Date']
new_df['MNC'] = df['MNC']
new_df['Tech'] = df['Tech']
new_df['Ch_From'] = df['Ch_From']
# new_df['until'] = 'تا'
new_df['Ch_To'] = None
new_df['dl_band_from'] = None
new_df['dl_band_to'] = None
new_df['up_band_from'] = None
new_df['up_band_to'] = None
new_df['Center F(MHZ)'] = None
new_df['Used Frequency'] = df['Used Frequency']
for index, row in df.iterrows():
try:
if new_df.loc[index, 'Used Frequency']:
if 790000000<=row['Frequency']<880000000:
new_df.loc[index, 'Center F(MHZ)'] = 791+(0.1*(float(new_df.loc[index, 'Ch_From'])-6150))
elif 900000000<=row['Frequency']<950000000:
new_df.loc[index, 'Center F(MHZ)'] = 925+(0.1*(float(new_df.loc[index, 'Ch_From'])-3450))
elif 1800000000<=row['Frequency']<1900000000:
new_df.loc[index, 'Center F(MHZ)'] = 1805+(0.1*(float(new_df.loc[index, 'Ch_From'])-1200))
elif 2100000000<=row['Frequency']<2200000000:
new_df.loc[index, 'Center F(MHZ)'] = 2110+(0.1*(float(new_df.loc[index, 'Ch_From'])))
elif 2300000000<=row['Frequency']<2390000000:
new_df.loc[index, 'Center F(MHZ)'] = 2300+(0.1*(float(new_df.loc[index, 'Ch_From'])-38650))
elif 2590000000<=row['Frequency']<2610000000:
new_df.loc[index, 'Center F(MHZ)'] = 2570+(0.1*(float(new_df.loc[index, 'Ch_From'])-37750))
elif 2620000000<=row['Frequency']<2700000000:
new_df.loc[index, 'Center F(MHZ)'] = 2620+(0.1*(float(new_df.loc[index, 'Ch_From'])-2750))
elif 3300000000<=row['Frequency']<3600000000:
new_df.loc[index, 'Center F(MHZ)'] = 3400+(0.1*(float(new_df.loc[index, 'Ch_From'])-41590))
else:
new_df.loc[index, 'Center F(MHZ)'] = None
else:
new_df.loc[index, 'Center F(MHZ)'] = None
except Exception as E:
new_df.loc[index, 'Center F(MHZ)'] = None
# error_handle(str(E))
for index, row in new_df.iterrows():
try:
if df.loc[index, 'Used Frequency']:
new_df.loc[index, 'dl_band_from'] = new_df.loc[index, 'Center F(MHZ)'] - (new_df.loc[index, 'Used Frequency']/2)
new_df.loc[index, 'dl_band_to'] = new_df.loc[index, 'Center F(MHZ)'] + (new_df.loc[index, 'Used Frequency']/2)
if 790<new_df.loc[index, 'dl_band_from']<850:
new_df.loc[index, 'up_band_from'] = new_df.loc[index, 'dl_band_from']+41
new_df.loc[index, 'up_band_to'] = new_df.loc[index, 'dl_band_to']+41
elif 900<new_df.loc[index, 'dl_band_from']<950:
new_df.loc[index, 'up_band_from'] = new_df.loc[index, 'dl_band_from']-45
new_df.loc[index, 'up_band_to'] = new_df.loc[index, 'dl_band_to']-45
elif 1800<new_df.loc[index, 'dl_band_from']<1860:
new_df.loc[index, 'up_band_from'] = new_df.loc[index, 'dl_band_from']-95
new_df.loc[index, 'up_band_to'] = new_df.loc[index, 'dl_band_to']-95
elif 2100<new_df.loc[index, 'dl_band_from']<2150:
new_df.loc[index, 'up_band_from'] = new_df.loc[index, 'dl_band_from']-190
new_df.loc[index, 'up_band_to'] = new_df.loc[index, 'dl_band_to']-190
elif 2300<new_df.loc[index, 'dl_band_from']<2360:
new_df.loc[index, 'up_band_from'] = '-'
new_df.loc[index, 'up_band_to'] = '-'
elif 2620<new_df.loc[index, 'dl_band_from']<2670:
new_df.loc[index, 'up_band_from'] = new_df.loc[index, 'dl_band_from']-120
new_df.loc[index, 'up_band_to'] = new_df.loc[index, 'dl_band_to']-120
elif 2590<new_df.loc[index, 'dl_band_from']<2610:
new_df.loc[index, 'up_band_from'] = '-'
new_df.loc[index, 'up_band_to'] = '-'
elif 3500<new_df.loc[index, 'dl_band_from']<3600:
new_df.loc[index, 'up_band_from'] = '-'
new_df.loc[index, 'up_band_to'] = '-'
else:
new_df.loc[index, 'dl_band_from'] = None
new_df.loc[index, 'dl_band_to'] = None
new_df.loc[index, 'up_band_from'] = None
new_df.loc[index, 'up_band_to'] = None
except Exception as E:
new_df.loc[index, 'dl_band_from'] = None
new_df.loc[index, 'dl_band_to'] = None
new_df.loc[index, 'up_band_from'] = None
new_df.loc[index, 'up_band_to'] = None
# error_handle(str(E))
return new_df
except Exception as E:
error_handle(str(E))
input_file_path = 'LTE.xlsx'
output_file_path = 'lte_out.xlsx'
df = read_excel_file(input_file_path)
try:
if df is not None:
output_data = analyze_lte_data(df)
write_to_excel(output_data, output_file_path)
except Exception as E:
error_handle(str(E))
*****************************************************************************************
*****************************************************************************************
******** ********
******** Last Step ********
******** Merge all excel files and create Result.xlsx. ********
******** Create archive CSV files and delete unnecessary files. ********
******** ********
*****************************************************************************************
*****************************************************************************************
file1 = 'gsm_out.xlsx'
file2 = 'umts_out.xlsx'
file3 = 'lte_out.xlsx'
output_file = 'result.xlsx'
df1 = pd.read_excel(file1)
df2 = pd.read_excel(file2)
df3 = pd.read_excel(file3)
merged_df = pd.concat([df1, df2, df3], ignore_index=True)
merged_df = merged_df[~merged_df['MNC'].isin([0, ' ', '', None])]
merged_df = merged_df[
~( # Negation to select the opposite of the conditions below
merged_df['MNC'].isnull() | # Catch NaN, None
(merged_df['MNC'].astype(str).str.strip() == '') | # Empty strings after stripping whitespace
(merged_df['MNC'] == 0) # Exact zero match for numeric types
)
]
merged_df = merged_df[
~( # Negation to select the opposite of the conditions below
merged_df['Used Frequency'].isnull() | # Catch NaN, None
(merged_df['Used Frequency'].astype(str).str.strip() == '') | # Empty strings after stripping whitespace
(merged_df['Used Frequency'] == 0) # Exact zero match for numeric types
)
]
merged_df = merged_df[
~( # Negation to select the opposite of the conditions below
merged_df['dl_band_from'].isnull() | # Catch NaN, None
(merged_df['dl_band_from'].astype(str).str.strip() == '') | # Empty strings after stripping whitespace
(merged_df['dl_band_from'] == 0) # Exact zero match for numeric types
)
]
sort_columns = ['MNC', 'dl_band_from', 'City']
merged_df = merged_df.sort_values(by=sort_columns, ascending=True)
merged_df['Result'] = ""
merged_df.to_excel(output_file, index=False)
print("Compression started.\nArchive will be saved as CSV.zip")
with zipfile.ZipFile('CSV.zip', 'w', zipfile.ZIP_DEFLATED) as zip_file:
for root, dirs, files in os.walk(csv_dir):
for file in files:
file_path = os.path.join(root, file)
relative_path = os.path.relpath(file_path, start=os.path.dirname(csv_dir))
zip_file.write(file_path, relative_path)
print(f"Added {relative_path} to the archive.")
print(f"Compression complete. Archive saved as '{csv_dir}'")
print("Deleting temporary files.")
os.system('cmd /c "del /q GSM.xlsx LTE.xlsx UMTS.xlsx lte_out.xlsx gsm_out.xlsx umts_out.xlsx"')
os.system('cmd /c "rmdir /s /q GSM"')
os.system('cmd /c "rmdir /s /q LTE"')
os.system('cmd /c "rmdir /s /q UMTS"')
os.system('cmd /c "rmdir /s /q CSV"')
os.system('cmd /c "rmdir /s /q Data"')
print(f'Result file saved as {output_file}')