sathvikk commited on
Commit
aff7880
Β·
verified Β·
1 Parent(s): 5c51397

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +66 -64
src/streamlit_app.py CHANGED
@@ -1,68 +1,70 @@
1
  import streamlit as st
2
  import os
3
- import uuid
 
4
  from datetime import datetime
5
- from huggingface_hub import upload_file
6
- from streamlit_js_eval import streamlit_js_eval
7
 
8
- # Dataset repo details
9
- REPO_ID = "your-username/temple-submissions" # change to your repo
10
- HF_TOKEN = st.secrets["HF_TOKEN"] # must add in Hugging Face secrets
11
-
12
- st.set_page_config(page_title="Temple Submission", layout="centered")
13
-
14
- st.title("πŸ›• Temple History Submission")
15
-
16
- with st.form("temple_form", clear_on_submit=False):
17
- name = st.text_input("Temple Name")
18
- lang = st.text_input("Language")
19
- location = st.text_input("πŸ“ Location")
20
- latitude = st.text_input("Latitude")
21
- longitude = st.text_input("Longitude")
22
-
23
- st.markdown("#### πŸ“Ž Upload Media")
24
-
25
- image = st.file_uploader("Upload Image", type=["jpg", "jpeg", "png"])
26
- media = st.file_uploader("Upload Audio or Video", type=["mp3", "wav", "m4a", "mp4", "mov", "mpeg4"])
27
-
28
- if st.form_submit_button("πŸ“© Submit"):
29
- uid = str(uuid.uuid4())[:8]
30
- folder = f"{uid}_{datetime.now().strftime('%Y%m%d%H%M%S')}"
31
-
32
- os.makedirs("/tmp/" + folder, exist_ok=True)
33
-
34
- # Save info text
35
- info_file = f"/tmp/{folder}/info.txt"
36
- with open(info_file, "w", encoding="utf-8") as f:
37
- f.write(f"Temple Name: {name}\nLanguage: {lang}\nLocation: {location}\nLatitude: {latitude}\nLongitude: {longitude}")
38
-
39
- upload_file(info_file, f"{folder}/info.txt", repo_id=REPO_ID, repo_type="dataset", token=HF_TOKEN)
40
-
41
- if image:
42
- image_path = f"/tmp/{folder}/{image.name}"
43
- with open(image_path, "wb") as f:
44
- f.write(image.getbuffer())
45
- upload_file(image_path, f"{folder}/{image.name}", repo_id=REPO_ID, repo_type="dataset", token=HF_TOKEN)
46
-
47
- if media:
48
- media_path = f"/tmp/{folder}/{media.name}"
49
- with open(media_path, "wb") as f:
50
- f.write(media.getbuffer())
51
- upload_file(media_path, f"{folder}/{media.name}", repo_id=REPO_ID, repo_type="dataset", token=HF_TOKEN)
52
-
53
- st.success("βœ… Submission uploaded successfully!")
54
-
55
- # Auto location button
56
- js = streamlit_js_eval(js_expressions="navigator.geolocation.getCurrentPosition((loc) => { window.streamlitLatitude = loc.coords.latitude; window.streamlitLongitude = loc.coords.longitude; }, console.error)", key="geo")
57
- if js and js.get("window.streamlitLatitude"):
58
- st.session_state["latitude"] = js["window.streamlitLatitude"]
59
- st.session_state["longitude"] = js["window.streamlitLongitude"]
60
- st.experimental_rerun()
61
-
62
- if "latitude" in st.session_state:
63
- st.text_input("Latitude", value=str(st.session_state["latitude"]), key="lat_input")
64
- if "longitude" in st.session_state:
65
- st.text_input("Longitude", value=str(st.session_state["longitude"]), key="lon_input")
66
-
67
- if st.button("πŸ“ Auto Detect Location"):
68
- pass # triggers JS above
 
 
 
 
1
  import streamlit as st
2
  import os
3
+ import geocoder
4
+ import pandas as pd
5
  from datetime import datetime
 
 
6
 
7
+ # Create submissions folder if not exists
8
+ UPLOAD_FOLDER = "submissions"
9
+ os.makedirs(UPLOAD_FOLDER, exist_ok=True)
10
+
11
+ # CSV to track uploads
12
+ CSV_LOG = "submissions_log.csv"
13
+
14
+ # Title
15
+ st.title("πŸ“Έ Upload Image with Geo Coordinates")
16
+
17
+ # File uploader
18
+ uploaded_file = st.file_uploader("Upload an image", type=["jpg", "jpeg", "png"])
19
+
20
+ # Detect location on button click
21
+ if st.button("πŸ“ Detect Location"):
22
+ g = geocoder.ip('me')
23
+ if g.ok:
24
+ lat, lon = g.latlng
25
+ st.session_state['location'] = {'lat': lat, 'lon': lon}
26
+ st.success(f"πŸ“ Location Detected: ({lat}, {lon})")
27
+ else:
28
+ st.error("❌ Failed to detect location")
29
+
30
+ # Show current detected coordinates
31
+ if 'location' in st.session_state:
32
+ st.write("**Latitude:**", st.session_state['location']['lat'])
33
+ st.write("**Longitude:**", st.session_state['location']['lon'])
34
+
35
+ # Save file with timestamp and location
36
+ if uploaded_file and 'location' in st.session_state:
37
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
38
+ filename = f"{timestamp}_{uploaded_file.name}"
39
+ file_path = os.path.join(UPLOAD_FOLDER, filename)
40
+
41
+ # Save image
42
+ with open(file_path, "wb") as f:
43
+ f.write(uploaded_file.getbuffer())
44
+
45
+ st.success(f"βœ… Saved file as {filename}")
46
+
47
+ # Log to CSV
48
+ entry = {
49
+ "timestamp": timestamp,
50
+ "filename": filename,
51
+ "latitude": st.session_state['location']['lat'],
52
+ "longitude": st.session_state['location']['lon']
53
+ }
54
+
55
+ # Append to log
56
+ if os.path.exists(CSV_LOG):
57
+ df = pd.read_csv(CSV_LOG)
58
+ df = pd.concat([df, pd.DataFrame([entry])], ignore_index=True)
59
+ else:
60
+ df = pd.DataFrame([entry])
61
+ df.to_csv(CSV_LOG, index=False)
62
+
63
+ # Show the saved log
64
+ st.subheader("πŸ“„ Upload History")
65
+ st.dataframe(df)
66
+ else:
67
+ if not uploaded_file:
68
+ st.info("πŸ“ Please upload an image.")
69
+ elif 'location' not in st.session_state:
70
+ st.info("πŸ“ Click 'Detect Location' first.")