habulaj commited on
Commit
29e5b0a
·
verified ·
1 Parent(s): 0cff1a8

Update routers/textclas.py

Browse files
Files changed (1) hide show
  1. routers/textclas.py +32 -33
routers/textclas.py CHANGED
@@ -1,44 +1,43 @@
1
- from fastapi import APIRouter, Query, HTTPException
2
- from keybert import KeyBERT
3
-
4
- # Inicializa o modelo KeyBERT com DistilBERT (mais rápido que BERT completo)
5
- kw_model = KeyBERT(model='distilbert-base-nli-mean-tokens')
 
6
 
 
7
  router = APIRouter()
8
 
9
- @router.get("/keywords/extract/")
10
- def extract_keywords(
11
- text: str = Query(..., description="Texto para extração de palavras-chave"),
12
- num_keywords: int = Query(5, description="Número de palavras-chave a serem retornadas", ge=1, le=20)
13
  ):
14
  """
15
- Extrai palavras-chave relevantes de um texto.
16
  """
17
  try:
18
- # Extrai palavras-chave
19
- keywords = kw_model.extract_keywords(
20
- text,
21
- keyphrase_ngram_range=(1, 2),
22
- stop_words='english',
23
- top_n=num_keywords
24
- )
 
 
25
 
26
- # Formata o retorno
27
- keyword_list = [kw[0] for kw in keywords]
 
 
28
 
29
- return {
30
- "text": text,
31
- "num_keywords": num_keywords,
32
- "keywords": keyword_list
33
- }
34
 
35
- except ValueError as ve:
36
- raise HTTPException(
37
- status_code=400,
38
- detail=f"Invalid input: {str(ve)}"
39
- )
40
  except Exception as e:
41
- raise HTTPException(
42
- status_code=500,
43
- detail=f"An error occurred during keyword extraction: {str(e)}"
44
- )
 
1
+ from fastapi import APIRouter, HTTPException, Query
2
+ from fastapi.responses import JSONResponse
3
+ from PIL import Image
4
+ import requests
5
+ import base64
6
+ from io import BytesIO
7
 
8
+ # Criação do roteador
9
  router = APIRouter()
10
 
11
+ @router.get("/image/base64/")
12
+ def get_image_as_base64(
13
+ image_url: str = Query(..., description="URL da imagem para ser processada")
 
14
  ):
15
  """
16
+ Recebe uma URL de imagem, converte para base64 e retorna no navegador.
17
  """
18
  try:
19
+ # Baixar a imagem da URL
20
+ response = requests.get(image_url)
21
+ if response.status_code != 200:
22
+ raise HTTPException(
23
+ status_code=400, detail="Não foi possível baixar a imagem da URL fornecida."
24
+ )
25
+
26
+ # Abrir a imagem com Pillow
27
+ image = Image.open(BytesIO(response.content))
28
 
29
+ # Converter a imagem para base64
30
+ buffered = BytesIO()
31
+ image.save(buffered, format=image.format if image.format else "PNG")
32
+ img_base64 = base64.b64encode(buffered.getvalue()).decode("utf-8")
33
 
34
+ # Retornar a imagem em base64
35
+ return JSONResponse(content={
36
+ "image_url": image_url,
37
+ "image_base64": f"data:image/{image.format.lower()};base64,{img_base64}"
38
+ })
39
 
40
+ except requests.exceptions.RequestException as e:
41
+ raise HTTPException(status_code=400, detail=f"Erro ao acessar a URL: {str(e)}")
 
 
 
42
  except Exception as e:
43
+ raise HTTPException(status_code=500, detail=f"Erro interno do servidor: {str(e)}")