Harika22 commited on
Commit
8f5e545
Β·
verified Β·
1 Parent(s): db71c87

Update pages/model.py

Browse files
Files changed (1) hide show
  1. pages/model.py +111 -0
pages/model.py CHANGED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import os
3
+ import pandas as pd
4
+ import matplotlib.pyplot as plt
5
+ import seaborn as sns
6
+ from io import StringIO
7
+ from langchain_huggingface import HuggingFaceEndpoint, ChatHuggingFace
8
+
9
+
10
+ os.environ["HF_TOKEN"]=os.getenv('HF_Token')
11
+ os.environ["HUGGINGFACEHUB_API_KEY"]=os.getenv('HF_Token')
12
+
13
+ st.set_page_config(page_title="InsightGenie – AI-Powered CSV Explorer", layout="wide")
14
+ st.title("πŸ§™ InsightGenie")
15
+ st.markdown("**Explore your CSV like magic – Ask, analyze, and visualize with AI.**")
16
+
17
+ if "qa_conversations" not in st.session_state:
18
+ st.session_state.qa_conversations = []
19
+
20
+ uploaded_csv = st.file_uploader("πŸ“‚ Upload your CSV file to begin", type=["csv"])
21
+
22
+ if uploaded_csv:
23
+ try:
24
+ data = pd.read_csv(uploaded_csv)
25
+ st.success("βœ… Data loaded successfully!")
26
+
27
+ st.header("πŸ”Ž Dataset Overview")
28
+ st.markdown(f"- **Rows and Columns:** {data.shape[0]} rows Γ— {data.shape[1]} columns")
29
+ st.markdown("**πŸ“Œ Column Names:**")
30
+ st.write(data.columns.tolist())
31
+
32
+ col1, col2 = st.columns(2)
33
+ with col1:
34
+ st.markdown("**🧩 Missing Values**")
35
+ st.dataframe(data.isnull().sum(), height=200)
36
+ with col2:
37
+ st.markdown("**πŸ”’ Data Types**")
38
+ st.dataframe(data.dtypes, height=200)
39
+
40
+ except Exception as e:
41
+ st.error(f"❌ Failed to read the file: {e}")
42
+ st.stop()
43
+
44
+ st.header("πŸ’¬ Ask InsightGenie")
45
+ user_question = st.text_input("Type your question about the dataset here:")
46
+
47
+ genie_endpoint = HuggingFaceEndpoint(
48
+ repo_id="deepseek-ai/DeepSeek-R1",
49
+ provider="nebius",
50
+ temperature=0.5,
51
+ max_new_tokens=150,
52
+ task="conversational"
53
+ )
54
+
55
+ genie_chatbot = ChatHuggingFace(
56
+ llm=genie_endpoint,
57
+ repo_id=genie_endpoint.repo_id,
58
+ provider=genie_endpoint.provider,
59
+ temperature=0.5,
60
+ max_new_tokens=150,
61
+ task="conversational"
62
+ )
63
+
64
+ if user_question:
65
+ sample_data = data.head(50).to_csv(index=False)
66
+
67
+ prompt = f"""
68
+ You are a skilled data assistant named InsightGenie. A user has uploaded a dataset and asked a question.
69
+ Answer clearly. If the question involves charts or graphs, provide appropriate Python code using matplotlib or seaborn.
70
+
71
+ Here’s a preview of the dataset:
72
+ {sample_data}
73
+
74
+ User question:
75
+ {user_question}
76
+ """
77
+
78
+ with st.spinner("πŸ” Generating response..."):
79
+ try:
80
+ model_response = genie_chatbot.invoke([{"role": "user", "content": prompt}])
81
+ bot_reply = model_response.content if hasattr(model_response, "content") else model_response
82
+
83
+ st.session_state.qa_conversations.append((user_question, bot_reply))
84
+
85
+ st.markdown("### 🧠 Genie Says")
86
+ st.write(bot_reply)
87
+
88
+ # Auto-plot for simple queries
89
+ if "plot" in user_question.lower():
90
+ with st.expander("πŸ“Š Auto-generated Plot"):
91
+ try:
92
+ numeric_cols = data.select_dtypes(include='number').columns.tolist()
93
+ if len(numeric_cols) >= 2:
94
+ fig, ax = plt.subplots()
95
+ sns.lineplot(data=data, x=numeric_cols[0], y=numeric_cols[1], ax=ax)
96
+ ax.set_title(f"{numeric_cols[1]} vs {numeric_cols[0]}")
97
+ st.pyplot(fig)
98
+ else:
99
+ st.info("⚠️ Not enough numeric columns to generate a plot.")
100
+ except Exception as e:
101
+ st.error(f"❌ Plotting error: {e}")
102
+ except Exception as e:
103
+ st.error(f"❌ Error generating AI response: {e}")
104
+
105
+ if st.session_state.qa_conversations:
106
+ st.header("πŸ“š Chat History")
107
+ for user_q, ai_a in reversed(st.session_state.qa_conversations):
108
+ st.markdown(f"**πŸ§‘β€πŸ’» You:** {user_q}")
109
+ st.markdown(f"**πŸ€– InsightGenie:** {ai_a}")
110
+ st.markdown("---")
111
+