File size: 7,739 Bytes
64ed1eb
fd9618a
 
64ed1eb
fd9618a
c7bea95
fd9618a
 
c7bea95
fd9618a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c7bea95
fd9618a
 
 
c7bea95
fd9618a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c7bea95
fd9618a
 
c7bea95
 
 
 
 
fd9618a
 
 
 
 
 
 
 
 
 
 
 
c7bea95
 
 
 
 
 
 
fd9618a
 
 
 
c7bea95
 
fd9618a
 
 
 
 
 
 
 
 
 
c7bea95
fd9618a
 
 
 
 
 
c7bea95
 
fd9618a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c7bea95
fd9618a
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
import streamlit as st
import sqlite3
import os

# ---------------- DATABASE SETUP ----------------
DB_PATH = "/tmp/telangana.db"  # Hugging Face writable directory

def create_tables():
    conn = sqlite3.connect(DB_PATH)
    cursor = conn.cursor()
    cursor.execute("""
    CREATE TABLE IF NOT EXISTS districts (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        name TEXT UNIQUE
    )""")
    cursor.execute("""
    CREATE TABLE IF NOT EXISTS categories (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        district_id INTEGER,
        category_name TEXT,
        FOREIGN KEY(district_id) REFERENCES districts(id)
    )""")
    cursor.execute("""
    CREATE TABLE IF NOT EXISTS products (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        category_id INTEGER,
        product_name TEXT,
        description TEXT,
        image_data BLOB,
        FOREIGN KEY(category_id) REFERENCES categories(id)
    )""")
    conn.commit()
    conn.close()

create_tables()

# ---------------- FUNCTIONS ----------------
def add_district(name):
    conn = sqlite3.connect(DB_PATH)
    cursor = conn.cursor()
    cursor.execute("INSERT OR IGNORE INTO districts(name) VALUES(?)", (name,))
    conn.commit()
    conn.close()

def add_category(district_name, category_name):
    conn = sqlite3.connect(DB_PATH)
    cursor = conn.cursor()
    cursor.execute("SELECT id FROM districts WHERE name=?", (district_name,))
    district_id = cursor.fetchone()
    if district_id:
        cursor.execute("INSERT INTO categories(district_id, category_name) VALUES(?, ?)", (district_id[0], category_name))
        conn.commit()
    conn.close()

def add_product(category_id, product_name, description, image_bytes):
    conn = sqlite3.connect(DB_PATH)
    cursor = conn.cursor()
    cursor.execute("""
        INSERT INTO products(category_id, product_name, description, image_data)
        VALUES(?, ?, ?, ?)""", (category_id, product_name, description, image_bytes))
    conn.commit()
    conn.close()

def get_all_data():
    conn = sqlite3.connect(DB_PATH)
    cursor = conn.cursor()
    cursor.execute("""
    SELECT d.name, c.category_name, p.product_name
    FROM districts d
    JOIN categories c ON d.id = c.district_id
    JOIN products p ON c.id = p.category_id
    """)
    data = cursor.fetchall()
    conn.close()
    return data

# ---------------- APP CONFIG ----------------
st.set_page_config(page_title="Telangana Products Explorer", page_icon="🌾", layout="wide")
menu = st.sidebar.radio("Navigation", ["Home", "Add Data", "View by District"])

# ---------------- HOME PAGE ----------------
if menu == "Home":
    st.title("🌾 Telangana Famous Products")
    st.subheader("Explore Products by District")

    data = get_all_data()
    if data:
        grouped = {}
        for district, category, product in data:
            grouped.setdefault(district, {}).setdefault(category, []).append(product)

        for district, categories in grouped.items():
            with st.expander(f"πŸ“ {district}"):
                for category, products in categories.items():
                    st.write(f"{category}: {', '.join(products)}")
    else:
        st.info("No data available. Please add data in 'Add Data' section.")

# ---------------- ADD DATA PAGE ----------------
elif menu == "Add Data":
    st.header("Add New Data")

    # Add District
    with st.form("add_district_form"):
        district_name = st.text_input("District Name")
        submitted = st.form_submit_button("Add District")
        if submitted and district_name:
            add_district(district_name)
            st.success(f"βœ… District '{district_name}' added!")

    st.write("---")

    # Add Category
    with st.form("add_category_form"):
        conn = sqlite3.connect(DB_PATH)
        cursor = conn.cursor()
        cursor.execute("SELECT name FROM districts")
        district_list = [row[0] for row in cursor.fetchall()]
        conn.close()

        if district_list:
            selected_district = st.selectbox("Select District", district_list)
            category_name = st.text_input("Category Name")
            cat_submitted = st.form_submit_button("Add Category")
            if cat_submitted and selected_district and category_name:
                add_category(selected_district, category_name)
                st.success(f"βœ… Category '{category_name}' added to {selected_district}")
        else:
            st.warning("Please add districts first.")

    st.write("---")

    # Add Product
    with st.form("add_product_form"):
        conn = sqlite3.connect(DB_PATH)
        cursor = conn.cursor()
        cursor.execute("""
        SELECT c.id, c.category_name, d.name 
        FROM categories c 
        JOIN districts d ON c.district_id = d.id
        """)
        category_list = [(row[0], f"{row[2]} - {row[1]}") for row in cursor.fetchall()]
        conn.close()

        if category_list:
            category_dict = {label: cat_id for cat_id, label in category_list}
            selected_category_label = st.selectbox("Select Category", list(category_dict.keys()))
            product_name = st.text_input("Product Name")
            product_description = st.text_area("Product Description")
            product_image = st.file_uploader("Product Image", type=["png", "jpg", "jpeg"])

            prod_submitted = st.form_submit_button("Add Product")
            if prod_submitted and selected_category_label and product_name:
                image_bytes = product_image.getvalue() if product_image else None
                add_product(
                    category_dict[selected_category_label],
                    product_name,
                    product_description,
                    image_bytes
                )
                st.success(f"βœ… Product '{product_name}' added!")
        else:
            st.warning("Please add categories first.")

# ---------------- VIEW BY DISTRICT ----------------
elif menu == "View by District":
    conn = sqlite3.connect(DB_PATH)
    cursor = conn.cursor()
    cursor.execute("SELECT name FROM districts")
    districts = [row[0] for row in cursor.fetchall()]
    conn.close()

    if districts:
        selected_district = st.selectbox("Select District", districts)
        if selected_district:
            conn = sqlite3.connect(DB_PATH)
            cursor = conn.cursor()
            cursor.execute("""
            SELECT c.category_name, p.product_name, p.description, p.image_data
            FROM districts d
            JOIN categories c ON d.id = c.district_id
            JOIN products p ON c.id = p.category_id
            WHERE d.name = ?
            """, (selected_district,))
            rows = cursor.fetchall()
            conn.close()

            if rows:
                st.write(f"### πŸ“ {selected_district}")
                category_dict = {}
                for category, product, description, image in rows:
                    category_dict.setdefault(category, []).append((product, description, image))

                for category, products in category_dict.items():
                    st.markdown(f"#### 🏷 {category}")
                    for product_name, description, image_data in products:
                        col1, col2 = st.columns([1, 3])
                        with col1:
                            if image_data:
                                st.image(image_data, use_column_width=True)
                        with col2:
                            st.write(f"**{product_name}**")
                            st.caption(description)
                    st.write("---")
            else:
                st.info("No products available for this district.")
    else:
        st.warning("Please add districts first.")