habulaj commited on
Commit
0e69a3b
·
verified ·
1 Parent(s): e8b21d9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +32 -20
app.py CHANGED
@@ -9,6 +9,8 @@ from io import BytesIO
9
  from PIL import Image, ImageFilter
10
  import rembg
11
  import onnxruntime as ort
 
 
12
 
13
  app = FastAPI()
14
 
@@ -17,6 +19,9 @@ options = ort.SessionOptions()
17
  options.intra_op_num_threads = 2 # Limita o número de threads para evitar sobrecarga
18
  options.execution_mode = ort.ExecutionMode.ORT_SEQUENTIAL # Execução sequencial para melhor desempenho em CPU
19
 
 
 
 
20
  def resize_image(image, max_size=512):
21
  """Redimensiona a imagem para uma largura máxima de 512px, mantendo a proporção."""
22
  width, height = image.size
@@ -26,29 +31,36 @@ def resize_image(image, max_size=512):
26
  image = image.resize(new_size, Image.Resampling.LANCZOS)
27
  return image
28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
  @app.get("/remove-background")
30
  async def remove_background(image_url: str):
31
  try:
32
- # Baixa a imagem da URL fornecida
33
- response = requests.get(image_url)
34
- response.raise_for_status()
35
-
36
- # Abre a imagem usando Pillow
37
- image = Image.open(BytesIO(response.content))
38
-
39
- # Pré-processamento: apenas redimensiona para 512px
40
- image = resize_image(image, max_size=512)
41
-
42
- # Remove o fundo da imagem usando rembg
43
- output = rembg.remove(image, session_options=options)
44
-
45
- # Pós-processamento: suaviza as bordas
46
- output = output.filter(ImageFilter.SMOOTH_MORE)
47
-
48
- # Converte a imagem de volta para bytes
49
- img_byte_arr = BytesIO()
50
- output.save(img_byte_arr, format='PNG')
51
- img_byte_arr.seek(0)
52
 
53
  # Retorna a imagem processada diretamente no navegador
54
  return StreamingResponse(img_byte_arr, media_type="image/png")
 
9
  from PIL import Image, ImageFilter
10
  import rembg
11
  import onnxruntime as ort
12
+ from concurrent.futures import ThreadPoolExecutor
13
+ import asyncio
14
 
15
  app = FastAPI()
16
 
 
19
  options.intra_op_num_threads = 2 # Limita o número de threads para evitar sobrecarga
20
  options.execution_mode = ort.ExecutionMode.ORT_SEQUENTIAL # Execução sequencial para melhor desempenho em CPU
21
 
22
+ # Pool de threads para executar tarefas bloqueantes
23
+ executor = ThreadPoolExecutor(max_workers=4)
24
+
25
  def resize_image(image, max_size=512):
26
  """Redimensiona a imagem para uma largura máxima de 512px, mantendo a proporção."""
27
  width, height = image.size
 
31
  image = image.resize(new_size, Image.Resampling.LANCZOS)
32
  return image
33
 
34
+ def process_image(image_url):
35
+ # Baixa a imagem da URL fornecida
36
+ response = requests.get(image_url)
37
+ response.raise_for_status()
38
+
39
+ # Abre a imagem usando Pillow
40
+ image = Image.open(BytesIO(response.content))
41
+
42
+ # Pré-processamento: apenas redimensiona para 512px
43
+ image = resize_image(image, max_size=512)
44
+
45
+ # Remove o fundo da imagem usando rembg
46
+ output = rembg.remove(image, session_options=options)
47
+
48
+ # Pós-processamento: suaviza as bordas
49
+ output = output.filter(ImageFilter.SMOOTH_MORE)
50
+
51
+ # Converte a imagem de volta para bytes
52
+ img_byte_arr = BytesIO()
53
+ output.save(img_byte_arr, format='PNG')
54
+ img_byte_arr.seek(0)
55
+
56
+ return img_byte_arr
57
+
58
  @app.get("/remove-background")
59
  async def remove_background(image_url: str):
60
  try:
61
+ # Executa o processamento da imagem em um thread separado
62
+ loop = asyncio.get_event_loop()
63
+ img_byte_arr = await loop.run_in_executor(executor, process_image, image_url)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64
 
65
  # Retorna a imagem processada diretamente no navegador
66
  return StreamingResponse(img_byte_arr, media_type="image/png")