Spaces:
Build error
Build error
SHAMIL SHAHBAZ AWAN commited on
Update app.py
Browse files1 unmodified line2345678789101112139101115161718192021222324252627282930313233343536373839404142434445464748495051525312135556575859606114151617181920212223242526272815 unmodified lines44454683474849503 unmodified lines5455569394955758596097616263646599100666768102103104105697071107727374109110111112113114115757677787980818283848586878889909192939495969798991001011021031041051061171181191201211221071081091241251101271281291301311321331111121131141151161171181191201211 unmodified lineimport pandas as pdimport matplotlib.pyplot as pltimport seaborn as snsfrom io import StringIOimport openaiimport os
# Try importing openpyxl, and install if not presenttry: import openpyxlexcept ImportError: st.error("openpyxl module is required to read Excel files. Attempting to install...") os.system('pip install openpyxl') st.success("openpyxl installed successfully. Please restart the app.")# Groq API key from secretsGROQ_API_KEY = os.getenv("HUGGINGFACE_KEY")
# Import the Groq SDK (after installing it)try: from groq import Groqexcept ImportError: st.error("The 'groq' library is required but not installed. Please ensure it's included in requirements.txt.") raise
# Configure pagest.set_page_config(page_title="Data Augmentation App", layout="wide")st.markdown( f""" <style> .reportview-container {{ background: url("https://cdn.pixabay.com/photo/2016/06/02/02/33/triangles-1430105_1280.png"); background-size: cover; }} footer {{ text-align: left; }} </style> """, unsafe_allow_html=True,)
st.title("Data Augmentation and Analysis App")st.sidebar.title("Upload Your File")st.sidebar.markdown("Supported formats: CSV, Excel")
# Fetch Groq API key from Streamlit secretsgroq_api_key = st.secrets.get("HUGGINGFACE_KEY") # Fetch Groq API key stored in secrets.jsonif not groq_api_key: st.error("Groq API key not found in secrets.")else: st.success("Groq API Key Loaded Successfully!")
# Initialize Groq clientclient = Groq(api_key=groq_api_key)
# Function to load data from file (CSV/Excel)# Function to load the uploaded file (CSV or Excel)def load_file(uploaded_file): """Load the uploaded file.""" if uploaded_file.name.endswith('.csv'): return pd.read_csv(uploaded_file) elif uploaded_file.name.endswith('.xlsx'): return pd.read_excel(uploaded_file) else: st.error("Unsupported file format. Please upload a CSV or Excel file.") """Load data from an uploaded file.""" try: if uploaded_file.type == "text/csv": data = pd.read_csv(uploaded_file) elif uploaded_file.type == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": data = pd.read_excel(uploaded_file) else: st.error("Unsupported file type.") return None return data except Exception as e: st.error(f"Error loading file: {e}") return None
# Function to generate graph based on user query15 unmodified lines # Bar chart for countries and units sold if 'country' in data.columns and 'units sold' in data.columns: country_data = data[['country', 'units sold']].groupby('country').sum().reset_index() sns.barplot(x='country', y='units sold', data=country_data, ax=ax) sns.barplot(x='country', y='units sold', data=country_data, ax=ax, color='skyblue') ax.set_xticklabels(ax.get_xticklabels(), rotation=45, ha='right') st.pyplot(fig) else:3 unmodified lines except Exception as e: st.error(f"Error generating graph: {e}")
# Function to handle user queries using the Groq modeldef handle_query(query): """Handle user query using the Groq model."""# Function to query the Groq model (Groq API)def query_groq_model(prompt): """Send a query to the Groq model and get a response.""" try: # Send user query to Groq model using Groq SDK # Initialize Groq client client = Groq(api_key=GROQ_API_KEY)
# Query Groq model for response chat_completion = client.chat.completions.create( messages=[{"role": "user", "content": query}], model="llama3-8b-8192", # Model name as per your Groq model messages=[{"role": "user", "content": prompt}], model="llama-3.1-8b-instant", # Replace with your model ) # Display the response st.write("Response from Groq Model:", chat_completion.choices[0].message.content)
return chat_completion.choices[0].message.content except Exception as e: st.error(f"Error in Groq processing: {e}") st.error(f"Error querying Groq model: {e}") return None
# Main Appuploaded_file = st.sidebar.file_uploader("Upload your file here", type=["csv", "xlsx"])if uploaded_file: data = load_file(uploaded_file) if data is not None: st.write("Dataset Preview") st.dataframe(data)# Streamlit App Interfacedef main(): st.set_page_config(page_title="Data Augmentation and Visualization", page_icon="📊", layout="wide") # Set background image st.markdown( """ <style> .stApp { background-image: url('https://cdn.pixabay.com/photo/2016/06/02/02/33/triangles-1430105_1280.png'); background-size: cover; } </style> """, unsafe_allow_html=True ) st.title("Data Augmentation and Visualization with Groq API") st.markdown("Created by: Shamil Shahbaz", unsafe_allow_html=True) # File upload section uploaded_file = st.file_uploader("Upload a CSV or Excel file", type=["csv", "xlsx"]) if uploaded_file is not None: # Load and display data data = load_file(uploaded_file) if data is not None: st.write("Dataset preview:", data.head())
# User input for graph generation query = st.text_input("Enter your query (e.g., 'Generate a bar chart for countries and units sold')")
query = st.text_area("Ask your question about the dataset") if query: if "table" in query.lower(): st.write("Table Preview") st.write(data) elif "graph" in query.lower(): if query: # Generate the graph based on the query generate_graph(data, query) else: handle_query(query) # Use Groq model for query processing
# Footerfooter = """ <div style='text-align: left; padding: 10px;'> <footer>Created by: Shamil Shahbaz</footer> </div>"""st.markdown(footer, unsafe_allow_html=True) # User input for Groq model query model_query = st.text_input("Ask Groq model a question:") if model_query: # Query the Groq model and display response response = query_groq_model(model_query) if response: st.write("Groq Model Response:", response)
if __name__ == "__main__": main()app.py+75-87