alexacido commited on
Commit
2a2b26f
verified
1 Parent(s): c1cefb8

Upload 4 files

Browse files
Files changed (3) hide show
  1. README.md +15 -6
  2. app.py +102 -89
  3. requirements.txt +5 -4
README.md CHANGED
@@ -1,12 +1,21 @@
1
  ---
2
- title: Data Analytics WithAI
3
- emoji: 馃搲
4
- colorFrom: yellow
5
- colorTo: gray
6
  sdk: streamlit
7
- sdk_version: 1.42.0
8
  app_file: app.py
9
  pinned: false
10
  ---
11
 
12
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: AI CSV Data Analyst
3
+ emoji: 馃搳
4
+ colorFrom: indigo
5
+ colorTo: blue
6
  sdk: streamlit
7
+ sdk_version: "1.35.0"
8
  app_file: app.py
9
  pinned: false
10
  ---
11
 
12
+ # 馃搳 AI CSV Data Analyst
13
+
14
+ Esta aplicaci贸n permite subir archivos `.csv` o `.xlsx` y hacer an谩lisis estad铆sticos, visualizaciones y preguntas impulsadas por la API de Gemini (Google Generative AI).
15
+
16
+ ## 馃殌 Caracter铆sticas
17
+
18
+ - Visualizaci贸n autom谩tica de datos
19
+ - Estad铆sticas solo si hay columnas num茅ricas
20
+ - Interacci贸n con IA usando Gemini
21
+ - Compatible con Hugging Face Spaces
app.py CHANGED
@@ -1,89 +1,102 @@
1
- import streamlit as st
2
- import pandas as pd
3
- import google.generativeai as genai
4
- import matplotlib.pyplot as plt
5
- import seaborn as sns
6
- import plotly.express as px
7
-
8
- # Set up page layout
9
- st.set_page_config(page_title="AI CSV Data Analyst", layout="wide")
10
-
11
- # Initialize Gemini API (Replace with your API Key)
12
- GEMINI_API_KEY = "AIzaSyDt0TM6beHrE-f5bvfYXQa6iDACSCfU7go"
13
- genai.configure(api_key=GEMINI_API_KEY)
14
-
15
- # Create two columns (70:30 split)
16
- left_col, right_col = st.columns([7, 3])
17
-
18
- with left_col:
19
- st.title("馃搳 AI-Powered CSV Data Analyst")
20
-
21
- # File Upload
22
- uploaded_file = st.file_uploader("Upload a CSV or Excel file", type=["csv", "xlsx"])
23
-
24
- if uploaded_file is not None:
25
- # Read File
26
- file_ext = uploaded_file.name.split(".")[-1]
27
- if file_ext == "csv":
28
- df = pd.read_csv(uploaded_file)
29
- elif file_ext == "xlsx":
30
- df = pd.read_excel(uploaded_file, engine="openpyxl")
31
-
32
- # Display the DataFrame
33
- st.subheader("馃搨 Uploaded Data")
34
- st.dataframe(df)
35
-
36
- # Data Insights
37
- st.subheader("馃搱 Data Insights")
38
-
39
- # Dataset Summary
40
- st.write(f"**Rows:** {df.shape[0]}, **Columns:** {df.shape[1]}")
41
- st.write(f"**Missing Values:**\n{df.isnull().sum()}")
42
-
43
- # Basic Statistics
44
- st.subheader("馃搳 Statistical Summary")
45
- st.write(df.describe())
46
-
47
- # Visualizations
48
- st.subheader("馃搲 Data Visualizations")
49
-
50
- # Select Column for Histogram
51
- numeric_columns = df.select_dtypes(include=["number"]).columns
52
- if len(numeric_columns) > 0:
53
- col = st.selectbox("Select a column for histogram:", numeric_columns)
54
- fig = px.histogram(df, x=col, title=f"Histogram of {col}")
55
- st.plotly_chart(fig)
56
-
57
- # Correlation Heatmap
58
- if len(numeric_columns) > 1:
59
- st.subheader("馃攳 Correlation Heatmap")
60
- fig, ax = plt.subplots(figsize=(6, 4))
61
- sns.heatmap(df[numeric_columns].corr(), annot=True, cmap="coolwarm", ax=ax)
62
- st.pyplot(fig)
63
-
64
- with right_col:
65
- st.subheader("馃挰 Chat with Your Data")
66
-
67
- user_query = st.text_input("Ask a question about the data...")
68
-
69
- if user_query and uploaded_file is not None:
70
- # Prepare prompt for AI
71
- prompt = f"""
72
- You are a data analyst. The user has uploaded a dataset.
73
- Answer the query based on the dataset provided.
74
-
75
- Dataset Overview:
76
- {df.describe().to_string()}
77
-
78
- User Question:
79
- {user_query}
80
- """
81
-
82
- # Get AI response
83
- model = genai.GenerativeModel("gemini-pro")
84
- response = model.generate_content(prompt)
85
-
86
- # Display AI Response
87
- if response.text:
88
- st.write("馃 AI Response:")
89
- st.write(response.text)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import pandas as pd
3
+ import google.generativeai as genai
4
+ import matplotlib.pyplot as plt
5
+ import seaborn as sns
6
+ import plotly.express as px
7
+
8
+ # Set up page layout
9
+ st.set_page_config(page_title="AI CSV Data Analyst", layout="wide")
10
+
11
+ # Initialize Gemini API (Replace with your API Key)
12
+ import os
13
+ GEMINI_API_KEY = "AIzaSyDt0TM6beHrE-f5bvfYXQa6iDACSCfU7go"
14
+ genai.configure(api_key=GEMINI_API_KEY)
15
+
16
+ # Create two columns (70:30 split)
17
+ left_col, right_col = st.columns([7, 3])
18
+
19
+ with left_col:
20
+ st.title("馃搳 AI-Powered CSV Data Analyst")
21
+
22
+ # File Upload
23
+ uploaded_file = st.file_uploader("Upload a CSV or Excel file", type=["csv", "xlsx"])
24
+
25
+ if uploaded_file is not None:
26
+ # Read File
27
+ file_ext = uploaded_file.name.split(".")[-1]
28
+ if file_ext == "csv":
29
+ df = pd.read_csv(uploaded_file, dtype=str)
30
+ elif file_ext == "xlsx":
31
+ df = pd.read_excel(uploaded_file, engine="openpyxl", dtype=str)
32
+
33
+ import numpy as np
34
+ # Display the DataFrame
35
+ st.subheader("馃搨 Uploaded Data")
36
+ st.dataframe(df)
37
+
38
+ # Data Insights
39
+ st.subheader("馃搱 Data Insights")
40
+
41
+ # Dataset Summary
42
+ st.write(f"**Rows:** {df.shape[0]}, **Columns:** {df.shape[1]}")
43
+ st.write(f"**Missing Values:**")
44
+ st.write(df.isnull().sum())
45
+
46
+ # Basic Statistics
47
+ st.subheader("馃搳 Statistical Summary")
48
+ numeric_df = df.apply(pd.to_numeric, errors='coerce')
49
+ if numeric_df.select_dtypes(include=['number']).shape[1] > 0:
50
+ st.write(numeric_df.describe())
51
+ else:
52
+ st.info("No hay columnas num茅ricas para mostrar estad铆sticas.")
53
+
54
+ # Visualizations
55
+ st.subheader("馃搲 Data Visualizations")
56
+
57
+ # Select Column for Histogram
58
+ numeric_columns = df.select_dtypes(include=["number"]).columns
59
+ if len(numeric_columns) > 0:
60
+ col = st.selectbox("Select a column for histogram:", numeric_columns)
61
+ fig = px.histogram(df, x=col, title=f"Histogram of {col}")
62
+ st.plotly_chart(fig)
63
+
64
+ # Correlation Heatmap
65
+ if len(numeric_columns) > 1:
66
+ st.subheader("馃攳 Correlation Heatmap")
67
+ fig, ax = plt.subplots(figsize=(6, 4))
68
+ sns.heatmap(df[numeric_columns].corr(), annot=True, cmap="coolwarm", ax=ax)
69
+ st.pyplot(fig)
70
+
71
+ with right_col:
72
+ st.subheader("馃挰 Chat with Your Data")
73
+
74
+ user_query = st.text_input("Ask a question about the data...")
75
+
76
+ if user_query and uploaded_file is not None:
77
+ # Prepare prompt for AI (limited to 5 columns and rounded)
78
+ numeric_df = df.apply(pd.to_numeric, errors="coerce")
79
+ safe_summary = numeric_df.describe().round(2).iloc[:, :5]
80
+
81
+ prompt = f"""
82
+ You are a data analyst. The user has uploaded a dataset.
83
+ Answer the query based on the dataset provided.
84
+
85
+ Dataset Overview (first 5 numeric columns):
86
+ {safe_summary.to_string()}
87
+
88
+ User Question:
89
+ {user_query}
90
+ """
91
+
92
+ try:
93
+ model = genai.GenerativeModel("models/gemini-pro")
94
+ response = model.generate_content(prompt)
95
+
96
+ if hasattr(response, "text"):
97
+ st.write("馃 AI Response:")
98
+ st.write(response.text)
99
+ else:
100
+ st.error("No se recibi贸 una respuesta v谩lida del modelo.")
101
+ except Exception as e:
102
+ st.error(f"Error al consultar el modelo Gemini: {e}")
requirements.txt CHANGED
@@ -1,6 +1,7 @@
1
- google-generativeai
2
- seaborn
3
  matplotlib
 
4
  plotly
5
- openpyxl
6
- pandas
 
1
+ streamlit
2
+ pandas
3
  matplotlib
4
+ seaborn
5
  plotly
6
+ google-generativeai
7
+ openpyxl