File size: 5,220 Bytes
8a7a466
8bb74bc
 
8f31dd0
8bb74bc
 
8f31dd0
 
8bb74bc
 
 
496c07a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8bb74bc
8f31dd0
 
 
 
8bb74bc
 
 
8f31dd0
 
 
8bb74bc
8f31dd0
 
 
8bb74bc
 
8f31dd0
 
 
 
8bb74bc
 
 
 
 
 
 
 
 
 
 
 
8a7a466
8bb74bc
 
 
 
 
496c07a
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import streamlit as st
import json
import os
import io
import base64
import boto3
import time
from PIL import Image
import firebase_admin
from firebase_admin import credentials, auth, firestore

# πŸš€ Load Secrets from Hugging Face Secrets
FIREBASE_CONFIG = json.loads(os.getenv("FIREBASE_CONFIG", "{}"))
AWS_ACCESS_KEY = os.getenv("AWS_ACCESS_KEY")
AWS_SECRET_KEY = os.getenv("AWS_SECRET_KEY")
S3_BUCKET_NAME = os.getenv("S3_BUCKET_NAME", "food-image-crowdsourcing")
DYNAMODB_TABLE = os.getenv("DYNAMODB_TABLE", "image_metadata")  # βœ… Corrected Table Name

# βœ… Initialize Firebase Admin SDK
if FIREBASE_CONFIG:
    cred = credentials.Certificate(FIREBASE_CONFIG)
    firebase_admin.initialize_app(cred)
else:
    st.error("⚠️ Firebase configuration is missing! Please check HF Secrets.")

# βœ… Initialize AWS Services (S3 & DynamoDB)
s3 = boto3.client(
    "s3",
    aws_access_key_id=AWS_ACCESS_KEY,
    aws_secret_access_key=AWS_SECRET_KEY,
)

dynamodb = boto3.resource(
    "dynamodb",
    aws_access_key_id=AWS_ACCESS_KEY,
    aws_secret_access_key=AWS_SECRET_KEY,
)
metadata_table = dynamodb.Table(DYNAMODB_TABLE)  # βœ… Corrected Table Name

# πŸ”Ή Initialize Session State for Tokens
if "tokens" not in st.session_state:
    st.session_state.tokens = 0
if "user_email" not in st.session_state:
    st.session_state.user_email = None

# πŸ”Ή UI - Page Title
st.title("πŸ“· Food Crowdsourcing Research App")
st.write("Help our research by uploading food images! Earn tokens for future app use.")

# βœ… **User Authentication Section**
st.sidebar.header("πŸ”‘ User Authentication")

auth_choice = st.sidebar.radio("Select an option", ["Login", "Sign Up", "Logout"])

if auth_choice == "Sign Up":
    with st.sidebar.form("signup_form"):
        email = st.text_input("Email")
        password = st.text_input("Password", type="password")
        submit_button = st.form_submit_button("Sign Up")

    if submit_button:
        try:
            user = auth.create_user(email=email, password=password)
            st.success(f"βœ… Account created! Now login with {email}.")
        except Exception as e:
            st.error(f"⚠️ {str(e)}")

if auth_choice == "Login":
    with st.sidebar.form("login_form"):
        email = st.text_input("Email")
        password = st.text_input("Password", type="password")
        submit_button = st.form_submit_button("Login")

    if submit_button:
        try:
            user = auth.get_user_by_email(email)
            st.session_state.user_email = email
            st.success(f"βœ… Welcome back, {email}!")
        except Exception as e:
            st.error(f"⚠️ {str(e)}")

if auth_choice == "Logout":
    if st.session_state.user_email:
        st.session_state.user_email = None
        st.success("βœ… Logged out successfully!")

# πŸ”Ή **Ensure User is Logged In**
if not st.session_state.user_email:
    st.warning("⚠️ Please log in to upload images.")
    st.stop()

# βœ… **Image Upload Section**
uploaded_file = st.file_uploader("πŸ“Έ Upload a food image", type=["jpg", "png", "jpeg"])

# βœ… **Terms & Conditions**
st.markdown("### **Terms & Conditions**")
st.write(
    "By uploading an image, you agree to transfer full copyright to the research team for AI training purposes. "
    "You are responsible for ensuring you own the image and it does not violate any copyright laws. "
    "We do not guarantee when tokens will be redeemable. Keep track of your user ID."
)
st.checkbox("I agree to the terms and conditions", key="terms_accepted")

# βœ… **Process and Upload Image**
if uploaded_file and st.session_state.terms_accepted:
    image = Image.open(uploaded_file)
    st.image(image, caption="Uploaded Image", use_column_width=True)

    # Show Original Size
    st.write(f"πŸ“ Original size: {image.size}")

    # Convert PNG to JPEG if needed
    if image.format == "PNG":
        image = image.convert("RGB")

    # Resize image to max 1024x1024 px
    MAX_SIZE = (1024, 1024)
    image.thumbnail(MAX_SIZE)

    # Convert Image to Bytes
    img_bytes = io.BytesIO()
    image.save(img_bytes, format="JPEG", quality=80)  # Reduce quality to save space
    img_bytes.seek(0)

    # πŸ”Ή Generate Unique File Name
    file_name = f"raw-uploads/{st.session_state.user_email}_{int(time.time())}.jpg"

    # βœ… **Upload to S3**
    try:
        s3.put_object(
            Bucket=S3_BUCKET_NAME,
            Key=file_name,
            Body=img_bytes.getvalue(),
            ContentType="image/jpeg",
        )
        st.success("βœ… Image uploaded successfully to S3!")

        # βœ… **Store Metadata in DynamoDB**
        metadata_table.put_item(
            Item={
                "user_email": st.session_state.user_email,
                "file_name": file_name,
                "upload_time": int(time.time()),
            }
        )

        # πŸŽ‰ **Reward Tokens**
        st.session_state.tokens += 1
        st.write("πŸŽ‰ You earned **1 token** for uploading!")
        st.success(f"πŸ”’ Total tokens: {st.session_state.tokens}")

    except Exception as e:
        st.error(f"⚠️ Failed to upload image: {str(e)}")

# βœ… **Future: Annotation for Additional Token**
# If annotation is provided, reward another token