Alley P commited on
Commit
7873ee1
·
1 Parent(s): 92ff08e

refactor: reorganize proj structure ; remove unused scripts; add dataset configs

Browse files
.gitignore CHANGED
@@ -19,7 +19,7 @@ my_env/
19
  # ╭──────────────────────────────╮
20
  # │ DADOS IGNORADOS (RAW) │
21
  # ╰──────────────────────────────╯
22
- datasets/FASDD_MERGED/
23
  datasets/FASDD_40PERCENT/
24
 
25
  # ╭──────────────────────────────╮
 
19
  # ╭──────────────────────────────╮
20
  # │ DADOS IGNORADOS (RAW) │
21
  # ╰──────────────────────────────╯
22
+ datasets/FASDD/
23
  datasets/FASDD_40PERCENT/
24
 
25
  # ╭──────────────────────────────╮
check_upload_status.py DELETED
@@ -1,47 +0,0 @@
1
- #!/usr/bin/env python3
2
- """Script para monitorar o progresso do upload"""
3
-
4
- import time
5
- import subprocess
6
- import os
7
- from pathlib import Path
8
-
9
- def check_upload_status():
10
- """Verifica o status do upload"""
11
- print("Verificando status do upload...")
12
-
13
- # Verificar se o processo está rodando
14
- try:
15
- result = subprocess.run(
16
- ['tasklist', '/fi', 'imagename eq python.exe'],
17
- capture_output=True,
18
- text=True
19
- )
20
-
21
- if 'python.exe' in result.stdout:
22
- print("✓ Processo Python está rodando")
23
- else:
24
- print("⚠ Nenhum processo Python encontrado")
25
-
26
- except Exception as e:
27
- print(f"Erro ao verificar processos: {e}")
28
-
29
- # Verificar se há arquivos de log
30
- log_file = Path('upload_log.txt')
31
- if log_file.exists():
32
- print(f"✓ Arquivo de log encontrado: {log_file.stat().st_size} bytes")
33
-
34
- # Mostrar últimas linhas do log
35
- with open(log_file, 'r', encoding='utf-8') as f:
36
- lines = f.readlines()
37
- if lines:
38
- print("Últimas linhas do log:")
39
- for line in lines[-10:]:
40
- print(f" {line.strip()}")
41
- else:
42
- print("⚠ Arquivo de log não encontrado")
43
-
44
- return True
45
-
46
- if __name__ == "__main__":
47
- check_upload_status()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fasdd_40.yaml → fasdd.yaml RENAMED
@@ -1,4 +1,4 @@
1
- path: datasets/FASDD_40PERCENT
2
  train: images/train
3
  val: images/val
4
  test: images/test
 
1
+ path: datasets/FASDD
2
  train: images/train
3
  val: images/val
4
  test: images/test
pipeline/sample_dataset_subset.py DELETED
@@ -1,44 +0,0 @@
1
- import os
2
- import shutil
3
- import random
4
- from pathlib import Path
5
- from tqdm import tqdm
6
-
7
- def sample_split(split, input_dir, output_dir, percent):
8
- img_dir = Path(input_dir) / "images" / split
9
- label_dir = Path(input_dir) / "labels" / split
10
- out_img_dir = Path(output_dir) / "images" / split
11
- out_label_dir = Path(output_dir) / "labels" / split
12
-
13
- out_img_dir.mkdir(parents=True, exist_ok=True)
14
- out_label_dir.mkdir(parents=True, exist_ok=True)
15
-
16
- images = list(img_dir.glob("*.jpg"))
17
- sample_size = int(len(images) * percent)
18
- selected_images = random.sample(images, sample_size)
19
-
20
- print(f"📂 {split.upper()}: copiando {sample_size} de {len(images)} imagens...")
21
-
22
- for img_path in tqdm(selected_images):
23
- shutil.copy(img_path, out_img_dir / img_path.name)
24
-
25
- label_path = label_dir / f"{img_path.stem}.txt"
26
- out_label = out_label_dir / f"{img_path.stem}.txt"
27
- if label_path.exists():
28
- shutil.copy(label_path, out_label)
29
-
30
- def sample_dataset(input_dir, output_dir, percent=0.4):
31
- print(f"🚀 Criando subconjunto do dataset: {int(percent*100)}%")
32
- for split in ["train", "val", "test"]:
33
- sample_split(split, input_dir, output_dir, percent)
34
- print("✅ Dataset copiado.")
35
-
36
- if __name__ == "__main__":
37
- import argparse
38
- parser = argparse.ArgumentParser()
39
- parser.add_argument("--input", type=str, required=True, help="Caminho do dataset original")
40
- parser.add_argument("--output", type=str, default="datasets/FASDD_40PERCENT", help="Destino do novo subset")
41
- parser.add_argument("--percent", type=float, default=0.4, help="Porcentagem a copiar (ex: 0.4 para 40%)")
42
- args = parser.parse_args()
43
-
44
- sample_dataset(args.input, args.output, args.percent)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
check_status.py → scripts/check_status_upload.py RENAMED
@@ -1,13 +1,10 @@
1
  #!/usr/bin/env python3
2
- """Script para verificar se o upload está funcionando"""
3
 
4
  import subprocess
5
- import time
6
  import os
7
  from pathlib import Path
8
 
9
- def check_processes():
10
- """Verifica processos Python rodando"""
11
  try:
12
  result = subprocess.run(
13
  ['wmic', 'process', 'where', 'name="python.exe"', 'get', 'processid,commandline'],
@@ -17,25 +14,23 @@ def check_processes():
17
 
18
  if result.returncode == 0:
19
  lines = result.stdout.strip().split('\n')
20
- python_processes = []
21
- for line in lines[1:]: # Pular header
22
- if line.strip() and 'upload' in line.lower():
23
- python_processes.append(line.strip())
24
 
25
- if python_processes:
26
- print("✓ Processos de upload encontrados:")
27
- for proc in python_processes:
28
  print(f" {proc}")
29
  else:
30
- print("⚠ Nenhum processo de upload encontrado")
31
  else:
32
- print("✗ Erro ao verificar processos")
33
 
34
  except Exception as e:
35
- print(f"Erro: {e}")
36
 
37
  def check_files():
38
- """Verifica arquivos criados"""
39
  files_to_check = [
40
  'upload_log.txt',
41
  'test_upload_results.txt',
@@ -46,30 +41,29 @@ def check_files():
46
  path = Path(file_path)
47
  if path.exists():
48
  size = path.stat().st_size
49
- print(f"✓ {file_path} existe ({size} bytes)")
50
  else:
51
- print(f"⚠ {file_path} não existe")
52
 
53
  def main():
54
- print("=== Verificação de status do upload ===")
55
- print(f"Diretório atual: {os.getcwd()}")
56
  print()
57
 
58
- print("1. Verificando processos...")
59
- check_processes()
60
 
61
- print("\n2. Verificando arquivos...")
62
  check_files()
63
-
64
- print("\n3. Testando comando simples...")
65
  try:
66
  result = subprocess.run(['dagshub', '--help'], capture_output=True, text=True, timeout=5)
67
  if result.returncode == 0:
68
- print("✓ DagsHub CLI funciona")
69
  else:
70
- print("✗ DagsHub CLI não funciona")
71
  except Exception as e:
72
- print(f"✗ Erro ao testar DagsHub: {e}")
73
 
74
  if __name__ == "__main__":
75
  main()
 
1
  #!/usr/bin/env python3
 
2
 
3
  import subprocess
 
4
  import os
5
  from pathlib import Path
6
 
7
+ def find_python_processes():
 
8
  try:
9
  result = subprocess.run(
10
  ['wmic', 'process', 'where', 'name="python.exe"', 'get', 'processid,commandline'],
 
14
 
15
  if result.returncode == 0:
16
  lines = result.stdout.strip().split('\n')
17
+ upload_processes = [
18
+ line.strip() for line in lines[1:] if line.strip() and 'upload' in line.lower()
19
+ ]
 
20
 
21
+ if upload_processes:
22
+ print("✓ Upload processes found:")
23
+ for proc in upload_processes:
24
  print(f" {proc}")
25
  else:
26
+ print("⚠ No upload processes found")
27
  else:
28
+ print("✗ Error checking processes")
29
 
30
  except Exception as e:
31
+ print(f"Error: {e}")
32
 
33
  def check_files():
 
34
  files_to_check = [
35
  'upload_log.txt',
36
  'test_upload_results.txt',
 
41
  path = Path(file_path)
42
  if path.exists():
43
  size = path.stat().st_size
44
+ print(f"✓ {file_path} exists ({size} bytes)")
45
  else:
46
+ print(f"⚠ {file_path} does not exist")
47
 
48
  def main():
49
+ print("=== Upload Status Check ===")
50
+ print(f"Current directory: {os.getcwd()}")
51
  print()
52
 
53
+ print("1. Checking processes...")
54
+ find_python_processes()
55
 
56
+ print("\n2. Checking files...")
57
  check_files()
58
+
 
59
  try:
60
  result = subprocess.run(['dagshub', '--help'], capture_output=True, text=True, timeout=5)
61
  if result.returncode == 0:
62
+ print("✓ DagsHub CLI is working")
63
  else:
64
+ print("✗ DagsHub CLI is not working")
65
  except Exception as e:
66
+ print(f"✗ Error testing DagsHub CLI: {e}")
67
 
68
  if __name__ == "__main__":
69
  main()
scripts/train.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from ultralytics import YOLO
2
+
3
+ def train_yolo_model(data_path, model, epochs=10, batch_size=32, imgsz=320):
4
+ """
5
+ Train YOLO model with optimized parameters for fastest training (testing purposes)
6
+
7
+ Args:
8
+ data_path: Path to dataset YAML file
9
+ model: Model size ('yolov9n.pt' is fastest, 'yolov9s.pt' for better accuracy)
10
+ epochs: Number of training epochs (10-20 for quick tests)
11
+ batch_size: Batch size (16-64 depending on GPU memory)
12
+ imgsz: Image size (320 fastest, 640 standard, 1280 highest quality)
13
+ """
14
+ # Load a YOLO model
15
+ model = YOLO(model)
16
+
17
+ # Train the model with optimized parameters for speed
18
+ results = model.train(
19
+ data=data_path,
20
+ epochs=epochs,
21
+ batch=batch_size,
22
+ imgsz=imgsz,
23
+ device='cpu', # Change to 'cuda' or '0' if you have a GPU
24
+ workers=4, # Number of dataloader workers
25
+ cache=True, # Cache images for faster training
26
+ amp=True, # Automatic Mixed Precision (faster on modern GPUs)
27
+ patience=5, # Early stopping patience
28
+ save_period=5, # Save checkpoint every 5 epochs
29
+ plots=False, # Disable plots to save time
30
+ verbose=True
31
+ )
32
+
33
+ return results
34
+
35
+ if __name__ == "__main__":
36
+ data_path = "fasdd.yaml" # Path to the dataset configuration file
37
+
38
+ # For fastest training (testing purposes):
39
+ train_yolo_model(data_path, model='yolov9s.pt', epochs=5, batch_size=64, imgsz=320)
40
+
41
+ # For balanced speed/accuracy (uncomment to use):
42
+ # train_yolo_model(data_path, epochs=20, batch_size=32, imgsz=480)
43
+
44
+ # For full training (uncomment to use):
45
+ # train_yolo_model(data_path, model='yolov9s.pt', epochs=100, batch_size=16, imgsz=640)
46
+
47
+ # For balanced speed/accuracy (uncomment to use):
48
+ # train_yolo_model(data_path, epochs=20, batch_size=32, imgsz=480)
{pipeline → scripts}/upload_to_dagshub.py RENAMED
@@ -4,56 +4,57 @@ from pathlib import Path
4
  from dotenv import load_dotenv
5
  import requests
6
 
7
- # Carrega o token do .env
8
  load_dotenv(dotenv_path=Path(__file__).resolve().parent.parent / ".env")
9
  DAGSHUB_TOKEN = os.getenv("DAGSHUB_TOKEN")
10
- USERNAME = "All3yp"
11
- REPO = "FS_DETECTION"
12
  REPO_PATH = f"{USERNAME}/{REPO}"
 
13
 
14
  if not DAGSHUB_TOKEN:
15
- raise ValueError("❌ DAGSHUB_TOKEN não encontrado no .env")
16
 
17
- def testar_conexao_dagshub(username, repo, token):
18
- print("🔐 Testando autenticação com DagsHub...")
19
- url = f"https://dagshub.com/api/v1/repos/{username}/{repo}"
20
- response = requests.get(url, auth=(username, token))
21
  if response.status_code == 200:
22
- print("✅ Conexão com DagsHub OK")
23
  return True
24
- print(f"❌ Falha na autenticação ({response.status_code}): {response.text}")
25
  return False
26
 
27
  def install_dagshub_client():
28
- print("🔧 Verificando cliente DagsHub...")
29
  try:
30
  subprocess.run(["dagshub", "--help"], capture_output=True, text=True, check=True)
31
  except (FileNotFoundError, subprocess.CalledProcessError):
32
- print("📦 Instalando cliente DagsHub...")
33
  subprocess.run(["pip", "install", "dagshub", "--upgrade"], check=True)
34
 
35
  def login_dagshub():
36
- print("🔐 Realizando login automático no DagsHub via token...")
37
  try:
38
  subprocess.run(["dagshub", "login", "--token", DAGSHUB_TOKEN], check=True)
39
- print("✅ Login realizado com sucesso")
40
  except subprocess.CalledProcessError as e:
41
- print(f"⚠️ Aviso durante login: {e.stderr}")
42
 
43
  def upload_datasets():
44
- print("📤 Enviando datasets para o bucket do DagsHub...")
45
 
46
  datasets_to_upload = [
47
- "datasets/FASDD_40PERCENT"
48
  ]
49
 
50
  for dataset_path in datasets_to_upload:
51
  path_obj = Path(dataset_path)
52
  if not path_obj.exists():
53
- print(f"⚠️ Dataset não encontrado: {dataset_path}, pulando...")
54
  continue
55
 
56
- print(f"📁 Upload: {dataset_path}")
57
  try:
58
  subprocess.run([
59
  "dagshub", "upload",
@@ -62,21 +63,21 @@ def upload_datasets():
62
  f"data/{path_obj.name}/",
63
  "--bucket", "--update", "-v"
64
  ], check=True)
65
- print(f"✅ Upload concluído: {dataset_path}")
66
  except subprocess.CalledProcessError as e:
67
- print(f"❌ Erro no upload de {dataset_path}: {e.stderr}")
68
 
69
  if __name__ == "__main__":
70
- print("🚀 Iniciando upload para o bucket DagsHub...")
71
 
72
- if not testar_conexao_dagshub(USERNAME, REPO, DAGSHUB_TOKEN):
73
- raise SystemExit("⛔ Token inválido ou repositório inacessível.")
74
 
75
  try:
76
  install_dagshub_client()
77
  login_dagshub()
78
  upload_datasets()
79
- print("✅ Upload finalizado com sucesso!")
80
  except Exception as e:
81
- print(f"❌ Erro durante o processo: {e}")
82
  raise
 
4
  from dotenv import load_dotenv
5
  import requests
6
 
7
+ ########## Configs ##########
8
  load_dotenv(dotenv_path=Path(__file__).resolve().parent.parent / ".env")
9
  DAGSHUB_TOKEN = os.getenv("DAGSHUB_TOKEN")
10
+ USERNAME = os.getenv("USERNAME")
11
+ REPO = os.getenv("REPO")
12
  REPO_PATH = f"{USERNAME}/{REPO}"
13
+ ##############################
14
 
15
  if not DAGSHUB_TOKEN:
16
+ raise ValueError("❌ DAGSHUB_TOKEN not found in .env")
17
 
18
+ def testar_conexao_dagshub(token):
19
+ print("🔐 Testing DagsHub authentication...")
20
+ url = f"https://dagshub.com/api/v1/repos/{USERNAME}/{REPO}"
21
+ response = requests.get(url, auth=(USERNAME, token))
22
  if response.status_code == 200:
23
+ print("✅ DagsHub connection OK")
24
  return True
25
+ print(f"❌ Authentication failed ({response.status_code}): {response.text}")
26
  return False
27
 
28
  def install_dagshub_client():
29
+ print("🔧 Checking DagsHub client...")
30
  try:
31
  subprocess.run(["dagshub", "--help"], capture_output=True, text=True, check=True)
32
  except (FileNotFoundError, subprocess.CalledProcessError):
33
+ print("📦 Installing DagsHub client...")
34
  subprocess.run(["pip", "install", "dagshub", "--upgrade"], check=True)
35
 
36
  def login_dagshub():
37
+ print("🔐 Performing automatic login to DagsHub via token...")
38
  try:
39
  subprocess.run(["dagshub", "login", "--token", DAGSHUB_TOKEN], check=True)
40
+ print("✅ Login successful")
41
  except subprocess.CalledProcessError as e:
42
+ print(f"⚠️ Warning during login: {e.stderr}")
43
 
44
  def upload_datasets():
45
+ print("📤 Uploading datasets to DagsHub bucket...")
46
 
47
  datasets_to_upload = [
48
+ "datasets/FASDD"
49
  ]
50
 
51
  for dataset_path in datasets_to_upload:
52
  path_obj = Path(dataset_path)
53
  if not path_obj.exists():
54
+ print(f"⚠️ Dataset not found: {dataset_path}, skipping...")
55
  continue
56
 
57
+ print(f"📁 Uploading: {dataset_path}")
58
  try:
59
  subprocess.run([
60
  "dagshub", "upload",
 
63
  f"data/{path_obj.name}/",
64
  "--bucket", "--update", "-v"
65
  ], check=True)
66
+ print(f"✅ Upload completed: {dataset_path}")
67
  except subprocess.CalledProcessError as e:
68
+ print(f"❌ Upload error for {dataset_path}: {e.stderr}")
69
 
70
  if __name__ == "__main__":
71
+ print("🚀 Starting upload to DagsHub bucket...")
72
 
73
+ if not testar_conexao_dagshub(DAGSHUB_TOKEN):
74
+ raise SystemExit("⛔ Invalid token or repository inaccessible.")
75
 
76
  try:
77
  install_dagshub_client()
78
  login_dagshub()
79
  upload_datasets()
80
+ print("✅ Upload completed successfully!")
81
  except Exception as e:
82
+ print(f"❌ Error during process: {e}")
83
  raise