MingDoan commited on
Commit
3a63794
·
1 Parent(s): 52c0de0

feat: Big Update

Browse files
.gitattributes ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
.gitignore CHANGED
@@ -1 +1,6 @@
1
- env/
 
 
 
 
 
 
1
+ # Python specific
2
+ env/
3
+ __pycache__/
4
+
5
+ # Huggingface Gradio auto-created folder
6
+ flagged/
README.md CHANGED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Ai Service Inference
3
+ emoji: 🐠
4
+ colorFrom: purple
5
+ colorTo: pink
6
+ sdk: gradio
7
+ sdk_version: 4.15.0
8
+ app_file: app.py
9
+ pinned: true
10
+ ---
app.py CHANGED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ from views import create_interface
2
+
3
+ ui = create_interface()
4
+
5
+ if __name__ == "__main__":
6
+ ui.launch()
controllers/chat.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import time
2
+ from services.api_service import post_data
3
+ from controllers.fw import get_fw_query_params
4
+
5
+
6
+ def format_response(message: str):
7
+ return message.replace("\\n", "\n")
8
+
9
+
10
+ def chat_controller(prompt: str, histories: list[list], fw_option: str = 'none'):
11
+ # Format histories
12
+ f_histories = []
13
+ for history in histories:
14
+ f_histories.append({
15
+ "role": "user",
16
+ "content": history[0]
17
+ })
18
+ f_histories.append({
19
+ "role": "assistant",
20
+ "content": history[1]
21
+ })
22
+ # Send request
23
+ request_data = {
24
+ "prompt": prompt,
25
+ "histories": f_histories
26
+ }
27
+ response = post_data(
28
+ f"/api/chats/{get_fw_query_params(fw_option)}", json=request_data)
29
+ if response is None:
30
+ return None
31
+ message = format_response(response['message'])
32
+ # Yielding response
33
+ for i in range(len(message)):
34
+ time.sleep(0.03)
35
+ yield message[: i+1]
controllers/config.py ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from controllers.fw import add_fw_option, del_fw_option, fetch_fw_options
2
+
3
+
4
+ def on_fw_add_btn_click(url: str):
5
+ add_fw_option(url)
6
+ # Fetch new options
7
+ return fetch_fw_options(), ""
8
+
9
+
10
+ def on_del_btn_click(url: str):
11
+ # Fetch options
12
+ options = fetch_fw_options()
13
+ # Delete option
14
+ del_fw_option(list(options.keys()).index(url))
15
+ # Remove from options
16
+ options.pop(url)
17
+ # Return new options
18
+ return options, ""
controllers/fd.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from PIL import Image
2
+ import numpy as np
3
+ import cv2 as cv
4
+ from services.api_service import post_data
5
+ from controllers.utils import image_to_bytes
6
+ from controllers.fw import get_fw_query_params
7
+
8
+
9
+ def draw_bboxs(image: Image, faces: list, color: str):
10
+ np_image = np.array(image)
11
+ for face in faces:
12
+ bbox = face['bbox']
13
+ x, y, w, h = bbox['x'], bbox['y'], bbox['width'], bbox['height']
14
+ # Convert hex to rgb
15
+ hex = color[1:]
16
+ rgb = tuple(int(hex[i:i+2], 16) for i in (0, 2, 4))
17
+ cv.rectangle(np_image, (x, y), (x + w, y + h), rgb, 2)
18
+ return np_image
19
+
20
+
21
+ def fd_controller(image: Image, model: str, color: str, fw_option: str = 'none'):
22
+ request_data = {
23
+ "image": image_to_bytes(image),
24
+ "model": model
25
+ }
26
+ response = post_data(
27
+ f"/api/fd/{get_fw_query_params(fw_option)}", files=request_data)
28
+ if response is None:
29
+ return None
30
+ faces = response['faces']
31
+ image = draw_bboxs(image, faces, color)
32
+ return image, faces
controllers/fw.py CHANGED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from services.api_service import get_data, post_data, delete_data
2
+
3
+
4
+ # Forward query params
5
+ def get_fw_query_params(fw_option: str):
6
+ if fw_option == 'none':
7
+ return ''
8
+ if fw_option == 'auto':
9
+ return '?fw=auto'
10
+ else:
11
+ return '?fw=' + fw_option
12
+
13
+
14
+ def fetch_fw_options(to_list=False) -> dict:
15
+ response = get_data("/service/fw/")
16
+ if to_list:
17
+ return [option['url'] for option in response['fw']]
18
+ fw_servers = {}
19
+ for res in response['fw']:
20
+ fw_servers[res['url']] = res['tasks']
21
+ return fw_servers
22
+
23
+
24
+ def add_fw_option(url: str):
25
+ request_data = {
26
+ "url": url
27
+ }
28
+ post_data("/service/fw/", json=request_data)
29
+
30
+
31
+ def del_fw_option(index: int):
32
+ request_data = {
33
+ "index": index
34
+ }
35
+ delete_data("/service/fw/", json=request_data)
controllers/rembg.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from PIL import Image
2
+ from controllers.utils import image_to_bytes, bytes_to_image
3
+ from services.api_service import post_data
4
+ from controllers.fw import get_fw_query_params
5
+
6
+
7
+ def rembg_controller(image: Image, resolution: str = 'original', fw_option: str = 'none'):
8
+ # Downscale image
9
+ if resolution != 'original':
10
+ if resolution == 'low':
11
+ resolution = image.size[0] / 4
12
+ elif resolution == 'high':
13
+ resolution = image.size[0] / 2
14
+ image.thumbnail((int(resolution), int(resolution)))
15
+ # Send image
16
+ request_data = {
17
+ "image": image_to_bytes(image)
18
+ }
19
+ response = post_data(
20
+ f"/api/rembg/{get_fw_query_params(fw_option)}", files=request_data, parse_json=False)
21
+ if response is None:
22
+ return None
23
+ return bytes_to_image(response)
controllers/utils.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import io
2
+ from PIL import Image
3
+
4
+
5
+ # Convert image to bytes
6
+ def image_to_bytes(image: Image):
7
+ img_byte_arr = io.BytesIO()
8
+ image.save(img_byte_arr, format='PNG')
9
+ return img_byte_arr.getvalue()
10
+
11
+
12
+ def bytes_to_image(image_bytes: bytes):
13
+ return Image.open(io.BytesIO(image_bytes))
services/api_service.py CHANGED
@@ -1,5 +1,5 @@
1
  from requests import get, post, put, delete
2
- from utils.constants import API_ENDPOINT
3
 
4
 
5
  def get_data(url, params=None, parse_json=True):
@@ -41,10 +41,10 @@ def put_data(url, json=None, parse_json=True):
41
  return None
42
 
43
 
44
- def delete_data(url, parse_json=True):
45
  if url.startswith("/"):
46
  url = API_ENDPOINT + url
47
- response = delete(url)
48
  if response.status_code == 200:
49
  if parse_json:
50
  return response.json()
 
1
  from requests import get, post, put, delete
2
+ from utilities.constants import API_ENDPOINT
3
 
4
 
5
  def get_data(url, params=None, parse_json=True):
 
41
  return None
42
 
43
 
44
+ def delete_data(url, json=None, parse_json=True):
45
  if url.startswith("/"):
46
  url = API_ENDPOINT + url
47
+ response = delete(url, json=json)
48
  if response.status_code == 200:
49
  if parse_json:
50
  return response.json()
services/state.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from utilities.constants import FW_DEFAULT_OPTION
2
+
3
+
4
+ class AppState():
5
+ def __init__(self):
6
+ self._state = {}
7
+
8
+ def get(self, key):
9
+ return self._state.get(key)
10
+
11
+ def set(self, key, value):
12
+ self._state[key] = value
13
+
14
+
15
+ # Create app state
16
+ app_state = AppState()
17
+
18
+ # Initialize app state
19
+ app_state.set('fw_option', FW_DEFAULT_OPTION)
utilities/constants.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ API_ENDPOINT = "https://gdscfptu-ai-service-hf.hf.space"
2
+ FW_DEFAULT_OPTION = "auto"
3
+ CHAT_EXAMPLES = ["Where should I go in Da Nang?",
4
+ "Best destinations in Quy Nhon"]
5
+ FD_DROPDOWN_CHOICES = ["mtcnn", "hog"]
6
+ FW_RADIO_CHOICES = ['none', 'auto']
7
+ REMBG_DROPDOWN_CHOICES = ["original", "high", "low"]
utils/constants.py DELETED
@@ -1,2 +0,0 @@
1
- API_ENDPOINT = "https://gdscfptu-ai-service-hf.hf.space"
2
- FW_DEFAULT_OPTION = "none"
 
 
 
views/__init__.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ # Import Interfaces
3
+ from .rembg import rembg_interface
4
+ from .fd import fd_interface
5
+ from .chat import chat_interface
6
+ from .config import config_interface
7
+
8
+
9
+ def create_interface():
10
+ rembg_ui = rembg_interface()
11
+ fd_ui = fd_interface()
12
+ chat_ui = chat_interface()
13
+ config_ui = config_interface()
14
+
15
+ return gr.TabbedInterface(
16
+ title="GDSC AI Service Inference",
17
+ interface_list=[rembg_ui, fd_ui, chat_ui.queue(), config_ui],
18
+ tab_names=[rembg_ui.title, fd_ui.title,
19
+ chat_ui.title, config_ui.title],
20
+ )
views/chat.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from controllers.chat import chat_controller
3
+ from services.state import app_state
4
+
5
+ CHAT_EXAMPLES = ["Where should I go in Da Nang?",
6
+ "Best destinations in Quy Nhon"]
7
+
8
+
9
+ def chats_yielding(prompt: str, histories: list[list]):
10
+ for msg in chat_controller(prompt, histories, app_state.get('fw_option')):
11
+ yield msg
12
+
13
+
14
+ def chat_interface():
15
+ return gr.ChatInterface(
16
+ title="Chat AI",
17
+ fn=chats_yielding,
18
+ examples=CHAT_EXAMPLES,
19
+ retry_btn=None,
20
+ undo_btn=None
21
+ )
views/config.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from controllers.config import on_del_btn_click, on_fw_add_btn_click
3
+ from controllers.fw import fetch_fw_options
4
+ from utilities.constants import FW_RADIO_CHOICES, FW_DEFAULT_OPTION
5
+
6
+
7
+ def config_interface():
8
+ with gr.Blocks() as ui:
9
+ gr.Markdown("### Forwarding Endpoint")
10
+ radio_btn = gr.Radio(choices=FW_RADIO_CHOICES, value=FW_DEFAULT_OPTION,
11
+ label="Select Forwarding Option")
12
+ fw_list = gr.Label(value=fetch_fw_options(), # TODO change to function
13
+ label="Current Endpoints", every=2)
14
+ with gr.Column():
15
+ input_box = gr.Textbox(label="Forwarding Endpoint",
16
+ placeholder="https://...")
17
+ with gr.Row():
18
+ add_btn = gr.Button(value="Add Endpoint", variant="secondary")
19
+ del_btn = gr.Button(value="Delete Endpoint", variant="stop")
20
+ gr.Markdown("### OpenAI API Key")
21
+ with gr.Column():
22
+ input_box2 = gr.Textbox(
23
+ label="OpenAI API Key", placeholder="sk_...")
24
+ with gr.Row():
25
+ add_btn2 = gr.Button(value="Add Key", variant="secondary")
26
+ del_btn2 = gr.Button(value="Reset Key", variant="stop")
27
+
28
+ # Assign actions
29
+ add_btn.click(
30
+ fn=on_fw_add_btn_click,
31
+ inputs=[input_box],
32
+ outputs=[fw_list, input_box]
33
+ )
34
+ del_btn.click(
35
+ fn=on_del_btn_click,
36
+ inputs=[input_box],
37
+ outputs=[fw_list, input_box]
38
+ )
39
+
40
+ ui.title = "Configuration"
41
+ return ui
views/fd.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from utilities.constants import FD_DROPDOWN_CHOICES
3
+ from controllers.fd import fd_controller
4
+ from services.state import app_state
5
+
6
+
7
+ def fd_interface():
8
+ return gr.Interface(
9
+ title="Face Detection",
10
+ fn=lambda model, image, color: fd_controller(
11
+ image, model, color, app_state.get('fw_option')),
12
+ inputs=[
13
+ gr.Dropdown(choices=FD_DROPDOWN_CHOICES,
14
+ value=FD_DROPDOWN_CHOICES[0], label="Select Model. *Not affect in forwarding mode*"),
15
+ gr.Image(type="pil", label="Input Image"),
16
+ gr.ColorPicker(label="Box Color")
17
+ ],
18
+ outputs=[
19
+ gr.Image(type="pil", label="Output Image"),
20
+ gr.JSON(label="Output Boxes")
21
+ ],
22
+ flagging_options=[]
23
+ )
views/rembg.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from controllers.rembg import rembg_controller
3
+ from services.state import app_state
4
+ from utilities.constants import REMBG_DROPDOWN_CHOICES
5
+
6
+
7
+ def rembg_interface():
8
+ return gr.Interface(
9
+ title="Remove Background",
10
+ fn=lambda resolution, image: rembg_controller(
11
+ image, resolution, app_state.get('fw_option')),
12
+ inputs=[
13
+ gr.Dropdown(choices=REMBG_DROPDOWN_CHOICES,
14
+ value=REMBG_DROPDOWN_CHOICES[0], label="Resolution"),
15
+ gr.Image(type="pil", label="Input Image")
16
+ ],
17
+ outputs=[
18
+ gr.Image(type="pil", label="Output Image")
19
+ ],
20
+ flagging_options=[]
21
+ )