CoolFace
Apppublic

yukaztn/Software_Defect_Prediction

sourceHugging Faceupdated 2y agoView on Hugging Face
0likes
app.py126 linesDownload Raw Back to root
1# -*- coding: utf-8 -*-2"""SBFapp.ipynb3 4Automatically generated by Colab.5 6Original file is located at7    https://colab.research.google.com/drive/1UrBunqn26Zk3G3F--EjGCGZyZqHBsCWI8"""9 10import gradio as gr11import pandas as pd12from jpmml_evaluator import make_evaluator13 14# Map dataset names to corresponding PMML model paths15dataset_models = {16    "CM1": "/content/CM1-SBF.pmml",17    "JM1": "/content/JM1-SBF.pmml",18    "KC1": "/content/KC1-SBF.pmml",19    "KC3": "/content/KC3-SBF.pmml",20    "MC1": "/content/MC1-SBF.pmml",21    "MC2": "/content/MC2-SBF.pmml",22    "PC1": "/content/PC1-SBF.pmml",23    "PC3": "/content/PC3-SBF.pmml",24    "PC4": "/content/PC4-SBF.pmml",25    "PC5": "/content/PC5-SBF.pmml",26}27 28# Preload models and their input fields29model_evaluators = {}30model_input_fields = {}31 32for dataset, model_path in dataset_models.items():33    evaluator = make_evaluator(model_path).verify()34    input_fields = [field.getName() for field in evaluator.getInputFields()]35    model_evaluators[dataset] = evaluator36    model_input_fields[dataset] = input_fields37 38# Generate a template Excel file with all possible fields39all_fields = set()40for fields in model_input_fields.values():41    all_fields.update(fields)42 43template_path = "/content/template.xlsx"44template_df = pd.DataFrame(columns=sorted(all_fields))45template_df.to_excel(template_path, index=False)46 47# Helper function to find the best-matching model48def find_matching_model(user_inputs):49    for dataset, input_fields in model_input_fields.items():50        if all(field in user_inputs for field in input_fields):51            return dataset, model_evaluators[dataset], input_fields52    raise ValueError("No matching model found for the provided inputs.")53 54# Helper function to normalize inputs55def normalize_inputs(data):56    for column in data.columns:57        try:58            # Normalize values to floats or integers59            data[column] = data[column].apply(60                lambda x: float(str(x).replace(" ", "").strip()) if pd.notnull(x) else None61            )62        except Exception as e:63            raise ValueError(f"Invalid format in column {column}: {e}")64    return data65 66# Prediction function67def predict_from_excel(file):68    try:69        # Load uploaded Excel file70        user_data = pd.read_excel(file.name)71 72        # Normalize input data73        normalized_data = normalize_inputs(user_data)74 75        # Find the best-matching model76        dataset, evaluator, input_fields = find_matching_model(normalized_data.columns)77 78        # Keep only required fields for prediction79        prediction_data = normalized_data[input_fields]80 81        # Evaluate using the selected PMML model82        results = evaluator.evaluateAll(prediction_data)83 84        # Add predictions to the original data85        normalized_data["prediction(Defective)"] = results["prediction(Defective)"]86        normalized_data["Prediction Label"] = normalized_data["prediction(Defective)"].apply(87            lambda x: "Bug-Prone" if x == "Y" else "Not Bug-Prone"88        )89 90        # Save the results to a new Excel file91        result_path = "/content/prediction_results.xlsx"92        normalized_data.to_excel(result_path, index=False)93 94        return "Prediction completed successfully. Download the results below.", result_path95 96    except Exception as e:97        return f"An error occurred: {str(e)}", None98 99# Gradio Interface100title = "Software Defect Prediction using SBF-C4.5"101description = f"""102Upload an Excel file containing software metrics to predict whether the software is Bug-Prone or Not Bug-Prone.103The system automatically matches your input fields to the correct prediction model.104 105### Download Template106[Download Template Excel File](https://docs.google.com/spreadsheets/d/1MT4Koi0QJ9_VSY2FJrDpmDemvRgQ1gST/edit?usp=sharing&ouid=103829640616315810037&rtpof=true&sd=true)107"""108 109# Define the interface110interface = gr.Interface(111    fn=predict_from_excel,112    inputs=[113        gr.File(label="Upload Dataset (Excel file, .xlsx format)"),114    ],115    outputs=[116        gr.Textbox(label="Prediction Status"),117        gr.File(label="Download Results (Excel file)"),118    ],119    title=title,120    description=description,121    flagging_mode="never",  # Updated to avoid the deprecation warning122)123 124 125# Launch the interface126interface.launch(share=True)