minemaster01 commited on
Commit
ea499a0
·
verified ·
1 Parent(s): 896aef0

Upload 2 files

Browse files
Files changed (2) hide show
  1. app.py +267 -0
  2. requirements.txt +2 -0
app.py ADDED
@@ -0,0 +1,267 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import os
3
+ import json
4
+ import uuid
5
+ from datetime import datetime
6
+ from huggingface_hub import HfApi, create_repo
7
+
8
+ # Setup local storage
9
+ os.makedirs("uploaded_images", exist_ok=True)
10
+ os.makedirs("submissions", exist_ok=True)
11
+
12
+ # --- Hugging Face Configuration ---
13
+ HF_TOKEN = os.environ.get("Crowdsourcing")
14
+ DATASET_NAME = "1-800-LLMs/se-culture-dataset-results"
15
+ DATASET_CREATED = False
16
+
17
+ # --- Data for Dropdowns ---
18
+ states_by_country = {
19
+ "India": ["Andhra Pradesh", "Arunachal Pradesh", "Assam", "Bihar", "Chhattisgarh", "Goa", "Gujarat", "Haryana","Himachal Pradesh", "Jharkhand", "Karnataka", "Kerala", "Madhya Pradesh", "Maharashtra", "Manipur","Meghalaya", "Mizoram", "Nagaland", "Odisha", "Punjab", "Rajasthan", "Sikkim", "Tamil Nadu","Telangana", "Tripura", "Uttar Pradesh", "Uttarakhand", "West Bengal", "Andaman and Nicobar Islands","Chandigarh", "Dadra and Nagar Haveli and Daman and Diu", "Delhi", "Jammu and Kashmir", "Ladakh","Lakshadweep", "Puducherry"],
20
+ "Pakistan": ["Balochistan", "Khyber Pakhtunkhwa", "Punjab", "Sindh", "Islamabad Capital Territory", "Other"],
21
+ "Bangladesh": ["Barisal", "Chittagong", "Dhaka", "Khulnā", "Mymensingh", "Rajshahi", "Rangpur", "Sylhet"],
22
+ "Afghanistan": ["Badakhshan", "Badghis", "Baghlan", "Balkh", "Bamyan", "Daykundi", "Farah", "Faryab", "Ghazni","Ghor", "Helmand", "Herat", "Jowzjan", "Kabul", "Kandahar", "Kapisa", "Khost", "Kunar", "Kunduz","Laghman", "Logar", "Nangarhar", "Nimruz", "Nuristan", "Paktia", "Paktika", "Panjshir", "Parwan","Samangan", "Sar-e Pol", "Takhar", "Uruzgan", "Wardak", "Zabul"],
23
+ "Bhutan": ["Bumthang", "Chukha", "Dagana", "Gasa", "Haa", "Lhuentse", "Mongar", "Paro", "Pemagatshel", "Punakha","Samdrup Jongkhar", "Samtse", "Sarpang", "Thimphu", "Trashigang", "Trashiyangtse", "Trongsa", "Tsirang","Wangdue Phodrang", "Zhemgang"],
24
+ "Nepal": ["Bagmati", "Gandaki", "Karnali", "Koshi", "Lumbini", "Madhesh", "Sudurpashchim"],
25
+ "Sri Lanka": ["Central", "Eastern", "North Central", "Northern", "North Western", "Sabaragamuwa", "Southern","Uva", "Western"]
26
+ }
27
+
28
+ south_asian_languages = [
29
+ "Assamese", "Bengali", "Bhojpuri", "Bodo", "Dari", "Dzongkha", "Dogri", "Gujarati", "Hindi", "Kannada",
30
+ "Kashmiri", "Konkani", "Maithili", "Malayalam", "Marathi", "Meitei", "Nepali", "Odia", "Pashto", "Punjabi",
31
+ "Sanskrit", "Santali", "Sindhi", "Sinhala", "Tamil", "Telugu", "Tibetan", "Tulu", "Urdu", "OTHER"
32
+ ]
33
+
34
+ # --- Helper Functions ---
35
+
36
+ def setup_hf_dataset():
37
+ """Creates the Hugging Face dataset repository if it doesn't exist."""
38
+ global DATASET_CREATED
39
+ if not DATASET_CREATED and HF_TOKEN:
40
+ try:
41
+ api = HfApi()
42
+ create_repo(DATASET_NAME, repo_type="dataset", token=HF_TOKEN, exist_ok=True)
43
+ DATASET_CREATED = True
44
+ print(f"Dataset {DATASET_NAME} is ready on Hugging Face Hub.")
45
+ except Exception as e:
46
+ print(f"Error setting up Hugging Face dataset: {e}")
47
+ elif not HF_TOKEN:
48
+ print("Warning: HF_TOKEN not set. Submissions will be stored locally only.")
49
+
50
+ def update_country_dependents(country):
51
+ """
52
+ Updates the state dropdown, other state textbox, and other country textbox
53
+ based on the selected country.
54
+ """
55
+ # Logic for the state dropdown
56
+ if country in states_by_country:
57
+ state_update = gr.update(
58
+ choices=states_by_country[country],
59
+ label=f"State/Province in {country}:",
60
+ interactive=True,
61
+ value=None, # Reset selection
62
+ visible=True
63
+ )
64
+ other_state_update = gr.update(visible=False, value="") # Hide other state textbox
65
+ else:
66
+ # Hide state dropdown for "None" or "OTHER"
67
+ state_update = gr.update(
68
+ choices=[],
69
+ interactive=False,
70
+ value=None,
71
+ visible=False
72
+ )
73
+ # Show 'Other State' textbox ONLY if country is 'OTHER'
74
+ other_state_update = gr.update(visible=(country == "OTHER"))
75
+
76
+ # Logic for the 'Other Country' textbox visibility
77
+ other_country_update = gr.update(visible=(country == "OTHER"))
78
+
79
+ # Return updates for all three components
80
+ return state_update, other_country_update, other_state_update
81
+
82
+
83
+ def update_other_language_visibility(selected_language):
84
+ """Shows the 'Other Language' textbox only when 'OTHER' is selected."""
85
+ return gr.update(visible=(selected_language == "OTHER"))
86
+
87
+ def process_submission(input_img, language, country, state, city, se_asia_relevance, culture_knowledge,
88
+ native_caption, english_caption, code_mixed_caption, domain, email, other_language, other_country, other_state):
89
+ """Validates, saves, and uploads a user submission."""
90
+ warnings = {
91
+ "img": (not input_img, "<span style='color:red'>⚠️ Please upload an image.</span>"),
92
+ "lang": (not language or (language == "OTHER" and not other_language), "<span style='color:red'>⚠️ Please select or specify a language.</span>"),
93
+ "country": (not country or country == "None" or (country == "OTHER" and not other_country), "<span style='color:red'>⚠️ Please select or specify a country.</span>"),
94
+ "email": (not email, "<span style='color:red'>⚠️ Please provide your email.</span>"),
95
+ "relevance": (not se_asia_relevance, "<span style='color:red'>⚠️ Please select the cultural relevance.</span>"),
96
+ "knowledge": (not culture_knowledge, "<span style='color:red'>⚠️ Please select your knowledge source.</span>"),
97
+ "english": (not english_caption, "<span style='color:red'>⚠️ Please enter an English caption.</span>"),
98
+ "code_mixed": (not code_mixed_caption, "<span style='color:red'>⚠️ Please enter a code-mixed caption.</span>"),
99
+ }
100
+ if any(v[0] for v in warnings.values()):
101
+ return (
102
+ gr.update(visible=True, value=warnings["img"][1] if warnings["img"][0] else ""),
103
+ gr.update(visible=True, value=warnings["lang"][1] if warnings["lang"][0] else ""),
104
+ gr.update(visible=True, value=warnings["country"][1] if warnings["country"][0] else ""),
105
+ gr.update(visible=False),
106
+ gr.update(visible=True, value=warnings["email"][1] if warnings["email"][0] else ""),
107
+ gr.update(visible=True, value=warnings["relevance"][1] if warnings["relevance"][0] else ""),
108
+ gr.update(visible=True, value=warnings["knowledge"][1] if warnings["knowledge"][0] else ""),
109
+ gr.update(visible=False),
110
+ gr.update(visible=True, value=warnings["english"][1] if warnings["english"][0] else ""),
111
+ gr.update(visible=True, value=warnings["code_mixed"][1] if warnings["code_mixed"][0] else ""),
112
+ gr.update(visible=False), gr.update(visible=False), gr.update(visible=False),
113
+ gr.update(visible=False), gr.update(visible=False), gr.update(visible=False),
114
+ gr.update(visible=False), gr.update(visible=False)
115
+ )
116
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S_%f")
117
+ image_filename = f"{timestamp}.jpg"
118
+ image_path = os.path.join("uploaded_images", image_filename)
119
+ input_img.save(image_path)
120
+
121
+ final_language = other_language if language == "OTHER" else language
122
+ final_country = other_country if country == "OTHER" else country
123
+ final_state = other_state if country == "OTHER" else state
124
+
125
+ submission_data = {
126
+ "id": str(uuid.uuid4()), "timestamp": timestamp, "image_filename": image_filename,
127
+ "language": final_language, "country": final_country, "state": final_state, "city": city,
128
+ "se_asia_relevance": se_asia_relevance, "cultural_knowledge_source": culture_knowledge,
129
+ "native_caption": native_caption, "english_caption": english_caption,
130
+ "code_mixed_caption": code_mixed_caption, "domain": domain, "email": email,
131
+ }
132
+ json_filename = f"{timestamp}.json"
133
+ json_path = os.path.join("submissions", json_filename)
134
+ with open(json_path, "w") as f:
135
+ json.dump(submission_data, f, indent=2)
136
+
137
+ if HF_TOKEN:
138
+ try:
139
+ api = HfApi()
140
+ api.upload_file(path_or_fileobj=json_path, path_in_repo=f"data/{json_filename}", repo_id=DATASET_NAME, repo_type="dataset", token=HF_TOKEN)
141
+ api.upload_file(path_or_fileobj=image_path, path_in_repo=f"images/{image_filename}", repo_id=DATASET_NAME, repo_type="dataset", token=HF_TOKEN)
142
+ print(f"Successfully uploaded {json_filename} and {image_filename} to HF.")
143
+ except Exception as e:
144
+ print(f"Error uploading to Hugging Face Hub: {e}")
145
+
146
+ location_info = f"Location: {city}, {final_state}, {final_country}" if city and final_state else f"Location: {final_country}"
147
+
148
+ return (
149
+ gr.update(value="", visible=False), gr.update(value="", visible=False),
150
+ gr.update(value="", visible=False), gr.update(value="", visible=False),
151
+ gr.update(value="", visible=False), gr.update(value="", visible=False),
152
+ gr.update(value="", visible=False), gr.update(value="", visible=False),
153
+ gr.update(value="", visible=False), gr.update(value="", visible=False),
154
+ gr.update(value=input_img, visible=True), gr.update(value="✅ Submission successful!", visible=True),
155
+ gr.update(value=location_info, visible=True), gr.update(value=se_asia_relevance, visible=True),
156
+ gr.update(value=culture_knowledge, visible=True), gr.update(value=native_caption, visible=True),
157
+ gr.update(value=english_caption, visible=True), gr.update(value=domain, visible=True)
158
+ )
159
+
160
+ def clear_all_fields():
161
+ """Resets all input and output components in the UI."""
162
+ return (
163
+ None, "OTHER", "", "None", "", None, "", "", # Add "" for other_state_textbox
164
+ None, None, "", "", "", "", "",
165
+ gr.update(value="", visible=False), gr.update(value="", visible=False),
166
+ gr.update(value="", visible=False), gr.update(value="", visible=False),
167
+ gr.update(value="", visible=False), gr.update(value="", visible=False),
168
+ gr.update(value="", visible=False), gr.update(value="", visible=False),
169
+ gr.update(value="", visible=False), gr.update(value="", visible=False),
170
+ gr.update(visible=False, value=None), gr.update(visible=False, value=None),
171
+ gr.update(visible=False, value=None), gr.update(visible=False, value=None),
172
+ gr.update(visible=False, value=None), gr.update(visible=False, value=None),
173
+ gr.update(visible=False, value=None), gr.update(visible=False, value=None)
174
+ )
175
+
176
+ # --- Main Application ---
177
+
178
+ setup_hf_dataset()
179
+
180
+ with gr.Blocks(theme='1024m/1024m-1') as gradio_app:
181
+ gr.Markdown("# Multilingual Image Captions")
182
+ gr.Markdown("Please check the [annotation guidelines](https://www.google.com/) and the [discord channel](https://www.google.com/) before proceeding.")
183
+
184
+ with gr.Row():
185
+ with gr.Column(scale=1):
186
+ input_img = gr.Image(label="Upload an image", sources=['upload', 'webcam'], type="pil")
187
+ img_warning = gr.Markdown(visible=False)
188
+ language = gr.Dropdown(choices=south_asian_languages, label="Language:", interactive=True, value=south_asian_languages[-1])
189
+ lang_warning = gr.Markdown(visible=False)
190
+ other_language = gr.Textbox(label="Other Language:", info="If not listed above", visible=True)
191
+ countries = ["None", "India", "Pakistan", "Bangladesh", "Afghanistan", "Bhutan", "Nepal", "Sri Lanka", "OTHER"]
192
+ country_dropdown = gr.Dropdown(choices=countries, label="Country where the image was taken:", interactive=True, value="None")
193
+ country_warning = gr.Markdown(visible=False)
194
+ other_country = gr.Textbox(label="Other Country:", info="If not listed above", visible=False)
195
+ state_dropdown = gr.Dropdown(choices=[], label="State/Province (Optional but preferred):", interactive=False, visible=False)
196
+ other_state_textbox = gr.Textbox(label="Other State/Province:", info="If country is 'OTHER'", visible=False)
197
+ city_textbox = gr.Textbox(label="City (Optional but preferred):", placeholder="Enter city name")
198
+ city_warning = gr.Markdown(visible=False)
199
+ email_input = gr.Textbox(label="Your Email:", placeholder="Enter your email address", info="Used as unique contributor ID")
200
+ email_warning = gr.Markdown(visible=False)
201
+ with gr.Column(scale=1):
202
+ se_asia_relevance = gr.Radio(choices=["Yes. Unique to South Asia", "Yes, people will likely think of South Asia when seeing the picture, but it may have low degree of similarity to other cultures.", "Maybe, this culture did not originate from South Asia, but it's quite dominant in South Asia", "Not really. It has some affiliation to South Asia, but actually does not represent South Asia or has stronger affiliation to cultures outside South Asia", "No. Totally unrelated to South Asia"], label="Is the image culturally relevant in South Asia?")
203
+ relevance_warning = gr.Markdown(visible=False)
204
+ culture_knowledge = gr.Radio(choices=["I'm from this country/culture", "I checked online resources (e.g., Wikipedia, articles, blogs)"], label="How do you know about this culture?", info="Please do not consult LLMs (e.g., GPT-4o, Claude, Command-R, etc.)")
205
+ knowledge_warning = gr.Markdown(visible=False)
206
+ native_caption = gr.Textbox(label="Caption in Native Language (Optional but preferred):", placeholder="Enter caption in the native language (script only)")
207
+ native_warning = gr.Markdown(visible=False)
208
+ english_caption = gr.Textbox(label="English Caption:", placeholder="Enter caption in English (script only)")
209
+ english_warning = gr.Markdown(visible=False)
210
+ code_mixed_caption = gr.Textbox(label="Code-Mixed Caption:", placeholder="Enter caption in code-mixed (English script only)")
211
+ code_mixed_warning = gr.Markdown(visible=False)
212
+ domain = gr.Textbox(label="Domain (Optional but preferred):", placeholder="1-2 word description")
213
+
214
+ with gr.Row():
215
+ clear_btn = gr.Button("Clear")
216
+ submit_btn = gr.Button("Submit")
217
+
218
+ with gr.Row():
219
+ with gr.Column(scale=1):
220
+ output_img = gr.Image(label="Submitted Image", visible=False)
221
+ output_text = gr.Text(label="Submission Status", visible=False)
222
+ output_location = gr.Text(label="Location Information", visible=False)
223
+ with gr.Column(scale=1):
224
+ output_relevance = gr.Text(label="South Asia Cultural Relevance", visible=False)
225
+ output_knowledge = gr.Text(label="Cultural Knowledge Source", visible=False)
226
+ output_native = gr.Text(label="Native Language Caption", visible=False)
227
+ output_english = gr.Text(label="English Caption", visible=False)
228
+ output_domain = gr.Text(label="Domain", visible=False)
229
+
230
+ # Event bindings
231
+ language.change(update_other_language_visibility, inputs=language, outputs=other_language)
232
+
233
+ country_dropdown.change(
234
+ fn=update_country_dependents,
235
+ inputs=country_dropdown,
236
+ outputs=[state_dropdown, other_country, other_state_textbox]
237
+ )
238
+
239
+ submit_btn.click(
240
+ fn=process_submission,
241
+ inputs=[
242
+ input_img, language, country_dropdown, state_dropdown, city_textbox,
243
+ se_asia_relevance, culture_knowledge, native_caption, english_caption,
244
+ code_mixed_caption, domain, email_input, other_language, other_country,
245
+ other_state_textbox
246
+ ],
247
+ outputs=[
248
+ img_warning, lang_warning, country_warning, city_warning, email_warning,
249
+ relevance_warning, knowledge_warning, native_warning, english_warning, code_mixed_warning,
250
+ output_img, output_text, output_location,
251
+ output_relevance, output_knowledge, output_native, output_english, output_domain
252
+ ]
253
+ )
254
+
255
+ components_to_clear = [
256
+ input_img, language, other_language, country_dropdown, other_country, state_dropdown,
257
+ other_state_textbox, city_textbox, se_asia_relevance, culture_knowledge, native_caption,
258
+ english_caption, code_mixed_caption, domain, email_input,
259
+ img_warning, lang_warning, country_warning, city_warning, email_warning, relevance_warning,
260
+ knowledge_warning, native_warning, english_warning, code_mixed_warning,
261
+ output_img, output_text,
262
+ output_location, output_relevance, output_knowledge, output_native, output_english, output_domain
263
+ ]
264
+ clear_btn.click(fn=clear_all_fields, inputs=None, outputs=components_to_clear)
265
+
266
+ if __name__ == "__main__":
267
+ gradio_app.launch(debug=True)
requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ gradio==4.*
2
+ Pillow>=9.0.0