Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
36 commits
Select commit Hold shift + click to select a range
259f925
feat: Adds setup for code quality analysis and refactoring.
EdivarCr Jun 25, 2026
5d2e2b1
feat: dados antes da refatoracao
EdivarCr Jun 27, 2026
b292b9c
refactor: remove many instances core.py
Julian-Cardoso Jun 28, 2026
00e1af2
refactor: remove many instances core.py(annotators)
Julian-Cardoso Jun 28, 2026
ef48233
refacotr: remove many instances line_zone.py
Julian-Cardoso Jun 28, 2026
1e534c1
refactor: remove many instances line_zone.py and test_line_counter.py
Julian-Cardoso Jun 28, 2026
d484eff
refactor: remove many instances line_zone.py and test_line_counter.py
Julian-Cardoso Jun 28, 2026
e4f965c
refactor: remove many instance inference_slicer.py and test_inference…
Julian-Cardoso Jun 28, 2026
1727fb9
refactor: remove many instances polygon_zone.py
Julian-Cardoso Jun 28, 2026
f9ac5db
refactor: remove many attributes f1_score.py and test_f1_score.py
Julian-Cardoso Jun 28, 2026
a187b2a
refactor: remove many attributes mean_average_precision.py and test_m…
Julian-Cardoso Jun 28, 2026
e4a226a
refactor: remove many attributes mean_average_precision.py
Julian-Cardoso Jun 28, 2026
8f1ad11
refactor: remove many attributes mean_average_recall.py and test_mean…
Julian-Cardoso Jun 28, 2026
6e2993f
refactor: remove many attributes precision.py and test_precision.py
Julian-Cardoso Jun 28, 2026
58db9ca
refactor: remove many attibutes recall.py and test_recall.py
Julian-Cardoso Jun 28, 2026
fdabbef
refactor: remove many attributes core.py
Julian-Cardoso Jun 28, 2026
6fc4666
refactor: remove many attributes core.py and single_object_track.py
Julian-Cardoso Jun 28, 2026
6212f3d
refactor: reduce statement complexity in byte_tracker core
EdivarCr Jun 28, 2026
059685a
refactor: simplify mean average precision calculation statements
EdivarCr Jun 28, 2026
5faf7c1
refactor: simplify internal detection helper functions
EdivarCr Jun 28, 2026
3dcd8ae
refactor: reduce statement count in video utility functions
EdivarCr Jun 28, 2026
b3f2f99
refactor: reduce statement complexity in detection metrics
EdivarCr Jun 28, 2026
76db078
refactor: reduce statement complexity in detection metrics
EdivarCr Jun 28, 2026
add76c0
refactor: reduce branch complexity in coco dataset format
EdivarCr Jun 28, 2026
cf80e8d
refactor: simplify control flow and branches in detections core
EdivarCr Jun 28, 2026
2b27d70
refactor: reduce branch count in inference slicer tool
EdivarCr Jun 28, 2026
4501cf2
refactor: simplify branch logic in internal detection utilities
EdivarCr Jun 28, 2026
1404351
refactor: reduce branch complexity in iou and nms utilities
EdivarCr Jun 28, 2026
0493016
refactor: simplify control flow in mask utilities
EdivarCr Jun 28, 2026
ed56d5d
refactor: update tests for sam connector after branch refactoring
EdivarCr Jun 28, 2026
a11f178
Merge pull request #1 from EdivarCr/refactor/remove-code-smell-too-ma…
EdivarCr Jun 28, 2026
3b4b3a5
Merge pull request #2 from EdivarCr/refactor/remove-code-smell-too-ma…
EdivarCr Jun 28, 2026
b5afb80
Merge branch 'develop' into refactor/remove-code-smell-instance-attri…
EdivarCr Jun 28, 2026
f7aace4
Merge pull request #3 from EdivarCr/refactor/remove-code-smell-instan…
EdivarCr Jun 28, 2026
8b8e6cd
chore: add post-refactor metrics extraction scripts and baseline reports
EdivarCr Jun 30, 2026
7524696
Adiciona arquivos finais do trabalho
EdivarCr Jul 2, 2026
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
Binary file not shown.
Binary file added Relatório Trabalho Manutenção.pdf
Binary file not shown.
Binary file added code_smells_dist_antes.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
66 changes: 66 additions & 0 deletions extract_metrics_after_codecarbon.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
from codecarbon import EmissionsTracker
import subprocess
import sys
import os

# Configuração

# Nome do projeto
PROJETO = "supervision"

# Ponto de entrada do projeto (define como o Python vai executar o projeto).
SCRIPT = "-m"

# Argumentos necessários para a execução do projeto.
# Se o projeto não precisar de argumentos, deixe vazio: ARGS = []
ARGS = ["pytest"]


# Tempo máximo que o CodeCarbon vai aguardar a execução do projeto antes de encerrar a
# medição e salvar os resultados.
# None -> sem limite — o CodeCarbon aguarda o projeto terminar sozinho.
# Use para scripts e pipelines que executam e terminam naturalmente.
#
# 60 -> encerra após 60 segundos, mesmo que o projeto ainda esteja rodando.
# Use para servidores (Flask, FastAPI, Django) que ficam rodando continuamente e nunca terminariam sozinhos.
TIMEOUT = None

# Não altere o nome dessa pasta, os relatórios vão ser salvos nela.
PASTA = "metrics-after-codecarbon"

# Executa com medição
os.makedirs(PASTA, exist_ok=True)

tracker = EmissionsTracker(
project_name=PROJETO,
measure_power_secs=1,
output_dir=PASTA,
output_file="emissions_depois.csv",
allow_multiple_runs=True,
log_level="error",
)

print(f"Iniciando medição de emissões para: {PROJETO}")
print(f"Comando: python {SCRIPT} {' '.join(ARGS)}")
if TIMEOUT:
print(f"Timeout: {TIMEOUT} segundos")

tracker.start()

try:
resultado = subprocess.run(
[sys.executable, SCRIPT] + ARGS,
timeout=TIMEOUT
)
exit_code = resultado.returncode
except subprocess.TimeoutExpired:
print("Tempo de medição encerrado.")
exit_code = 0

emissions = tracker.stop()

print(f"\nResultados:")
print(f" Exit code: {exit_code}")
print(f" COâ‚‚ emitido: {emissions * 1000:.6f} g COâ‚‚")
print(f" Arquivo salvo em: {os.path.join(PASTA, 'emissions_depois.csv')}")
print("\nConcluído.")
112 changes: 112 additions & 0 deletions extract_metrics_after_pylint.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
import json
import os
import subprocess
import sys
from collections import defaultdict, Counter

# Configuração
PROJETO = "./src" # diretório do código fonte
PASTA = "metrics-after-pylint" # Não altere o nome dessa pasta, os relatórios vão ser salvos nela.

os.makedirs(PASTA, exist_ok=True)

# Roda o Pylint
print(f"Rodando pylint em {PROJETO}...")

resultado = subprocess.run(
["pylint", PROJETO, "--output-format=json", "--score=y"],
capture_output=True,
text=True,
encoding="utf-8",
)

# Salva o JSON bruto
caminho_json = os.path.join(PASTA, "pylint_depois.json")
with open(caminho_json, "w", encoding="utf-8") as f:
f.write(resultado.stdout)
print(f"JSON completo salvo em: {caminho_json}")

# Processa mensagens
try:
mensagens = json.loads(resultado.stdout)
except json.JSONDecodeError:
print("Erro ao processar JSON do Pylint.")
sys.exit(1)

if not mensagens:
print("Nenhuma mensagem encontrada.")
sys.exit(0)

# Salva JSONs por categoria
por_tipo = defaultdict(list)
for msg in mensagens:
tipo = msg.get("type", "unknown")
por_tipo[tipo].append(msg)

tipos_nomes = {
"convention": "pylint_convention_depois.json",
"refactor": "pylint_refactor_depois.json",
"warning": "pylint_warning_depois.json",
"error": "pylint_error_depois.json",
"fatal": "pylint_fatal_depois.json",
}

for tipo, nome_arquivo in tipos_nomes.items():
caminho = os.path.join(PASTA, nome_arquivo)
with open(caminho, "w", encoding="utf-8") as f:
json.dump(por_tipo.get(tipo, []), f, indent=2, ensure_ascii=False)
print(f"{len(por_tipo.get(tipo, [])):>5} mensagens → {caminho}")

print(f"\nTotal: {len(mensagens)} mensagens encontradas.")

# Ranking da categoria refactor
mensagens_refactor = [msg for msg in mensagens if msg.get("type") == "refactor"]
contagem_simbolos = Counter(msg["symbol"] for msg in mensagens_refactor)
caminho_ranking = os.path.join(PASTA, "pylint_ranking_smells_depois.json")
with open(caminho_ranking, "w", encoding="utf-8") as f:
json.dump(
[{"simbolo": s, "ocorrencias": t} for s, t in contagem_simbolos.most_common()],
f,
indent=2,
ensure_ascii=False,
)
print(f"Ranking de símbolos salvo em: {caminho_ranking}")

# Arquivos com mais problemas
por_arquivo = defaultdict(lambda: defaultdict(int))
for msg in mensagens:
path = msg.get("path", "desconhecido")
tipo = msg.get("type", "unknown")
por_arquivo[path][tipo] += 1
por_arquivo[path]["total"] += 1

arquivos_ordenados = sorted(
[
{"arquivo": path, **contagens}
for path, contagens in por_arquivo.items()
],
key=lambda x: x["total"],
reverse=True,
)
caminho_arquivos = os.path.join(PASTA, "pylint_arquivos_criticos_depois.json")
with open(caminho_arquivos, "w", encoding="utf-8") as f:
json.dump(arquivos_ordenados, f, indent=2, ensure_ascii=False)
print(f"Arquivos críticos salvo em: {caminho_arquivos}")

# Distribuição por categoria
total = len(mensagens)
distribuicao = [
{
"categoria": tipo,
"ocorrencias": len(msgs),
"percentual": round(len(msgs) / total * 100, 2),
}
for tipo, msgs in por_tipo.items()
]
distribuicao.sort(key=lambda x: x["ocorrencias"], reverse=True)
caminho_dist = os.path.join(PASTA, "pylint_distribuicao_categorias_depois.json")
with open(caminho_dist, "w", encoding="utf-8") as f:
json.dump(distribuicao, f, indent=2, ensure_ascii=False)
print(f"Distribuição por categoria salva em: {caminho_dist}")

print("\nConcluído.")
68 changes: 68 additions & 0 deletions extract_metrics_after_pytest.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import os
import subprocess
import sys
from pathlib import Path

# Configuração, ajuste apenas se necessário.

# Diretório raiz do projeto, os testes vai começar a execução a petir dele.
PROJETO = "."

# Diretório dos testes detectado automaticamente, mas pode forçar manualmente
# Exemplos: TESTES = "./tests" ou TESTES = "./test"
TESTES = None

# Pasta onde os relatórios serão salvos (não altere)
PASTA = "metrics-after-pytest"

# Detecção automática do diretório de testes
CANDIDATOS = ["tests", "test", "src/tests", "src/test"]

if TESTES is None:
for candidato in CANDIDATOS:
if Path(candidato).exists():
TESTES = candidato
break

if TESTES is None:
print("Erro: diretório de testes não encontrado.")
print(f"Procurado em: {CANDIDATOS}")
print("Defina manualmente a variável TESTES no script.")
sys.exit(1)

# Execução
os.makedirs(PASTA, exist_ok=True)

print(f"Projeto : {os.path.abspath(PROJETO)}")
print(f"Testes : {TESTES}")
print(f"Relatórios em: {PASTA}/")
print()

resultado = subprocess.run(
[
sys.executable, "-m", "pytest", TESTES,
"-v",
f"--junit-xml={os.path.join(PASTA, 'pytest_depois.xml')}",
f"--html={os.path.join(PASTA, 'pytest_depois.html')}",
"--self-contained-html",
f"--cov={PROJETO}",
"--cov-branch",
f"--cov-report=xml:{os.path.join(PASTA, 'coverage_depois.xml')}",
f"--cov-report=json:{os.path.join(PASTA, 'coverage_depois.json')}",
f"--cov-report=html:{os.path.join(PASTA, 'coverage_depois_html')}",
"--cov-report=term-missing",
],
cwd=PROJETO,

text=True,
encoding="utf-8",
)

print(f"\nExit code: {resultado.returncode}")
print(f"\nArquivos gerados em '{PASTA}':")
print(f" pytest_depois.xml → resultados dos testes em XML")
print(f" pytest_depois.html → relatório visual dos testes")
print(f" coverage_depois.xml → cobertura de código em XML")
print(f" coverage_depois.json → cobertura de código em JSON")
print(f" coverage_depois_html/ → relatório visual de cobertura")
print("\nConcluído.")
Loading