File size: 4,011 Bytes
2d2a8d4
 
 
 
65b42b1
d48f72d
2d2a8d4
d48f72d
 
bf4b27d
f900b38
c74f6d6
49ac35b
 
 
 
 
 
 
 
 
bf4b27d
 
 
49ac35b
 
 
bf4b27d
 
 
49ac35b
 
 
 
 
 
 
bf4b27d
49ac35b
 
 
 
 
 
 
 
 
 
 
 
 
2d2a8d4
49ac35b
 
 
 
 
 
bf4b27d
49ac35b
 
 
 
2d2a8d4
49ac35b
 
 
 
2d2a8d4
49ac35b
bf4b27d
49ac35b
 
 
 
 
 
d48f72d
49ac35b
 
 
 
 
c74f6d6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
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()