anhdt-dsai-02 commited on
Commit
7c8c1e0
·
verified ·
1 Parent(s): 5d8a5bb

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +122 -130
app.py CHANGED
@@ -1,120 +1,76 @@
1
  import gradio as gr
2
- from collections import defaultdict
3
- import random
4
- import pandas as pd
5
- import os
6
- import cloudinary
7
- import cloudinary.uploader
8
- from cloudinary.utils import cloudinary_url
9
- import io
10
- import time
11
  import requests
 
 
 
12
 
 
 
13
 
 
14
 
15
- # Configuration
16
- cloudinary.config(
17
- cloud_name = os.environ["cloud_name"],
18
- api_key = os.environ["api_key"] ,
19
- api_secret = os.environ["api_secret"] ,
20
- secure=True
21
- )
22
 
23
- from datetime import datetime
24
- import pytz
25
 
26
- # Define the GMT+7 timezone
27
- gmt_plus7 = pytz.timezone('Etc/GMT-7') # 'Etc/GMT-7' represents GMT+7
28
 
 
29
 
 
30
 
31
- def authenticate(user_id):
 
32
 
33
- url = "https://intern-api.imtaai.com/api/subnets/2/authenticate"
34
- headers = {
35
- "Content-Type": "application/json",
36
- "Accept": "application/json",
37
- "X-Public-Api-Key": os.environ['ADMIN']
38
- }
39
- payload = { "token": user_id }
40
- response = requests.post(url, json=payload, headers=headers)
41
 
42
- return response.status_code == 200
 
 
 
43
 
44
- def login(username, state, package):
45
- state[0] = username
46
- #package[0] = get_next_package(user_id=username)
47
- """
48
- #temp
49
- gr.Info("Login successfully. Welcome!")
50
- return f"Welcome, {username}!", gr.update(visible=False), gr.update(visible=True)
51
- #temp
52
- """
53
-
54
- # Authenticate user
55
- if authenticate(username):
56
- #user_sessions[username] = True
57
- gr.Info("Login successfully. Welcome!")
58
- return f"Welcome, {username}!", gr.update(visible=False), gr.update(visible=True)
59
- else:
60
- raise gr.Error("Token ID is invalid! Try again!")
61
- return "Invalid Token ID", gr.update(visible=True), gr.update(visible=False)
62
 
63
- def logout(username):
64
- # Log out user and reset session
65
- if username in user_sessions:
66
- del user_sessions[username]
67
- gr.Warning("You need to login to access this subnet and do task ⛔️!", duration=5)
68
- return "Logged out. Please log in again.", gr.update(visible=True), gr.update(visible=False)
69
-
70
- def get_image_bytes(image):
71
- if image is None:
72
- return "No image uploaded!"
73
-
74
- # Convert the image to bytes
75
- img_byte_arr = io.BytesIO()
76
- image.save(img_byte_arr, format='JPEG') # Save as PNG or desired format
77
- img_bytes = img_byte_arr.getvalue()
78
-
79
- return img_bytes
80
-
81
-
82
- # Define a function to handle image and text caption
83
- def process_image_and_caption(username_input, image, caption):
84
- #check image
85
- if image is None:
86
- gr.Warning("No image uploaded!", duration=5)
87
- return "No image uploaded!", image, caption
88
-
89
- # check caption
90
- if not caption.strip():
91
- gr.Warning("No caption uploaded!", duration=5)
92
- return "No caption uploaded!", image, caption
93
- # Get current time in GMT+7
94
- current_time = datetime.now(gmt_plus7)
95
-
96
- # Print the time
97
- time = current_time.strftime('-%Y-%m-%d-%H-%M-%S')
98
- name = username_input + time
99
- # Upload an image
100
- img_bytes = get_image_bytes(image)
101
- upload_image_result = cloudinary.uploader.upload(img_bytes, public_id = name, asset_folder = "image_for_captioning")
102
-
103
-
104
- # Upload caption
105
- # Convert to bytes
106
- caption_bytes = caption.encode('utf-8')
107
- # Create a byte array buffer (like a binary file stream)
108
- byte_buffer = io.BytesIO(caption_bytes)
109
- upload_caption_result = cloudinary.uploader.upload(byte_buffer, public_id = name, asset_folder = "caption", resource_type = "raw")
110
- send_score(username_input, 0.1)
111
- gr.Info("Submit successfully")
112
- return f'You just upload an Image with Caption: "{caption}" \nIntime {time}', None, None
113
-
114
- def send_score(user_id, score):
115
  max_retries = 10
116
  while max_retries > 0:
117
- url = "https://intern-api.imtaai.com/api/subnets/2/grade"
118
 
119
  payload = {
120
  "token": user_id,
@@ -136,50 +92,86 @@ def send_score(user_id, score):
136
  max_retries -= 1
137
  return False
138
 
139
- # Define the Gradio interface
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
140
  with gr.Blocks() as demo:
141
- state = gr.State([None])
142
- package = gr.State([None])
143
- # Login section
144
  with gr.Column(visible=True) as login_section:
145
  username_input = gr.Textbox(placeholder="Enter your token", label="Token ID", type="password")
146
  login_button = gr.Button("Login")
147
  login_output = gr.Textbox(label="Login Status", interactive=False)
148
 
149
- # Upload section (initially hidden)
 
150
  with gr.Column(visible=False) as upload_section:
151
- gr.Markdown("""### Upload hình ảnh (image) kèm chú thích (captioning).
152
- - Chú ý: Hình ảnh phải rõ nét, có nội dung; chú thích phải miêu tả chính xác nội dung của hình ảnh.
153
- <div style='color: red; font-size: 18px;'>Không đăng tải các nội dung cá nhân, nhạy cảm vì dữ liệu có thể được public cho cộng đồng trong lương lai</div>""")
154
- with gr.Row():
155
-
156
- image_input = gr.Image(type="pil", label="Upload Image")
157
- caption_input = gr.Textbox(label="Enter Caption")
158
 
159
- submit_button = gr.Button("Submit")
160
- output = gr.Textbox(label="Output")
161
 
162
- # Button functions
163
 
 
 
164
 
165
- submit_button.click(
166
- process_image_and_caption,
167
- inputs=[username_input, image_input, caption_input],
168
- outputs=[output, image_input, caption_input]
169
- )
170
- caption_input.submit(
171
- process_image_and_caption,
172
- inputs=[username_input, image_input, caption_input],
173
- outputs=[output, image_input, caption_input]
174
- )
175
 
176
-
 
 
 
 
 
 
 
 
 
 
 
 
 
177
  username_input.submit(
178
- login, inputs=[username_input, state, package], outputs=[login_output, login_section, upload_section] #, translation_section, en_input, vi_input]
179
  )
180
  login_button.click(
181
- login, inputs=[username_input, state, package], outputs=[login_output, login_section, upload_section] #, translation_section, en_input, vi_input]
182
  )
183
 
 
184
 
185
- demo.launch(debug=True)
 
 
 
1
  import gradio as gr
 
 
 
 
 
 
 
 
 
2
  import requests
3
+ import json
4
+ import os
5
+ from datasets import load_dataset
6
 
7
+ from pymongo.mongo_client import MongoClient
8
+ from pymongo.server_api import ServerApi
9
 
10
+ db_password = os.environ["db_password"]
11
 
12
+ uri = f"mongodb+srv://tuna:{db_password}@tuna.ixw4ff2.mongodb.net/?appName=tuna"
 
 
 
 
 
 
13
 
14
+ # Create a new client and connect to the server
15
+ client = MongoClient(uri, server_api=ServerApi('1'))
16
 
17
+ database = client['valid_image_caption']
18
+ collection = database["log_valid"]
19
 
20
+ ds = load_dataset("anhdt-dsai-02/test_image_dataset_1_2_3_4", token = os.environ['token_huggingface'] )
21
 
22
+ def get_similar_captions(caption):
23
 
24
+ url = "https://anhdt-dsai-02-caption-retrieval.hf.space/retrieval"
25
+ params = {"caption": caption}
26
 
27
+ try:
28
+ response = requests.post(url, params=params, headers={"accept": "application/json"})
29
+ response.raise_for_status() # Raises an HTTPError for bad responses (4xx and 5xx)
30
+ data = response.json() # Assuming response is JSON
 
 
 
 
31
 
32
+ except requests.exceptions.RequestException as e:
33
+ print(f"Request failed: {e}")
34
+ except ValueError:
35
+ print("Failed to parse JSON response")
36
 
37
+ return data
38
+
39
+
40
+
41
+ index = 0
42
+
43
+ def create_question():
44
+ global index
45
+ print(index)
46
+ caption = ds['train'][index]["caption"] # delete [0]
47
+ caption_lst = get_similar_captions(caption)
48
+ #id_lst = [pair['id'] for pair in caption_lst]
49
+
50
+ id_lst = [int(pair['id']/10) for pair in caption_lst]
 
 
 
 
51
 
52
+ images = [ds["train"][id]['image'] for id in id_lst]
53
+
54
+ index += 1
55
+
56
+ return caption, images, id_lst
57
+
58
+ def on_select(evt: gr.SelectData):
59
+ idx = evt.index
60
+ return idx
61
+
62
+ # Function to handle user selection
63
+ def process_answer(user_id, caption, selected_image, ids):
64
+
65
+ collection.insert_one({ "used_id" : user_id, "caption": caption, "ids": ids, "choice": selected_image})
66
+ send_score(user_id, 0.1)
67
+
68
+ return create_question()
69
+
70
+ def send_score(user_id, score = 0.1):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
71
  max_retries = 10
72
  while max_retries > 0:
73
+ url = os.environ['api_url'] + "grade"
74
 
75
  payload = {
76
  "token": user_id,
 
92
  max_retries -= 1
93
  return False
94
 
95
+ def authenticate(user_id):
96
+
97
+ url = os.environ['api_url'] + "authenticate"
98
+ headers = {
99
+ "Content-Type": "application/json",
100
+ "Accept": "application/json",
101
+ "X-Public-Api-Key": os.environ['ADMIN']
102
+ }
103
+ payload = { "token": user_id }
104
+ response = requests.post(url, json=payload, headers=headers)
105
+
106
+ return response.status_code == 200
107
+
108
+
109
+
110
+ def login(username):
111
+ #state[0] = username
112
+ #package[0] = get_next_package(user_id=username)
113
+ """
114
+ #temp
115
+ gr.Info("Login successfully. Welcome!")
116
+ return f"Welcome, {username}!", gr.update(visible=False), gr.update(visible=True)
117
+ #temp
118
+ """
119
+
120
+ # Authenticate user
121
+ if authenticate(username):
122
+ #user_sessions[username] = True
123
+ gr.Info("Login successfully. Welcome!")
124
+ return f"Welcome, {username}!", gr.update(visible=False), gr.update(visible=True), *create_question()
125
+ else:
126
+ raise gr.Error("Token ID is invalid! Try again!")
127
+ return "Invalid Token ID", gr.update(visible=True), gr.update(visible=False)
128
+
129
+ # Gradio UI
130
  with gr.Blocks() as demo:
 
 
 
131
  with gr.Column(visible=True) as login_section:
132
  username_input = gr.Textbox(placeholder="Enter your token", label="Token ID", type="password")
133
  login_button = gr.Button("Login")
134
  login_output = gr.Textbox(label="Login Status", interactive=False)
135
 
136
+
137
+ # Upload section (initially hidden)
138
  with gr.Column(visible=False) as upload_section:
139
+ caption = gr.State()
140
+ images = gr.State()
141
+ id_lst = gr.State()
142
+ # Store the selected image path
143
+ selected_image = gr.State()
 
 
144
 
 
 
145
 
146
+ #caption.value, images.value, id_lst.value = create_question()
147
 
148
+ gr.Markdown("**Đâu là hình ảnh phù hợp với caption sau:**")
149
+ markdown = gr.Markdown(caption.value)
150
 
 
 
 
 
 
 
 
 
 
 
151
 
152
+
153
+ # Display images in a Gallery
154
+ gallery = gr.Gallery(value=images.value, label="Ấn vào hình ảnh để chọn sau đó Submit", columns = 4)
155
+
156
+ # Use the Gallery's select event to update the selected image
157
+ gallery.select(fn=on_select, outputs=selected_image)
158
+
159
+ # Submit button
160
+ submit_button = gr.Button("Submit")
161
+
162
+ # Output message
163
+ output_message = gr.Textbox(label="Result")
164
+
165
+ # Action in Login Section
166
  username_input.submit(
167
+ login, inputs=[username_input], outputs=[login_output, login_section, upload_section, markdown, gallery, id_lst] #, translation_section, en_input, vi_input]
168
  )
169
  login_button.click(
170
+ login, inputs=[username_input], outputs=[login_output, login_section, upload_section, markdown, gallery, id_lst] #, translation_section, en_input, vi_input]
171
  )
172
 
173
+ # Link the submit button to the processing function
174
 
175
+ submit_button.click(fn=process_answer, inputs=[username_input, caption, selected_image, id_lst], outputs=[markdown, gallery, id_lst])
176
+ # Launch the app
177
+ demo.launch(debug = True)