Spaces:
Sleeping
Sleeping
Update app.py
#2
by MeerRangrez - opened
12345678910111213141516171819202113 unmodified lines3536373839404142434445465 unmodified lines52535455565758596061625 unmodified lines68697071727374757677787980818283848528 unmodified lines11411511611711811912027 unmodified lines1481491501511521531541551561575 unmodified lines16316416516616716816926 unmodified lines19619719819920020120216 unmodified lines2192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492501 unmodified line25225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631789 unmodified lines407408409410411412413import streamlit as stimport sqlite3import pandas as pdfrom PIL import Imageimport io# Page Configuration for Mobile & Desktop responsivenessst.set_page_config(page_title="Difa E Ahlesunnat Smart System", layout="centered")DB_NAME = 'masjid_difa_system.db'# --- 1. ULTRA-SMOOTH & LAG-FREE DATABASE UTILITIES ---def init_db():"""Initializes the database with WAL mode enabled to completely eliminate connection glitches."""conn = sqlite3.connect(DB_NAME, timeout=60.0)try:c = conn.cursor()# Enable Write-Ahead Logging for high concurrency and lag-free mobile usagec.execute("PRAGMA journal_mode=WAL;")c.execute("PRAGMA synchronous=NORMAL;")13 unmodified linesref_book TEXT, page_no TEXT, ref_img BLOB,FOREIGN KEY(topic_id) REFERENCES global_aqaid(id) ON DELETE CASCADE)''')# Quran Folders & Pages Tablec.execute('''CREATE TABLE IF NOT EXISTS quran_folders(id INTEGER PRIMARY KEY AUTOINCREMENT, folder_name TEXT, cover_img BLOB)''')c.execute('''CREATE TABLE IF NOT EXISTS quran_pages(id INTEGER PRIMARY KEY AUTOINCREMENT, quran_folder_id INTEGER, surah_verse TEXT, manually_text TEXT, quran_img BLOB,FOREIGN KEY(quran_folder_id) REFERENCES quran_folders(id) ON DELETE CASCADE)''')# Fiqh & Masail Tablesc.execute('''CREATE TABLE IF NOT EXISTS fiqh_folders5 unmodified linesfinally:conn.close()# Run initialization once at startupinit_db()def run_query(query, params=(), is_select=True):"""Executes queries safely using short-lived connections to protect mobile sessions from freezing."""conn = sqlite3.connect(DB_NAME, timeout=60.0)conn.execute("PRAGMA journal_mode=WAL;")try:5 unmodified linescursor.execute(query, params)return cursor.lastrowidexcept sqlite3.OperationalError as e:st.error(f"Database Busy/Locked: {e}. Retrying operation dynamically...")return Nonefinally:conn.close()# --- 2. SESSION STATE MANAGEMENT ---states = ['role', 'logged_in_masjid', 'selected_aqaid_id', 'selected_quran_folder_id', 'selected_fiqh_folder_id']for state in states:if state not in st.session_state:st.session_state[state] = 'namzi' if state == 'role' else None# --- 3. MOBILE-OPTIMIZED PREMIUM CSS ---st.markdown("""<style>.stApp { background-color: #f5f6f8; }28 unmodified linesst.markdown("<div class='apk-credit'>APK created BY UMAID RANGREZ</div>", unsafe_allow_html=True)st.markdown("<div class='app-title'>🕌 DIFA E AHLESUNNAT SMART SYSTEM</div>", unsafe_allow_html=True)# --- 4. SIDEBAR NAVIGATION ---st.sidebar.markdown("## 🧭 Navigation Panel")if st.session_state['role'] == 'namzi':menu = st.sidebar.radio("Go To Panel:", ["📋 VIEW LIVE BOARD", "⚙️ OWNER LOGIN", "🕌 IMAAME LOGIN"])27 unmodified linesst.session_state['logged_in_masjid'] = Nonest.session_state['selected_aqaid_id'] = Nonest.session_state['selected_quran_folder_id'] = Nonest.session_state['selected_fiqh_folder_id'] = Nonest.rerun()# --- 5. OWNER MASJID REGISTRATION ---if st.session_state['role'] == 'owner':st.markdown("### 🛠️ Owner Control Desk")with st.expander("➕ Register New Masjid (Full System)"):5 unmodified linesst.success(f"'{n_name}' registered successfully!")st.rerun()# --- 6. CORE TABS SYSTEM ---all_masjids = run_query("SELECT id, name FROM masjids")tab_board, tab_quran, tab_aqaid, tab_fiqh = st.tabs(["📊 Masjid Time Board", "📖 Quran Shareef", "🛡️ Difa E Aqaid", "📝 Fiqh Wa Masail"])26 unmodified linesst.markdown(f"<div class='notice-box box-red'><div class='notice-title'>🚨 जनाज़ा जानकारी</div><div class='notice-desc'>{data.get('zanaza') or 'कोई सूचना नहीं है।'}</div></div>", unsafe_allow_html=True)st.markdown(f"<div class='notice-box box-green'><div class='notice-title'>🕋 ईद-उल-फ़ित्र (Yearly)</div><div class='notice-desc'>{data.get('yearly') or 'सूचना यहाँ लाइव दिखेगी।'}</div></div>", unsafe_allow_html=True)st.markdown(f"<div class='notice-box box-blue'><div class='notice-title'>📢 ओनर संदेश</div><div class='notice-desc'>{data.get('extra') or 'विशेष संदेश यहाँ देखें।'}</div></div>", unsafe_allow_html=True)st.markdown(f"<div class='notice-box box-pink'><div class='notice-title'>💗 स्पेशल अपडेट्स</div><div class='notice-desc'>{data.get('pink_box') or 'लाइव अपडेट्स यहाँ देखें।'}</div></div>", unsafe_allow_html=True)if data['bottom_img']: st.image(data['bottom_img'], use_column_width=True)if (st.session_state['role'] == 'owner') or (st.session_state['role'] == 'imam' and st.session_state['logged_in_masjid'] == selected_id):16 unmodified linesst.rerun()else: st.info("No masjids registered yet.")# --- TAB 2: UPGRADED QURAN SHAREEF MODULE ---with tab_quran:st.markdown("### 📖 Upgraded Quran Shareef Dashboard")q_folders = run_query("SELECT * FROM quran_folders")if st.session_state['selected_quran_folder_id'] is not None:q_fid = st.session_state['selected_quran_folder_id']if q_folders is not None and not q_folders.empty and q_fid in q_folders['id'].values:cur_q_folder = q_folders[q_folders['id'] == q_fid].iloc[0]if st.button("⬅️ Back to Quran Versions List", key="back_quran_main"):st.session_state['selected_quran_folder_id'] = Nonest.rerun()st.markdown(f"#### 📁 Quran Version: {cur_q_folder['folder_name']}")q_pages_df = run_query("SELECT * FROM quran_pages WHERE quran_folder_id=? ORDER BY id ASC", (q_fid,))if q_pages_df is not None and not q_pages_df.empty:for p_idx, p_row in q_pages_df.iterrows():st.markdown(f"<div class='detail-container'><span class='counter-badge'>Page ID: {p_row['id']} | Sequence #{p_idx + 1}</span><h5>📖 Reference/Para/Surah: {p_row['surah_verse']}</h5><p class='detail-text'>{p_row['manually_text']}</p></div>", unsafe_allow_html=True)if p_row['quran_img']:q_img_list = p_row['quran_img'].split(b"##Q_IMG_SEP##")for sub_idx, q_img in enumerate(q_img_list):if q_img: st.image(q_img, caption=f"Page/Part {sub_idx+1}", use_column_width=True)else: st.info("Is version me koi page ya image store nahi hai.")else:st.session_state['selected_quran_folder_id'] = Nonest.rerun()else:if q_folders is not None and not q_folders.empty:q_cols = st.columns(2)1 unmodified linewith q_cols[idx % 2]:st.markdown(f"<div class='grid-card-box'><div class='grid-card-title'>📖 {row['folder_name']}</div></div>", unsafe_allow_html=True)if row['cover_img']: st.image(row['cover_img'], use_column_width=True)if st.button(f"Open Version: {row['folder_name']}", key=f"open_q_{row['id']}", use_container_width=True):st.session_state['selected_quran_folder_id'] = int(row['id'])st.rerun()st.markdown("<br>", unsafe_allow_html=True)else: st.info("Quran Database is empty. Create folders via Owner Terminal.")if st.session_state['role'] == 'owner':st.markdown("---")st.markdown("#### 🛠️ Owner Quran Control Terminal")q_action = st.radio("Quran Operations", ["1. Create New Quran Version (Folder)", "2. Add/Upload Bulk Pages (Multi-Image)", "3. Correct/Edit Quran Page Data", "4. Delete Entire Version Folder"], key="quran_owner_radio")if q_action == "1. Create New Quran Version (Folder)":with st.form("q_f_add", clear_on_submit=True):q_vname = st.text_input("Quran Version/Firqa Name")q_cover = st.file_uploader("Upload Cover Graphic", type=['jpg','png','jpeg'])if st.form_submit_button("Add New Quran Column") and q_vname:run_query("INSERT INTO quran_folders (folder_name, cover_img) VALUES (?, ?)", (q_vname, q_cover.getvalue() if q_cover else None), is_select=False)st.success("New Column Setup Done!")st.rerun()elif q_action == "2. Add/Upload Bulk Pages (Multi-Image)" and q_folders is not None and not q_folders.empty:target_q_f = st.selectbox("Select Version Column:", q_folders['id'].tolist(), format_func=lambda x: q_folders[q_folders['id']==x]['folder_name'].values[0])with st.form("q_p_add", clear_on_submit=True):q_sv = st.text_input("Surah / Para / Verse Reference")q_m_text = st.text_area("Manually Written Translation/Notes")q_photos = st.file_uploader("Upload Pages (Upto 600-1200 items support)", type=['jpg','png','jpeg'], accept_multiple_files=True)if st.form_submit_button("Save Entry inside Column"):q_combined = b""if q_photos: q_combined = b"##Q_IMG_SEP##".join([f.getvalue() for f in q_photos])run_query("INSERT INTO quran_pages (quran_folder_id, surah_verse, manually_text, quran_img) VALUES (?, ?, ?, ?)", (target_q_f, q_sv, q_m_text, q_combined), is_select=False)st.success("Pages Added Successfully!")st.rerun()elif q_action == "3. Correct/Edit Quran Page Data":all_qp = run_query("SELECT id, surah_verse, manually_text FROM quran_pages")if all_qp is not None and not all_qp.empty:edit_q_id = st.selectbox("Select Page ID to Correct:", all_qp['id'].tolist(), format_func=lambda x: f"Page ID: {x} - {all_qp[all_qp['id']==x]['surah_verse'].values[0]}")cur_qp_row = all_qp[all_qp['id'] == edit_q_id].iloc[0]with st.form("edit_q_form"):eq_sv = st.text_input("Correct Reference:", value=cur_qp_row['surah_verse'])eq_tx = st.text_area("Correct Manual Text:", value=cur_qp_row['manually_text'])eq_img = st.file_uploader("Replace Images (Leave blank to keep old)", type=['jpg','png','jpeg'], accept_multiple_files=True)if st.form_submit_button("🛠️ APPLY REVISIONS"):if eq_img:q_bytes = b"##Q_IMG_SEP##".join([f.getvalue() for f in eq_img])run_query("UPDATE quran_pages SET surah_verse=?, manually_text=?, quran_img=? WHERE id=?", (eq_sv, eq_tx, q_bytes, edit_q_id), is_select=False)else:run_query("UPDATE quran_pages SET surah_verse=?, manually_text=? WHERE id=?", (eq_sv, eq_tx, edit_q_id), is_select=False)st.success("Quran Page Corrected!")st.rerun()else: st.info("No pages found to edit.")elif q_action == "4. Delete Entire Version Folder" and q_folders is not None and not q_folders.empty:del_q_id = st.selectbox("Select Version to Wipe Out:", q_folders['id'].tolist(), format_func=lambda x: q_folders[q_folders['id']==x]['folder_name'].values[0])if st.button("🔴 CONFIRM DELETE VERSION", type="primary"):run_query("DELETE FROM quran_folders WHERE id=?", (del_q_id,), is_select=False)run_query("DELETE FROM quran_pages WHERE quran_folder_id=?", (del_q_id,), is_select=False)st.success("Column Removed Successfully.")st.session_state['selected_quran_folder_id'] = Nonest.rerun()# --- TAB 3: DYNAMIC MULTI-REFERENCE DIFA E AQAID ---with tab_aqaid:89 unmodified linesst.session_state['selected_aqaid_id'] = Nonest.rerun()# --- TAB 4: FIQH WA MASAIL ---with tab_fiqh:st.markdown("### 📝 Fiqh Wa Masail (Masail Directory)")fiqh_data = run_query("SELECT * FROM fiqh_folders")1234567891011121314151617181913 unmodified lines333435363738394041424344454647484950515253545 unmodified lines6061626364656667685 unmodified lines74757677787980818283848586878889909128 unmodified lines12012112212312412512627 unmodified lines1541551561571581591601611621631645 unmodified lines17017117217317417517626 unmodified lines20320420520620720820916 unmodified lines2262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982991 unmodified line30130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439589 unmodified lines485486487488489490491import streamlit as stimport sqlite3import pandas as pdimport io# Page Configuration for Responsive Mobile/Desktop Viewst.set_page_config(page_title="Difa E Ahlesunnat Smart System", layout="centered")DB_NAME = 'masjid_difa_system.db'# --- 1. ULTRA-SMOOTH WAL-MODE DATABASE INITIALIZATION ---def init_db():"""Initializes database with sub-folder and Audio/Voice capabilities for Quran"""conn = sqlite3.connect(DB_NAME, timeout=60.0)try:c = conn.cursor()c.execute("PRAGMA journal_mode=WAL;")c.execute("PRAGMA synchronous=NORMAL;")13 unmodified linesref_book TEXT, page_no TEXT, ref_img BLOB,FOREIGN KEY(topic_id) REFERENCES global_aqaid(id) ON DELETE CASCADE)''')# Quran Main Columns (Folders - Can be used for Para Wise or Full Quran directly)c.execute('''CREATE TABLE IF NOT EXISTS quran_folders(id INTEGER PRIMARY KEY AUTOINCREMENT, folder_name TEXT, cover_img BLOB)''')# Quran Sub-Columns (Optional Sub-Folders, e.g., Para 1, Para 2...)c.execute('''CREATE TABLE IF NOT EXISTS quran_sub_folders(id INTEGER PRIMARY KEY AUTOINCREMENT, main_folder_id INTEGER, sub_folder_name TEXT,FOREIGN KEY(main_folder_id) REFERENCES quran_folders(id) ON DELETE CASCADE)''')# UPGRADED: Quran Content (Supports Multi-Images + Full PDF + Voice/Audio MP3 File)c.execute('''CREATE TABLE IF NOT EXISTS quran_pages(id INTEGER PRIMARY KEY AUTOINCREMENT, main_folder_id INTEGER, sub_folder_id INTEGER,surah_verse TEXT, manually_text TEXT, quran_img BLOB, pdf_file BLOB, pdf_name TEXT,voice_audio BLOB, voice_name TEXT,FOREIGN KEY(main_folder_id) REFERENCES quran_folders(id) ON DELETE CASCADE,FOREIGN KEY(sub_folder_id) REFERENCES quran_sub_folders(id) ON DELETE CASCADE)''')# Fiqh & Masail Tablesc.execute('''CREATE TABLE IF NOT EXISTS fiqh_folders5 unmodified linesfinally:conn.close()init_db()def run_query(query, params=(), is_select=True):conn = sqlite3.connect(DB_NAME, timeout=60.0)conn.execute("PRAGMA journal_mode=WAL;")try:5 unmodified linescursor.execute(query, params)return cursor.lastrowidexcept sqlite3.OperationalError as e:st.error(f"Database Busy: {e}")return Nonefinally:conn.close()# --- 2. SESSION STATE MANAGEMENT ---states = ['role', 'logged_in_masjid', 'selected_aqaid_id', 'selected_quran_folder_id', 'selected_quran_sub_id', 'selected_fiqh_folder_id']for state in states:if state not in st.session_state:st.session_state[state] = 'namzi' if state == 'role' else None# --- 3. MOBILE PREMIUM STYLING ---st.markdown("""<style>.stApp { background-color: #f5f6f8; }28 unmodified linesst.markdown("<div class='apk-credit'>APK created BY UMAID RANGREZ</div>", unsafe_allow_html=True)st.markdown("<div class='app-title'>🕌 DIFA E AHLESUNNAT SMART SYSTEM</div>", unsafe_allow_html=True)# --- 4. SIDEBAR NAVIGATION PANEL ---st.sidebar.markdown("## 🧭 Navigation Panel")if st.session_state['role'] == 'namzi':menu = st.sidebar.radio("Go To Panel:", ["📋 VIEW LIVE BOARD", "⚙️ OWNER LOGIN", "🕌 IMAAME LOGIN"])27 unmodified linesst.session_state['logged_in_masjid'] = Nonest.session_state['selected_aqaid_id'] = Nonest.session_state['selected_quran_folder_id'] = Nonest.session_state['selected_quran_sub_id'] = Nonest.session_state['selected_fiqh_folder_id'] = Nonest.rerun()# --- 5. OWNER REGISTRATION WORKSPACE ---if st.session_state['role'] == 'owner':st.markdown("### 🛠️ Owner Control Desk")with st.expander("➕ Register New Masjid (Full System)"):5 unmodified linesst.success(f"'{n_name}' registered successfully!")st.rerun()# --- 6. CORE APP INTERFACE CORE TABS ---all_masjids = run_query("SELECT id, name FROM masjids")tab_board, tab_quran, tab_aqaid, tab_fiqh = st.tabs(["📊 Masjid Time Board", "📖 Quran Shareef", "🛡️ Difa E Aqaid", "📝 Fiqh Wa Masail"])26 unmodified linesst.markdown(f"<div class='notice-box box-red'><div class='notice-title'>🚨 जनाज़ा जानकारी</div><div class='notice-desc'>{data.get('zanaza') or 'कोई सूचना नहीं है।'}</div></div>", unsafe_allow_html=True)st.markdown(f"<div class='notice-box box-green'><div class='notice-title'>🕋 ईद-उल-फ़ित्र (Yearly)</div><div class='notice-desc'>{data.get('yearly') or 'सूचना यहाँ लाइव दिखेगी।'}</div></div>", unsafe_allow_html=True)st.markdown(f"<div class='notice-box box-blue'><div class='notice-title'>📢 ओनर संदेश</div><div class='notice-desc'>{data.get('extra') or 'विशेष संदेश यहाँ देखें।'}</div></div>", unsafe_allow_html=True)st.markdown(f"<div class='notice-box box-pink'><div class='notice-title'>💗 स्पेशल अपडेट्स</div><div class='notice-desc'>{data.get('pink_box') or 'लाइev अपडेट्स यहाँ देखें।'}</div></div>", unsafe_allow_html=True)if data['bottom_img']: st.image(data['bottom_img'], use_column_width=True)if (st.session_state['role'] == 'owner') or (st.session_state['role'] == 'imam' and st.session_state['logged_in_masjid'] == selected_id):16 unmodified linesst.rerun()else: st.info("No masjids registered yet.")# --- TAB 2: ADVANCED QURAN SHAREEF MODULE (AUDIO/VOICE + DIRECT OR SUB-COLUMN FLEXIBILITY) ---with tab_quran:st.markdown("### 📖 Smart Quran Audio & Digital Column Board")q_folders = run_query("SELECT * FROM quran_folders")def display_quran_records(df_records):"""Helper to cleanly render text, audio players, download buttons, and bulk images."""for p_idx, p_row in df_records.iterrows():st.markdown(f"<div class='detail-container'><span class='counter-badge'>Entry ID: {p_row['id']}</span><h5>📖 {p_row['surah_verse']}</h5><p class='detail-text'>{p_row['manually_text']}</p></div>", unsafe_allow_html=True)# 1. Voice / Audio Playerif p_row['voice_audio']:st.audio(p_row['voice_audio'], format="audio/mp3")st.caption(f"🎵 Play Voice Track: {p_row['voice_name'] or 'Audio Clip'}")# 2. PDF Document Viewerif p_row['pdf_file']:st.info(f"📄 Attached Document: {p_row['pdf_name']}")st.download_button(label="📥 Download & Read Full PDF", data=p_row['pdf_file'], file_name=p_row['pdf_name'] or "document.pdf", mime="application/pdf", key=f"dl_q_{p_row['id']}")# 3. Bulk Pages/Imagesif p_row['quran_img']:q_img_list = p_row['quran_img'].split(b"##Q_IMG_SEP##")for sub_idx, q_img in enumerate(q_img_list):if q_img: st.image(q_img, caption=f"Page Image Scan {sub_idx+1}", use_column_width=True)# LEVEL 3: Inside a Specific Para/Sub-Columnif st.session_state['selected_quran_sub_id'] is not None:sub_id = st.session_state['selected_quran_sub_id']if st.button("⬅️ Back to Sub-Columns", key="back_qsub"):st.session_state['selected_quran_sub_id'] = Nonest.rerun()q_pages_df = run_query("SELECT * FROM quran_pages WHERE sub_folder_id=? ORDER BY id ASC", (sub_id,))if q_pages_df is not None and not q_pages_df.empty:display_quran_records(q_pages_df)else: st.info("Is section me abhi koi audio, pdf ya image upload nahi hai.")# LEVEL 2: Inside Main Column Folderelif st.session_state['selected_quran_folder_id'] is not None:q_fid = st.session_state['selected_quran_folder_id']if st.button("⬅️ Back to Main Columns Panel", key="back_qfolder"):st.session_state['selected_quran_folder_id'] = Nonest.rerun()cur_folder_name = q_folders[q_folders['id']==q_fid]['folder_name'].values[0]st.markdown(f"#### 📁 Folder: {cur_folder_name}")# Check if direct data (Full Quran style) exists right under this folderdirect_content_df = run_query("SELECT * FROM quran_pages WHERE main_folder_id=? AND (sub_folder_id IS NULL OR sub_folder_id = 0) ORDER BY id ASC", (q_fid,))if direct_content_df is not None and not direct_content_df.empty:st.markdown("📝 **Direct Full-Upload Content Found:**")display_quran_records(direct_content_df)st.markdown("---")# Also check for Para-wise sub-columnsst.markdown("📂 **Sub-Columns Inside This Folder:**")sub_folders_df = run_query("SELECT * FROM quran_sub_folders WHERE main_folder_id=?", (q_fid,))if sub_folders_df is not None and not sub_folders_df.empty:for idx, s_row in sub_folders_df.iterrows():if st.button(f"➔ {s_row['sub_folder_name']}", key=f"sub_btn_{s_row['id']}", use_container_width=True):st.session_state['selected_quran_sub_id'] = int(s_row['id'])st.rerun()else:if (direct_content_df is None or direct_content_df.empty):st.info("Is folder mein na hi koi direct content mila aur na hi koi sub-column.")# LEVEL 1: Main Grid Displayelse:if q_folders is not None and not q_folders.empty:q_cols = st.columns(2)1 unmodified linewith q_cols[idx % 2]:st.markdown(f"<div class='grid-card-box'><div class='grid-card-title'>📖 {row['folder_name']}</div></div>", unsafe_allow_html=True)if row['cover_img']: st.image(row['cover_img'], use_column_width=True)if st.button(f"Open Column: {row['folder_name']}", key=f"open_q_{row['id']}", use_container_width=True):st.session_state['selected_quran_folder_id'] = int(row['id'])st.rerun()st.markdown("<br>", unsafe_allow_html=True)else: st.info("Quran directory empty. Login as Owner to add content.")# OWNER CONTENT UPLOADER & RECORDER TERMINALif st.session_state['role'] == 'owner':st.markdown("---")st.markdown("#### 🛠️ Owner Advanced Voice & Content Desk")q_action = st.radio("Choose Action:", ["1. Create Main Column (Folder)","2. Create Sub-Column inside Main Column (e.g. Para 1)","3. Upload Voice, PDF or Bulk Images (Direct or in Sub-Column)","4. Delete/Wipe Quran Rows"], key="q_owner_action_v3")if q_action == "1. Create Main Column (Folder)":with st.form("q_f_add_v3", clear_on_submit=True):q_vname = st.text_input("Main Column Folder Title (e.g., Para Wise Quran or Full Quran 30 Para)")q_cover = st.file_uploader("Upload Identity Cover Photo", type=['jpg','png','jpeg'])if st.form_submit_button("Launch Main Folder") and q_vname:run_query("INSERT INTO quran_folders (folder_name, cover_img) VALUES (?, ?)", (q_vname, q_cover.getvalue() if q_cover else None), is_select=False)st.success("Launched Successfully!")st.rerun()elif q_action == "2. Create Sub-Column inside Main Column (e.g. Para 1)" and q_folders is not None and not q_folders.empty:target_main = st.selectbox("Select Main Folder:", q_folders['id'].tolist(), format_func=lambda x: q_folders[q_folders['id']==x]['folder_name'].values[0])with st.form("q_sub_add_v3", clear_on_submit=True):q_sub_name = st.text_input("Sub-Column/Para Title (e.g., Para 01)")if st.form_submit_button("Generate Sub-Column"):run_query("INSERT INTO quran_sub_folders (main_folder_id, sub_folder_name) VALUES (?, ?)", (target_main, q_sub_name), is_select=False)st.success("Sub-column setup enabled!")st.rerun()elif q_action == "3. Upload Voice, PDF or Bulk Images (Direct or in Sub-Column)" and q_folders is not None and not q_folders.empty:chosen_main_id = st.selectbox("1. Choose Target Main Folder:", q_folders['id'].tolist(), format_func=lambda x: q_folders[q_folders['id']==x]['folder_name'].values[0], key="sel_m_v3")# Fetch sub-folders if availablesub_pool = run_query("SELECT id, sub_folder_name FROM quran_sub_folders WHERE main_folder_id=?", (chosen_main_id,))sub_options = [(0, "🚫 No Sub-Column (Upload Directly into Main Folder)")]if sub_pool is not None and not sub_pool.empty:for s_idx, s_row in sub_pool.iterrows():sub_options.append((int(s_row['id']), f"📂 Into Sub-Column: {s_row['sub_folder_name']}"))chosen_sub_id = st.selectbox("2. Target Sub-Column Mode Selection:", [opt[0] for opt in sub_options], format_func=lambda x: next(o[1] for o in sub_options if o[0] == x))with st.form("upload_master_form_v3", clear_on_submit=True):v_title = st.text_input("Topic Context / Para Reference Title")v_text = st.text_area("Write Manual Text / Tarjuma Notes")v_audio = st.file_uploader("🎙️ Upload Voice Track / Audio File", type=['mp3', 'wav', 'm4a', 'aac'])v_pdf = st.file_uploader("📄 Attach Entire Book PDF File", type=['pdf'])v_photos = st.file_uploader("📸 Upload Bulk Scanned Page Images", type=['jpg','png','jpeg'], accept_multiple_files=True)if st.form_submit_button("🚀 INJECT ALL MEDIA LIVE"):combined_imgs = b""if v_photos: combined_imgs = b"##Q_IMG_SEP##".join([f.getvalue() for f in v_photos])audio_bytes = v_audio.getvalue() if v_audio else Noneaudio_name = v_audio.name if v_audio else Nonepdf_bytes = v_pdf.getvalue() if v_pdf else Nonepdf_name = v_pdf.name if v_pdf else Nonerun_query("""INSERT INTO quran_pages (main_folder_id, sub_folder_id, surah_verse, manually_text, quran_img, pdf_file, pdf_name, voice_audio, voice_name)VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)""",(chosen_main_id, chosen_sub_id if chosen_sub_id != 0 else None, v_title, v_text, combined_imgs, pdf_bytes, pdf_name, audio_bytes, audio_name), is_select=False)st.success("All Media Pack Uploaded Cleanly and Successfully!")st.rerun()elif q_action == "4. Delete/Wipe Quran Rows":del_level = st.radio("Select Wipe Out Operation Type:", ["Delete Single Content Item Row", "Wipe Complete Main Folder Block"])if del_level == "Delete Single Content Item Row":all_items = run_query("SELECT id, surah_verse FROM quran_pages")if all_items is not None and not all_items.empty:trg_row_id = st.selectbox("Select Entry Row ID to delete:", all_items['id'].tolist(), format_func=lambda x: f"ID: {x} - {all_items[all_items['id']==x]['surah_verse'].values[0]}")if st.button("🔴 Permanently Delete Data Row", type="primary"):run_query("DELETE FROM quran_pages WHERE id=?", (trg_row_id,), is_select=False)st.success("Row wiped out.")st.rerun()else:trg_fold_id = st.selectbox("Select Entire Main Folder to delete:", q_folders['id'].tolist(), format_func=lambda x: q_folders[q_folders['id']==x]['folder_name'].values[0])if st.button("🔴 CLEAR EVERYTHING INSIDE FOLDER", type="primary"):run_query("DELETE FROM quran_folders WHERE id=?", (trg_fold_id,), is_select=False)run_query("DELETE FROM quran_sub_folders WHERE main_folder_id=?", (trg_fold_id,), is_select=False)run_query("DELETE FROM quran_pages WHERE main_folder_id=?", (trg_fold_id,), is_select=False)st.success("Wiped all records.")st.session_state['selected_quran_folder_id'] = Nonest.session_state['selected_quran_sub_id'] = Nonest.rerun()# --- TAB 3: DYNAMIC MULTI-REFERENCE DIFA E AQAID ---with tab_aqaid:89 unmodified linesst.session_state['selected_aqaid_id'] = Nonest.rerun()# --- TAB 4: FIQH WA MASAIL (WAZU, GHUSL, FATEHA SYSTEM) ---with tab_fiqh:st.markdown("### 📝 Fiqh Wa Masail (Masail Directory)")fiqh_data = run_query("SELECT * FROM fiqh_folders")
app.py+163-85