Spaces:
Build error
Build error
SHAMIL SHAHBAZ AWAN commited on
Update app.py
Browse files1 unmodified line234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636415 unmodified lines808182838485863 unmodified lines909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331 unmodified lineimport pandas as pdimport matplotlib.pyplot as pltimport seaborn as snsimport 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.")# 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)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.")return None# Function to generate graph based on user query15 unmodified lines# Bar chart for countries and units soldif '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)ax.set_xticklabels(ax.get_xticklabels(), rotation=45, ha='right')st.pyplot(fig)else:3 unmodified linesexcept 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."""try:# Send user query to Groq model using Groq SDKchat_completion = client.chat.completions.create(messages=[{"role": "user", "content": query}],model="llama3-8b-8192", # Model name as per your Groq model)# Display the responsest.write("Response from Groq Model:", chat_completion.choices[0].message.content)except Exception as e:st.error(f"Error in Groq processing: {e}")# 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)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():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)1 unmodified line234567891011121314151617181920212223242526272815 unmodified lines444546474849503 unmodified lines545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211 unmodified lineimport pandas as pdimport matplotlib.pyplot as pltimport seaborn as snsfrom io import StringIOimport openaiimport os# Groq API key from secretsGROQ_API_KEY = os.getenv("HUGGINGFACE_KEY")# Function to load the uploaded file (CSV or Excel)def load_file(uploaded_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 Nonereturn dataexcept 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 soldif '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, color='skyblue')ax.set_xticklabels(ax.get_xticklabels(), rotation=45, ha='right')st.pyplot(fig)else:3 unmodified linesexcept Exception as e:st.error(f"Error generating graph: {e}")# 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:# Initialize Groq clientclient = Groq(api_key=GROQ_API_KEY)# Query Groq model for responsechat_completion = client.chat.completions.create(messages=[{"role": "user", "content": prompt}],model="llama-3.1-8b-instant", # Replace with your model)return chat_completion.choices[0].message.contentexcept Exception as e:st.error(f"Error querying Groq model: {e}")return None# Streamlit App Interfacedef main():st.set_page_config(page_title="Data Augmentation and Visualization", page_icon="📊", layout="wide")# Set background imagest.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 sectionuploaded_file = st.file_uploader("Upload a CSV or Excel file", type=["csv", "xlsx"])if uploaded_file is not None:# Load and display datadata = load_file(uploaded_file)if data is not None:st.write("Dataset preview:", data.head())# User input for graph generationquery = st.text_input("Enter your query (e.g., 'Generate a bar chart for countries and units sold')")if query:# Generate the graph based on the querygenerate_graph(data, query)# User input for Groq model querymodel_query = st.text_input("Ask Groq model a question:")if model_query:# Query the Groq model and display responseresponse = query_groq_model(model_query)if response:st.write("Groq Model Response:", response)if __name__ == "__main__":main()
app.py+75-87