import os import pandas as pd import numpy as np import matplotlib.pyplot as plt import gradio as gr import requests # Groq API Setup API_KEY = "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" API_URL = "https://api.groq.com/openai/v1/chat/completions" # Updated API URL def analyze_file(uploaded_file): try: # Load the file into a pandas DataFrame if uploaded_file.name.endswith('.csv'): df = pd.read_csv(uploaded_file.name) elif uploaded_file.name.endswith('.xlsx'): df = pd.read_excel(uploaded_file.name) else: return "Error: The uploaded file is neither CSV nor Excel." # Clean up the column names by stripping any leading/trailing spaces df.columns = df.columns.str.strip() # Display the column names and first few rows for debugging print("Columns in the uploaded file:", df.columns) print("Preview of the uploaded data:", df.head()) # Display column names and preview in the Gradio UI for debugging st.write(df.columns) st.write(df.head()) # Check if required columns are present if 'Gain (dB)' in df.columns and 'Frequency (GHz)' in df.columns: # Perform basic data analysis mean_gain = df['Gain (dB)'].mean() median_gain = df['Gain (dB)'].median() std_dev_gain = df['Gain (dB)'].std() # Display analysis results print(f"Mean Gain: {mean_gain}") print(f"Median Gain: {median_gain}") print(f"Standard Deviation of Gain: {std_dev_gain}") # Plotting the data fig, ax = plt.subplots() ax.plot(df['Frequency (GHz)'], df['Gain (dB)'], label='Gain (dB)', color='blue') ax.set_xlabel('Frequency (GHz)') ax.set_ylabel('Gain (dB)') ax.set_title('Gain vs Frequency') ax.legend() plt.close(fig) # Close to avoid inline display # Send summary to Groq API for analysis data_summary = f""" The dataset contains simulation results for antennas. The frequency range is from 1 GHz to 10 GHz. - The antenna's gain increases from 5 dB to 30 dB as frequency increases. - Efficiency is consistently above 90%, with the highest reaching 99%. """ headers = { "Authorization": f"Bearer {API_KEY}", "Content-Type": "application/json" } payload = { "messages": [{"role": "user", "content": data_summary}], "model": "llama-3.3-70b-versatile" # Ensure this model is supported by Groq } # Send the request to Groq API response = requests.post(API_URL, json=payload, headers=headers) if response.status_code == 200: groq_analysis = response.json()["choices"][0]["message"]["content"] else: groq_analysis = f"Error: {response.status_code}, {response.text}" return mean_gain, median_gain, std_dev_gain, fig, groq_analysis else: return "Error: Required columns 'Gain (dB)' or 'Frequency (GHz)' not found in the dataset." except Exception as e: # Return error message if something goes wrong return f"An error occurred: {str(e)}" # Create the Gradio interface using the new Gradio 3.x syntax iface = gr.Interface( fn=analyze_file, inputs=gr.File(label="Upload CSV or Excel File"), # Corrected to use `gr.File` outputs=[ gr.Textbox(label="Mean Gain"), gr.Textbox(label="Median Gain"), gr.Textbox(label="Standard Deviation of Gain"), gr.Image(label="Plot"), gr.Textbox(label="Groq's Analysis") ], title="Data Analysis and Visualization with Groq API", description="Upload a CSV or Excel file to analyze the antenna data and get insights." ) # Launch the interface iface.launch()