GHarshasri commited on
Commit
fd9618a
Β·
verified Β·
1 Parent(s): ed0b30b

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +207 -38
src/streamlit_app.py CHANGED
@@ -1,40 +1,209 @@
1
- import altair as alt
2
- import numpy as np
3
- import pandas as pd
4
  import streamlit as st
 
 
5
 
6
- """
7
- # Welcome to Streamlit!
8
-
9
- Edit `/streamlit_app.py` to customize this app to your heart's desire :heart:.
10
- If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
11
- forums](https://discuss.streamlit.io).
12
-
13
- In the meantime, below is an example of what you can do with just a few lines of code:
14
- """
15
-
16
- num_points = st.slider("Number of points in spiral", 1, 10000, 1100)
17
- num_turns = st.slider("Number of turns in spiral", 1, 300, 31)
18
-
19
- indices = np.linspace(0, 1, num_points)
20
- theta = 2 * np.pi * num_turns * indices
21
- radius = indices
22
-
23
- x = radius * np.cos(theta)
24
- y = radius * np.sin(theta)
25
-
26
- df = pd.DataFrame({
27
- "x": x,
28
- "y": y,
29
- "idx": indices,
30
- "rand": np.random.randn(num_points),
31
- })
32
-
33
- st.altair_chart(alt.Chart(df, height=700, width=700)
34
- .mark_point(filled=True)
35
- .encode(
36
- x=alt.X("x", axis=None),
37
- y=alt.Y("y", axis=None),
38
- color=alt.Color("idx", legend=None, scale=alt.Scale()),
39
- size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])),
40
- ))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import streamlit as st
2
+ import sqlite3
3
+ import os
4
 
5
+ # ---------------- DATABASE SETUP ----------------
6
+ DB_PATH = "telangana.db"
7
+
8
+ def create_tables():
9
+ conn = sqlite3.connect(DB_PATH)
10
+ cursor = conn.cursor()
11
+ cursor.execute("""
12
+ CREATE TABLE IF NOT EXISTS districts (
13
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
14
+ name TEXT UNIQUE
15
+ )""")
16
+ cursor.execute("""
17
+ CREATE TABLE IF NOT EXISTS categories (
18
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
19
+ district_id INTEGER,
20
+ category_name TEXT,
21
+ FOREIGN KEY(district_id) REFERENCES districts(id)
22
+ )""")
23
+ cursor.execute("""
24
+ CREATE TABLE IF NOT EXISTS products (
25
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
26
+ category_id INTEGER,
27
+ product_name TEXT,
28
+ description TEXT,
29
+ image_data BLOB,
30
+ FOREIGN KEY(category_id) REFERENCES categories(id)
31
+ )""")
32
+ conn.commit()
33
+ conn.close()
34
+
35
+ create_tables()
36
+
37
+ # ---------------- FUNCTIONS ----------------
38
+ def add_district(name):
39
+ conn = sqlite3.connect(DB_PATH)
40
+ cursor = conn.cursor()
41
+ cursor.execute("INSERT OR IGNORE INTO districts(name) VALUES(?)", (name,))
42
+ conn.commit()
43
+ conn.close()
44
+
45
+ def add_category(district_name, category_name):
46
+ conn = sqlite3.connect(DB_PATH)
47
+ cursor = conn.cursor()
48
+ cursor.execute("SELECT id FROM districts WHERE name=?", (district_name,))
49
+ district_id = cursor.fetchone()
50
+ if district_id:
51
+ cursor.execute("INSERT INTO categories(district_id, category_name) VALUES(?, ?)", (district_id[0], category_name))
52
+ conn.commit()
53
+ conn.close()
54
+
55
+ def add_product(category_id, product_name, description, image_bytes):
56
+ conn = sqlite3.connect(DB_PATH)
57
+ cursor = conn.cursor()
58
+ cursor.execute("""
59
+ INSERT INTO products(category_id, product_name, description, image_data)
60
+ VALUES(?, ?, ?, ?)""", (category_id, product_name, description, image_bytes))
61
+ conn.commit()
62
+ conn.close()
63
+
64
+ def get_all_data():
65
+ conn = sqlite3.connect(DB_PATH)
66
+ cursor = conn.cursor()
67
+ cursor.execute("""
68
+ SELECT d.name, c.category_name, p.product_name
69
+ FROM districts d
70
+ JOIN categories c ON d.id = c.district_id
71
+ JOIN products p ON c.id = p.category_id
72
+ """)
73
+ data = cursor.fetchall()
74
+ conn.close()
75
+ return data
76
+
77
+ # ---------------- APP CONFIG ----------------
78
+ st.set_page_config(page_title="Telangana Products Explorer", page_icon="🌾", layout="wide")
79
+ menu = st.sidebar.radio("Navigation", ["Home", "Add Data", "View by District"])
80
+
81
+ # ---------------- HOME PAGE ----------------
82
+ if menu == "Home":
83
+ st.title("🌾 Telangana Famous Products")
84
+ st.subheader("Explore Products by District")
85
+
86
+ data = get_all_data()
87
+ if data:
88
+ grouped = {}
89
+ for district, category, product in data:
90
+ grouped.setdefault(district, {}).setdefault(category, []).append(product)
91
+
92
+ for district, categories in grouped.items():
93
+ with st.expander(f"πŸ“ {district}"):
94
+ for category, products in categories.items():
95
+ # CORRECTED LINE BELOW:
96
+ st.write(f"{category}: {', '.join(products)}")
97
+ else:
98
+ st.info("No data available. Please add data in 'Add Data' section.")
99
+
100
+ # ---------------- ADD DATA PAGE ----------------
101
+ elif menu == "Add Data":
102
+ st.header("Add New Data")
103
+
104
+ # Add District
105
+ with st.form("add_district_form"):
106
+ district_name = st.text_input("District Name")
107
+ submitted = st.form_submit_button("Add District")
108
+ if submitted and district_name:
109
+ add_district(district_name)
110
+ st.success(f"βœ… District '{district_name}' added!")
111
+
112
+ st.write("---")
113
+
114
+ # Add Category
115
+ with st.form("add_category_form"):
116
+ conn = sqlite3.connect(DB_PATH)
117
+ cursor = conn.cursor()
118
+ cursor.execute("SELECT name FROM districts")
119
+ district_list = [row[0] for row in cursor.fetchall()]
120
+ conn.close()
121
+
122
+ if district_list:
123
+ selected_district = st.selectbox("Select District", district_list)
124
+ category_name = st.text_input("Category Name")
125
+ cat_submitted = st.form_submit_button("Add Category")
126
+ if cat_submitted and selected_district and category_name:
127
+ add_category(selected_district, category_name)
128
+ st.success(f"βœ… Category '{category_name}' added to {selected_district}")
129
+ else:
130
+ st.warning("Please add districts first.")
131
+
132
+ st.write("---")
133
+
134
+ # Add Product
135
+ with st.form("add_product_form"):
136
+ conn = sqlite3.connect(DB_PATH)
137
+ cursor = conn.cursor()
138
+ cursor.execute("""
139
+ SELECT c.id, c.category_name, d.name
140
+ FROM categories c
141
+ JOIN districts d ON c.district_id = d.id
142
+ """)
143
+ category_list = [(row[0], f"{row[2]} - {row[1]}") for row in cursor.fetchall()]
144
+ conn.close()
145
+
146
+ if category_list:
147
+ category_dict = {label: cat_id for cat_id, label in category_list}
148
+ selected_category_label = st.selectbox("Select Category", list(category_dict.keys()))
149
+ product_name = st.text_input("Product Name")
150
+ product_description = st.text_area("Product Description")
151
+ product_image = st.file_uploader("Product Image", type=["png", "jpg", "jpeg"])
152
+
153
+ prod_submitted = st.form_submit_button("Add Product")
154
+ if prod_submitted and selected_category_label and product_name:
155
+ image_bytes = product_image.getvalue() if product_image else None
156
+ add_product(
157
+ category_dict[selected_category_label],
158
+ product_name,
159
+ product_description,
160
+ image_bytes
161
+ )
162
+ st.success(f"βœ… Product '{product_name}' added!")
163
+ else:
164
+ st.warning("Please add categories first.")
165
+
166
+ # ---------------- VIEW BY DISTRICT ----------------
167
+ elif menu == "View by District":
168
+ conn = sqlite3.connect(DB_PATH)
169
+ cursor = conn.cursor()
170
+ cursor.execute("SELECT name FROM districts")
171
+ districts = [row[0] for row in cursor.fetchall()]
172
+ conn.close()
173
+
174
+ if districts:
175
+ selected_district = st.selectbox("Select District", districts)
176
+ if selected_district:
177
+ conn = sqlite3.connect(DB_PATH)
178
+ cursor = conn.cursor()
179
+ cursor.execute("""
180
+ SELECT c.category_name, p.product_name, p.description, p.image_data
181
+ FROM districts d
182
+ JOIN categories c ON d.id = c.district_id
183
+ JOIN products p ON c.id = p.category_id
184
+ WHERE d.name = ?
185
+ """, (selected_district,))
186
+ rows = cursor.fetchall()
187
+ conn.close()
188
+
189
+ if rows:
190
+ st.write(f"### πŸ“ {selected_district}")
191
+ category_dict = {}
192
+ for category, product, description, image in rows:
193
+ category_dict.setdefault(category, []).append((product, description, image))
194
+
195
+ for category, products in category_dict.items():
196
+ st.markdown(f"#### 🏷 {category}")
197
+ for product_name, description, image_data in products:
198
+ col1, col2 = st.columns([1, 3])
199
+ with col1:
200
+ if image_data:
201
+ st.image(image_data, use_column_width=True)
202
+ with col2:
203
+ st.write(f"{product_name}") # Bolding product name for consistency
204
+ st.caption(description)
205
+ st.write("---")
206
+ else:
207
+ st.info("No products available for this district.")
208
+ else:
209
+ st.warning("Please add districts first.")