top001 commited on
Commit
c71ddef
·
verified ·
1 Parent(s): 70c9623

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +77 -63
app.py CHANGED
@@ -8,6 +8,13 @@ import numpy as np
8
  import onnxruntime as ort
9
  from PIL import Image
10
  from huggingface_hub import hf_hub_download
 
 
 
 
 
 
 
11
 
12
  def _yield_tags_from_txt_file(txt_file: str):
13
  with open(txt_file, 'r') as f:
@@ -39,17 +46,26 @@ def image_preprocess(image: Image.Image) -> np.ndarray:
39
  height_pad_right = 512 - f_height - height_pad_left
40
  width_pad_left = (512 - f_width) // 2
41
  width_pad_right = 512 - f_width - width_pad_left
42
- data = np.pad(data, ((height_pad_left, height_pad_right), (width_pad_left, width_pad_right), (0, 0)),
43
- mode='constant', constant_values=0.0)
 
 
 
 
44
 
45
  assert data.shape == (512, 512, 3), f'Shape (512, 512, 3) expected, but {data.shape!r} found.'
46
  return data.reshape((1, 512, 512, 3)) # B x H x W x C
47
 
48
  RE_SPECIAL = re.compile(r'([\\()])')
49
 
50
- def image_to_deepdanbooru_tags(image: Image.Image, threshold: float,
51
- use_spaces: bool, use_escape: bool, include_ranks: bool, score_descend: bool) \
52
- -> Tuple[str, Mapping[str, float]]:
 
 
 
 
 
53
  tags = get_deepdanbooru_tags()
54
  session = get_deepdanbooru_onnx()
55
  input_name = session.get_inputs()[0].name
@@ -78,64 +94,62 @@ def image_to_deepdanbooru_tags(image: Image.Image, threshold: float,
78
 
79
  return output_text, filtered_tags
80
 
81
- if __name__ == '__main__':
82
- import io
83
- from fastapi import FastAPI, File, UploadFile
84
- from fastapi.responses import JSONResponse
85
- from fastapi.middleware.cors import CORSMiddleware
86
-
87
- with gr.Blocks() as demo:
88
- with gr.Row():
89
- with gr.Column():
90
- gr_input_image = gr.Image(type='pil', label='Original Image')
91
- gr_threshold = gr.Slider(0.0, 1.0, 0.5, label='Tagging Confidence Threshold')
92
- with gr.Row():
93
- gr_space = gr.Checkbox(value=False, label='Use Space Instead Of _')
94
- gr_escape = gr.Checkbox(value=True, label='Use Text Escape')
95
- gr_confidence = gr.Checkbox(value=False, label='Keep Confidences')
96
- gr_order = gr.Checkbox(value=True, label='Descend By Confidence')
97
-
98
- gr_btn_submit = gr.Button(value='Tagging', variant='primary')
99
-
100
- with gr.Column():
101
- with gr.Tabs():
102
- with gr.Tab("Tags"):
103
- gr_tags = gr.Label(label='Tags')
104
- with gr.Tab("Exported Text"):
105
- gr_output_text = gr.TextArea(label='Exported Text')
106
-
107
- gr_btn_submit.click(
108
- image_to_deepdanbooru_tags,
109
- inputs=[gr_input_image, gr_threshold, gr_space, gr_escape, gr_confidence, gr_order],
110
- outputs=[gr_output_text, gr_tags],
111
- )
112
-
113
- # Get the FastAPI app from Gradio Blocks
114
- app = demo.app
115
-
116
- # Allow cross-origin requests (optional, useful for testing)
117
- origins = ["*"]
118
- app.add_middleware(
119
- CORSMiddleware,
120
- allow_origins=origins,
121
- allow_methods=["*"],
122
- allow_headers=["*"],
 
 
 
 
 
 
 
 
 
 
 
123
  )
124
 
125
- @app.post("/api/analyze_image")
126
- async def analyze_image(file: UploadFile = File(...)):
127
- contents = await file.read()
128
- image = Image.open(io.BytesIO(contents))
129
- output_text, filtered_tags = image_to_deepdanbooru_tags(
130
- image,
131
- threshold=0.5,
132
- use_spaces=False,
133
- use_escape=True,
134
- include_ranks=False,
135
- score_descend=True
136
- )
137
- return JSONResponse(content=filtered_tags)
138
-
139
- # Launch the Gradio app
140
- demo.queue(concurrency_count=os.cpu_count()).launch(server_name="0.0.0.0")
141
 
 
 
 
8
  import onnxruntime as ort
9
  from PIL import Image
10
  from huggingface_hub import hf_hub_download
11
+ import io
12
+
13
+ from fastapi import FastAPI, File, UploadFile
14
+ from fastapi.responses import JSONResponse
15
+ import uvicorn
16
+
17
+ app = FastAPI()
18
 
19
  def _yield_tags_from_txt_file(txt_file: str):
20
  with open(txt_file, 'r') as f:
 
46
  height_pad_right = 512 - f_height - height_pad_left
47
  width_pad_left = (512 - f_width) // 2
48
  width_pad_right = 512 - f_width - width_pad_left
49
+ data = np.pad(
50
+ data,
51
+ ((height_pad_left, height_pad_right), (width_pad_left, width_pad_right), (0, 0)),
52
+ mode='constant',
53
+ constant_values=0.0
54
+ )
55
 
56
  assert data.shape == (512, 512, 3), f'Shape (512, 512, 3) expected, but {data.shape!r} found.'
57
  return data.reshape((1, 512, 512, 3)) # B x H x W x C
58
 
59
  RE_SPECIAL = re.compile(r'([\\()])')
60
 
61
+ def image_to_deepdanbooru_tags(
62
+ image: Image.Image,
63
+ threshold: float,
64
+ use_spaces: bool,
65
+ use_escape: bool,
66
+ include_ranks: bool,
67
+ score_descend: bool
68
+ ) -> Tuple[str, Mapping[str, float]]:
69
  tags = get_deepdanbooru_tags()
70
  session = get_deepdanbooru_onnx()
71
  input_name = session.get_inputs()[0].name
 
94
 
95
  return output_text, filtered_tags
96
 
97
+ @app.post("/tagging")
98
+ async def tagging_endpoint(image: UploadFile = File(...)):
99
+ image_data = await image.read()
100
+ pil_image = Image.open(io.BytesIO(image_data)).convert("RGB")
101
+ # Use default parameters or customize as needed
102
+ output_text, filtered_tags = image_to_deepdanbooru_tags(
103
+ pil_image,
104
+ threshold=0.5,
105
+ use_spaces=False,
106
+ use_escape=False,
107
+ include_ranks=False,
108
+ score_descend=True
109
+ )
110
+ tags = list(filtered_tags.keys())
111
+ return JSONResponse(content={"tags": tags})
112
+
113
+ def gradio_interface(
114
+ image: Image.Image,
115
+ threshold: float,
116
+ use_spaces: bool,
117
+ use_escape: bool,
118
+ include_ranks: bool,
119
+ score_descend: bool
120
+ ):
121
+ output_text, filtered_tags = image_to_deepdanbooru_tags(
122
+ image, threshold, use_spaces, use_escape, include_ranks, score_descend
123
+ )
124
+ return output_text, filtered_tags
125
+
126
+ with gr.Blocks() as demo:
127
+ with gr.Row():
128
+ with gr.Column():
129
+ gr_input_image = gr.Image(type='pil', label='Original Image')
130
+ gr_threshold = gr.Slider(0.0, 1.0, 0.5, label='Tagging Confidence Threshold')
131
+ with gr.Row():
132
+ gr_space = gr.Checkbox(value=False, label='Use Space Instead Of _')
133
+ gr_escape = gr.Checkbox(value=True, label='Use Text Escape')
134
+ gr_confidence = gr.Checkbox(value=False, label='Keep Confidences')
135
+ gr_order = gr.Checkbox(value=True, label='Descend By Confidence')
136
+
137
+ gr_btn_submit = gr.Button(value='Tagging', variant='primary')
138
+
139
+ with gr.Column():
140
+ with gr.Tabs():
141
+ with gr.Tab("Tags"):
142
+ gr_tags = gr.Label(label='Tags')
143
+ with gr.Tab("Exported Text"):
144
+ gr_output_text = gr.TextArea(label='Exported Text')
145
+
146
+ gr_btn_submit.click(
147
+ gradio_interface,
148
+ inputs=[gr_input_image, gr_threshold, gr_space, gr_escape, gr_confidence, gr_order],
149
+ outputs=[gr_output_text, gr_tags],
150
  )
151
 
152
+ app = gr.mount_gradio_app(app, demo, path="/")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
153
 
154
+ if __name__ == '__main__':
155
+ uvicorn.run(app, host='0.0.0.0', port=7860)