Untitled

mail@pastecode.io avatar
unknown
plain_text
a month ago
7.3 kB
1
Indexable
Never
from flask import Flask, render_template, request, send_file
import pandas as pd
import os

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/process_files', methods=['POST'])
def process_files():
    # Extract form data
    utility = request.form['utility']
    sheet1_file = request.files['sheet1_file']
    sheet2_file = request.files['sheet2_file']
    column1_name = request.form['column1_name']
    column2_name = request.form['column2_name']

    if utility == 'utility1':
        # Your logic for Utility 1
        df_sheet1 = pd.read_excel(sheet1_file)
        df_sheet2 = pd.read_excel(sheet2_file)
        
        # If "Concated" column doesn't exist in the second sheet, create it
        if 'Concated' not in df_sheet2.columns:
            # Concatenate specified columns and create "Concated" column
            df_sheet2['Concated'] = df_sheet2[column1_name] + '|' + df_sheet2[column2_name]

        # Extract Concated filters from "Concated" column of Sheet2
        concated_filters = df_sheet2['Concated'].tolist()

        # Create an empty dataframe to store the results
        result_df = pd.DataFrame(columns=['Column1', 'Column2', 'Concated', 'Features'])

        # Iterate through Concated filters
        for concated_filter in concated_filters:
            # Clean the Concated filter to remove non-printable characters
            cleaned_filter = ''.join(char for char in concated_filter if char.isprintable())

            # Split the cleaned Concated filter
            column1, column2 = cleaned_filter.split('|')

            # Filter based on Column1 and Column2 in the first sheet
            filter_condition = (df_sheet1['Requirement(s)'].str.contains(column1)) & (df_sheet1['Specification(s)'].str.contains(column2))
            filtered_df = df_sheet1[filter_condition].copy()

            # Get unique features for the Concated value
            features = ', '.join(filtered_df['Software Features'].unique())

            # Your Utility 1 logic here...
            # Sample logic (replace this with your actual logic)
            result_df = pd.DataFrame({
                'Column1': [column1],
                'Column2': [column2],
                'Concated': [concated_filter],
                'Features': [features]
            })

        # Save result to Excel
        result_df.to_excel('output.xlsx', index=False)

        # Return the result file
        return send_file('output.xlsx', as_attachment=True)

    elif utility == 'utility2':
        # Your logic for Utility 2
        directory = 'Output/'  # Change this to your desired directory
        os.makedirs(directory, exist_ok=True)  # Create the directory if it doesn't exist

        # Assuming sheet2_file is a directory, iterate through files in the directory
        for WorkingFile in os.listdir(sheet2_file):
            df = pd.read_excel(os.path.join(sheet2_file, WorkingFile))

            print("")
            print("########################################################")
            print("DataFrame Successfully Imported From File: ", WorkingFile)

            array_with_ID = df[df.columns[0]].to_numpy()
            array_with_values = df[[df.columns[1]]].to_numpy().tolist()

            dictionary = {}
            for i in range(0, len(array_with_ID)):
                if array_with_ID[i] not in dictionary:
                    temp_array = []
                    temp_array.append(array_with_values[i])
                    dictionary[array_with_ID[i]] = temp_array
                else:
                    previous_arr = []
                    previous_arr = (dictionary[array_with_ID[i]])
                    previous_arr.append(array_with_values[i])
                    dictionary[array_with_ID[i]] = (previous_arr)

            print("")
            print("########################################################")
            print("Grouping of the Values - Successfully Completed")

            def func1(input_list):
                resultList = [element for nestedlist in input_list for element in nestedlist]

                Final_array_SRD = []
                for i in resultList:
                    if type(i) == int:
                        Final_array_SRD.append([i])
                        continue
                    if type(i) != float:
                        list_of_integers = [int(item) if item.isdigit() else item for item in i.split(',')]
                        Final_array_SRD.append(list_of_integers)

                resultList2 = [element for nestedlist in Final_array_SRD for element in nestedlist]
                res = (list(set(resultList2)))
                return res

            new_dictionary_Solution = {}
            for key, value in dictionary.items():
                temp_res = func1(value)
                new_dictionary_Solution[key] = temp_res

            print("")
            print("########################################################")
            print("Removing Empty Strings from the data - Successfully Completed")

            def funcToRemoveEmptyString(input_List1):
                result1 = []
                for i in input_List1:
                    if type(i) == int:
                        i = str(i)
                        if i not in result1:
                            result1.append(i.strip())
                    elif i != "" and i != " ":
                        if i not in result1:
                            result1.append(i.strip())
                return result1

            new_dictionary_Solution_processed = {}
            for key, value in new_dictionary_Solution.items():
                temp_res = funcToRemoveEmptyString(value)
                new_dictionary_Solution_processed[key] = temp_res

            print("")
            print("########################################################")
            print("Removing Duplicate Values from the data - Successfully Completed")

            def removeDupes(inputlist11):
                res = []
                for i in inputlist11:
                    if i not in res:
                        res.append(i)
                return res

            dictionary_final_Sol_dupes_Removed = {}
            for key, value in new_dictionary_Solution_processed.items():
                temp_result1 = removeDupes(value)
                dictionary_final_Sol_dupes_Removed[key] = temp_result1

            print("")
            print("########################################################")
            print("Excel file Successfully created in the Output Folder with the name : ",
                  "OutputFor" + str(WorkingFile))

            df_final = pd.DataFrame(dictionary_final_Sol_dupes_Removed.items(), columns=['Column01', 'Column02'])
            output_filename = os.path.join(directory, "OutputFor" + str(WorkingFile))
            df_final.to_excel(output_filename, sheet_name='FinalWorkBook', index=False)

        # Return the result file
        return send_file(output_filename, as_attachment=True)

if __name__ == '__main__':
    app.run(debug=True)
Leave a Comment