import pandas as pd import gradio as gr from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.metrics.pairwise import cosine_similarity from openpyxl import load_workbook from IPython.display import Markdown import os # Initialize empty DataFrame and TF-IDF matrix data = pd.DataFrame() tfidf_vectorizer = None tfidf_matrix = None # Helper: Load Data from File (Excel or CSV) def load_file(file): global data, tfidf_vectorizer, tfidf_matrix try: # Read file based on its extension if file.endswith(".xlsx"): # Read Excel file workbook = load_workbook(filename=file, data_only=True) sheet = workbook.active headers = [cell.value if cell.value is not None else f"Unnamed Column {i}" for i, cell in enumerate(sheet[1])] rows = sheet.iter_rows(min_row=2, values_only=True) data = pd.DataFrame(rows, columns=headers) # Extract hyperlinks from "Information" column if present if "Information" in data.columns: for i, row in enumerate(sheet.iter_rows(min_row=2)): cell = row[data.columns.get_loc("Information")] if cell.hyperlink: data.at[i, "Information"] = cell.hyperlink.target elif file.endswith(".csv"): # Read CSV file data = pd.read_csv(file) else: return "Unsupported file format. Please upload a .xlsx or .csv file." # Initialize TF-IDF for employee search tfidf_vectorizer = TfidfVectorizer(analyzer="char_wb", ngram_range=(2, 4)) tfidf_matrix = tfidf_vectorizer.fit_transform(data["Employee Name"].astype(str)) return "File loaded successfully!" except Exception as e: return f"Error loading file: {e}" # Helper: Generate Report Dynamically import os def generate_dynamic_report(query): if data.empty or tfidf_vectorizer is None: return None query_vec = tfidf_vectorizer.transform([query]) similarities = cosine_similarity(query_vec, tfidf_matrix).flatten() best_match_idx = similarities.argmax() if similarities[best_match_idx] > 0: employee = data.iloc[best_match_idx] employee_name = employee["Employee Name"] report_file = f"{employee_name.replace(' ', '_')}_report.html" # Generate HTML content dynamically with open(report_file, "w") as file: file.write(f"{employee_name} Report") file.write(f"

Employee Report for {employee_name}

") file.write("
") # Employee Details file.write("

Employee Details:

") # Customer Insights file.write("

Customer Insights:

") # Summary file.write("

Summary:

") file.write(f"

{employee_name} has shown notable contributions in the domain. Refer to the linked documents for more details.

") file.write("

Thank you for using our Employee Dashboard!

") file.write("") return report_file else: return None # Helper: Search Employee def search_employee(query): if data.empty or tfidf_vectorizer is None: return pd.DataFrame([{"Error": "No data available. Please upload a file first."}]) query_vec = tfidf_vectorizer.transform([query]) similarities = cosine_similarity(query_vec, tfidf_matrix).flatten() best_match_idx = similarities.argmax() if similarities[best_match_idx] > 0: # Ensure output is a valid DataFrame with one row employee = data.iloc[best_match_idx].to_frame().T # Convert Series to DataFrame return employee else: return pd.DataFrame([{"Error": "No matching employee found."}]) # Gradio Interface with gr.Blocks() as interface: gr.Markdown("""

Employee Dashboard

Upload your Excel or CSV file to get started. Search employees, view metrics, and generate dynamic reports.

""") with gr.Row(): file_upload = gr.File(label="Upload Excel or CSV File", type="filepath") upload_status = gr.Textbox(label="Upload Status", interactive=False) upload_button = gr.Button("Upload") upload_button.click(load_file, inputs=[file_upload], outputs=[upload_status]) with gr.Row(): search_query = gr.Textbox(label="Search Employee", placeholder="Type partial name (e.g., 'Aar')") employee_details = gr.Dataframe(label="Employee Details", interactive=True) report_output = gr.File(label="Download Report") search_button = gr.Button("Search") search_button.click( search_employee, inputs=[search_query], outputs=[employee_details], ) search_button.click( generate_dynamic_report, inputs=[search_query], outputs=[report_output], ) if __name__ == "__main__": interface.launch(share=True)