Skip to content
Open

Main #21

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 47 additions & 0 deletions .dockerignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
# Ignorar arquivos e diretórios irrelevantes
*.pyc
*.pyo
*.pyd
__pycache__/
*.log
*.tmp
*.swp

# Ignorar arquivos de controle de versão
.git/
*.gitignore

# Ignorar ambientes virtuais e pacotes locais
.env/
*.env
*.tar
*.zip
*.rar
recorte-placas-env/

# Ignorar imagens e arquivos grandes
*.jpg
*.png
photos/
processed_photos/

# Ignorar outros arquivos desnecessários
*.tar
*.bak
*.old
*.DS_Store
*.idea
*.vscode

# Incluir arquivos essenciais explicitamente
!Dockerfile
!requirements.txt
!imageProcAPI.py
!workflow.py
!scan.py
!teste.py

# Incluir pastas essenciais explicitamente
!connection/
!pyimagesearch/
!utils/
9 changes: 8 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,9 @@
*.pyc
.DS_Store
.DS_Store
images/
output/
recorte-placas-env/
photos/
processed_photos/
python-image/
recorte-placas.tar
31 changes: 31 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
# Use a imagem oficial do Python mais leve
FROM python:3.8-slim

# Defina um ambiente não interativo para evitar prompts do apt
ENV DEBIAN_FRONTEND=noninteractive

# Instale dependências essenciais do sistema
RUN apt-get update && apt-get install -y --no-install-recommends \
build-essential \
libopencv-dev \
&& apt-get clean && rm -rf /var/lib/apt/lists/*

# Defina o diretório de trabalho dentro do container
WORKDIR /app

# Copie e instale apenas as dependências antes para aproveitar o cache do Docker
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

# Copie o restante do código da aplicação
COPY . .

# Exponha a porta que o Flask usará
EXPOSE 5000

# Defina variáveis de ambiente para produção
ENV FLASK_APP=imageProcAPI.py
ENV FLASK_RUN_HOST=0.0.0.0

# Execute o servidor Flask diretamente para melhor compatibilidade
CMD ["python", "-m", "flask", "run", "--host=0.0.0.0"]
38 changes: 0 additions & 38 deletions README.md

This file was deleted.

Binary file removed before_after.gif
Binary file not shown.
23 changes: 23 additions & 0 deletions connection/patch.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import requests

def patch(id, photo_url):

url = f"https://tfiswpjimraodvnjbybx.supabase.co/rest/v1/Boards?id=eq.{id}"
headers = { "Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InRmaXN3cGppbXJhb2R2bmpieWJ4Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3MzMxNTIwNTUsImV4cCI6MjA0ODcyODA1NX0.I8UX36hAphowNk85VcL6iYh4TIBwsE0r3wgreTEDaII",
"apikey": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InRmaXN3cGppbXJhb2R2bmpieWJ4Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3MzMxNTIwNTUsImV4cCI6MjA0ODcyODA1NX0.I8UX36hAphowNk85VcL6iYh4TIBwsE0r3wgreTEDaII",
"Prefer": "return=representation"
}

data = {
"trimmed_photo_url": photo_url
}


response = requests.patch(url, json=data, headers=headers)

if response.status_code in [200, 204]:
print("Atualização feita com sucesso!")
print(response.json()) # Caso a API retorne um JSON
else:
print(f"Erro ao atualizar: {response.status_code}")
print(response.text) # Exibir a resposta do servidor
46 changes: 46 additions & 0 deletions connection/supabase_connection.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import requests

class SupabaseConnection:
"""
Classe para gerenciar a conexão e upload de arquivos para o Supabase Storage.
"""

def __init__(self):
"""
Inicializa a conexão com os parâmetros fornecidos.

:param supabase_url: URL do Supabase
:param bucket_name: Nome do bucket no Supabase
:param file_key: Caminho onde será salvo no Supabase
:param file_path: Caminho do arquivo local
:param jwt_token: JWT Token para autenticação
"""
self.supabase_url = "https://tfiswpjimraodvnjbybx.supabase.co"
self.bucket_name = "boards"
self.jwt_token = "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InRmaXN3cGppbXJhb2R2bmpieWJ4Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3MzMxNTIwNTUsImV4cCI6MjA0ODcyODA1NX0.I8UX36hAphowNk85VcL6iYh4TIBwsE0r3wgreTEDaII"
self.headers = {
"Authorization": f"{self.jwt_token}",
"Content-Type": "image/jpeg"
}

def upload_file_to_supabase(self, image_name, image_path):
"""
Faz o upload do arquivo para o Supabase Storage.
"""
upload_url = f"{self.supabase_url}/storage/v1/object/{self.bucket_name}/images/{image_name}"

try:
with open(image_path, "rb") as file:
response = requests.put(upload_url, headers=self.headers, data=file)

# Verificar resposta
if response.status_code == 200:
print(f"✅ Upload bem-sucedido! Arquivo salvo como: images/{image_name}")
response_json = response.json()
response_json.update({"url": f"{upload_url}"})
return response_json
else:
print(f"❌ Erro no upload: {response.status_code} - {response.text}")

except Exception as e:
print("❌ Erro ao enviar a imagem:", e)
14 changes: 14 additions & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
version: '3.8' # Versão do Docker Compose

services:
flask_app: # Nome do serviço (pode ser qualquer nome)
build: . # Indica que o Dockerfile está no diretório atual
container_name: flask_container # Nome do contêiner (opcional)
ports:
- "5000:5000" # Mapeia a porta 5000 do contêiner para a porta 5000 do host
environment:
- FLASK_APP=imageProcAPI.py # Define a variável de ambiente FLASK_APP
- FLASK_RUN_HOST=0.0.0.0 # Define a variável de ambiente FLASK_RUN_HOST
volumes:
- .:/app # Monta o diretório atual do host no diretório /app do contêiner (útil para desenvolvimento)
restart: unless-stopped # Reinicia o contêiner automaticamente, a menos que seja parado manualmente
59 changes: 59 additions & 0 deletions imageProcAPI.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
from flask import Flask, request, jsonify
from workflow import workImage
import threading
import time
import random
import string

app = Flask(__name__)

image_queue = [] # Lista para armazenar as URLs da fila
processing = False # Flag para indicar se há uma imagem sendo processada

def process_next_image():
global processing
while True:
if image_queue and not processing:
processing = True
image_data = image_queue.pop(0)
image_name = image_data["image_name"]
print(f"Processando imagem: {image_name}")

# Processa a imagem e obtém os dados da imagem no bucket
workImage(image_data["photo_url"], image_name, image_data["id"])

processing = False
time.sleep(1) # Pequeno delay para evitar loop intenso

def generate_random_name(length=10):
letters = string.ascii_lowercase
image_name = ''.join(random.choice(letters) for _ in range(length))
return image_name + ".jpg"

@app.route("/")
def imageURL():
return "API de Processamento de Imagens - Online"

@app.route("/create-procimage", methods=["POST"])
def create_procimage():
data = request.get_json()

if "photo_url" not in data:
return jsonify({"error": "Parâmetro 'photo_url' é obrigatório"}), 400

if "id" not in data:
return jsonify({"error": "Parâmetro 'id' é obrigatório"}), 400

image_name = generate_random_name()
data["image_name"] = image_name
image_queue.append(data)
print(f"Imagem recebida e adicionada na fila com nome: {data['image_name']}")

return jsonify({"status": "ok", "image_name": image_name, "processed_image_url": f"https://tfiswpjimraodvnjbybx.supabase.co/storage/v1/object/boards/images/{image_name}"}), 201

if __name__ == "__main__":
# Iniciar a thread para processar a fila em background
processing_thread = threading.Thread(target=process_next_image, daemon=True)
processing_thread.start()

app.run(host="0.0.0.0", debug=True)
Binary file removed output/cell_pic.jpg
Binary file not shown.
Binary file removed output/chart.JPG
Binary file not shown.
Binary file removed output/desk.JPG
Binary file not shown.
Binary file removed output/dollar_bill.JPG
Binary file not shown.
Binary file removed output/math_cheat_sheet.JPG
Binary file not shown.
Binary file removed output/notepad.JPG
Binary file not shown.
Binary file removed output/receipt.jpg
Binary file not shown.
Binary file removed output/tax.jpeg
Binary file not shown.
106 changes: 0 additions & 106 deletions polygon_interacter.py

This file was deleted.

Empty file removed pyimagesearch/__init__.py
Empty file.
Binary file modified requirements.txt
Binary file not shown.
Binary file removed sample_images/cell_pic.jpg
Binary file not shown.
Binary file removed sample_images/chart.JPG
Binary file not shown.
Binary file removed sample_images/desk.JPG
Binary file not shown.
Binary file removed sample_images/dollar_bill.JPG
Binary file not shown.
Binary file removed sample_images/math_cheat_sheet.JPG
Binary file not shown.
Binary file removed sample_images/notepad.JPG
Binary file not shown.
Binary file removed sample_images/receipt.jpg
Binary file not shown.
Binary file removed sample_images/tax.jpeg
Binary file not shown.
Loading