J / TROUBLESHOOTING_IMPORTS.md
Andro0s's picture
Upload 14 files
80dd10c verified

🔧 TROUBLESHOOTING: ModuleNotFoundError en Hugging Face

❌ Error: ModuleNotFoundError: No module named 'src'

Este error ocurre cuando Python no puede encontrar el módulo src. Aquí están las soluciones:


✅ SOLUCIÓN 1: Usar el archivo start.py (Recomendado)

Ya he actualizado el proyecto con un script de inicio que maneja correctamente los imports.

Cambios realizados:

  1. Nuevo archivo: start.py

    • Configura el PYTHONPATH correctamente
    • Verifica que todos los archivos existan
    • Prueba los imports antes de iniciar
    • Inicia el servidor FastAPI
  2. Dockerfile actualizado:

    CMD ["python", "start.py"]
    
  3. app.py actualizado:

    • Maneja imports con try/except
    • Método alternativo de importación si falla el estándar

Para usar:

# Local
python start.py

# Docker
docker build -t aliah-plus .
docker run -p 7860:7860 aliah-plus

# El start.py se ejecutará automáticamente

✅ SOLUCIÓN 2: Verificar estructura de archivos

Asegúrate de que la estructura sea exactamente así:

aliah-plus/
├── app.py
├── start.py          ← NUEVO
├── Dockerfile
├── requirements.txt
│
└── src/
    ├── __init__.py   ← IMPORTANTE
    ├── face_processor.py
    ├── embedding_engine.py
    ├── comparator.py
    ├── ocr_extractor.py
    ├── cross_referencer.py
    ├── vector_db.py
    │
    └── scrapers/
        ├── __init__.py   ← IMPORTANTE
        └── stealth_engine.py

CRÍTICO: Los archivos __init__.py deben existir en:

  • src/__init__.py
  • src/scrapers/__init__.py

✅ SOLUCIÓN 3: Verificar archivos init.py

Si los archivos __init__.py no existen o están vacíos, créalos:

src/init.py

"""
Aliah-Plus - Sistema Avanzado de Re-Identificación Facial
"""

__version__ = "1.0.0"
__author__ = "Aliah-Plus Team"

from .face_processor import FaceProcessor
from .embedding_engine import EmbeddingEngine
from .comparator import FaceComparator
from .ocr_extractor import OCRExtractor
from .cross_referencer import CrossReferencer
from .vector_db import VectorDatabase

__all__ = [
    'FaceProcessor',
    'EmbeddingEngine',
    'FaceComparator',
    'OCRExtractor',
    'CrossReferencer',
    'VectorDatabase',
]

src/scrapers/init.py

"""
Scrapers module - Web scraping engines with stealth capabilities
"""

from .stealth_engine import StealthSearch

__all__ = ['StealthSearch']

✅ SOLUCIÓN 4: Variables de entorno en Dockerfile

El Dockerfile ya incluye:

ENV PYTHONPATH=/code

Esto asegura que Python pueda encontrar los módulos en /code/src.


✅ SOLUCIÓN 5: Comando de inicio correcto

Opción A: Con start.py (Recomendado)

CMD ["python", "start.py"]

Opción B: Con uvicorn directamente

CMD ["python", "-m", "uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]

🧪 TESTING: Verificar que funciona

Test local:

# 1. Verificar estructura
ls -R src/

# 2. Verificar __init__.py existe
test -f src/__init__.py && echo "✓ src/__init__.py exists"
test -f src/scrapers/__init__.py && echo "✓ src/scrapers/__init__.py exists"

# 3. Test imports
python -c "from src.face_processor import FaceProcessor; print('✓ Import works')"

# 4. Iniciar con start.py
python start.py

Test en Docker:

# 1. Build
docker build -t aliah-plus .

# 2. Run con logs
docker run -p 7860:7860 aliah-plus

# Deberías ver:
# ====================================
# Aliah-Plus Startup
# ====================================
# [1/4] Checking Python path...
# [2/4] Checking source files...
#   ✓ app.py
#   ✓ src/__init__.py
#   ...
# [3/4] Testing imports...
#   ✓ FaceProcessor
#   ✓ EmbeddingEngine
#   ...
# [4/4] Starting FastAPI server...

🔍 DIAGNÓSTICO: Si sigue fallando

1. Verificar logs completos

# Hugging Face Spaces
# Ve a tu Space → Pestaña "Logs"
# Busca líneas con "ModuleNotFoundError"

# Docker
docker logs <container_id>

2. Verificar que archivos se copiaron

# Entrar al container
docker run -it aliah-plus /bin/bash

# Dentro del container
ls -la /code/src/
cat /code/src/__init__.py

# Verificar PYTHONPATH
echo $PYTHONPATH

# Test manual
python -c "import sys; print(sys.path)"
python -c "from src.face_processor import FaceProcessor"

3. Verificar permisos

# En el host
ls -la src/
# Todos los archivos deben ser legibles

# Si hay problemas de permisos
chmod -R 755 src/

🚀 DEPLOYMENT EN HUGGING FACE SPACES

Pasos para re-deployar con la corrección:

  1. Actualiza tu repositorio local:

    cd aliah-plus
    git pull  # O descarga el proyecto actualizado
    
  2. Verifica que start.py existe:

    ls -la start.py
    # Debe existir y tener ~100 líneas
    
  3. Verifica Dockerfile actualizado:

    grep "start.py" Dockerfile
    # Debe mostrar: CMD ["python", "start.py"]
    
  4. Push a Hugging Face:

    git add .
    git commit -m "Fix: Add start.py to handle module imports"
    git push
    
  5. Espera el rebuild:

    • Ve a tu Space en HF
    • El container se reconstruirá automáticamente
    • Revisa los logs para ver el proceso de inicio

📊 CHECKLIST DE SOLUCIÓN

Marca cada item cuando lo completes:

  • ✅ Archivo start.py existe en la raíz
  • ✅ Archivo src/__init__.py existe y tiene contenido
  • ✅ Archivo src/scrapers/__init__.py existe y tiene contenido
  • ✅ Dockerfile tiene CMD ["python", "start.py"]
  • app.py tiene el código de importación actualizado (con try/except)
  • ✅ Tests locales pasan: python start.py
  • ✅ Docker build funciona: docker build -t aliah-plus .
  • ✅ Docker run funciona: docker run -p 7860:7860 aliah-plus
  • ✅ Pushed a Hugging Face Spaces
  • ✅ Space se construye sin errores
  • ✅ Health check responde: curl http://localhost:7860/health

🎯 RESULTADO ESPERADO

Cuando todo funcione correctamente, deberías ver:

===== Application Startup at 2026-01-29 01:30:00 =====

============================================================
Aliah-Plus Startup
============================================================

[1/4] Checking Python path...
Current directory: /code
Python path includes: True

[2/4] Checking source files...
  ✓ app.py
  ✓ src/__init__.py
  ✓ src/face_processor.py
  ✓ src/embedding_engine.py
  ✓ src/comparator.py
  ✓ src/ocr_extractor.py
  ✓ src/cross_referencer.py
  ✓ src/vector_db.py
  ✓ src/scrapers/__init__.py
  ✓ src/scrapers/stealth_engine.py

[3/4] Testing imports...
  ✓ FaceProcessor
  ✓ EmbeddingEngine
  ✓ FaceComparator
  ✓ OCRExtractor
  ✓ CrossReferencer
  ✓ VectorDatabase
  ✓ StealthSearch

[4/4] Starting FastAPI server...
============================================================
INFO:     Started server process [1]
INFO:     Waiting for application startup.
INFO:     Application startup complete.
INFO:     Uvicorn running on http://0.0.0.0:7860 (Press CTRL+C to quit)

💡 EXPLICACIÓN TÉCNICA

¿Por qué ocurre este error?

  1. Python no sabe dónde buscar módulos

    • Por defecto, Python busca en sys.path
    • Si /code no está en sys.path, no encuentra src
  2. Diferencia entre desarrollo y producción

    • Local: Python encuentra módulos relativos fácilmente
    • Docker/HF: Estructura de directorios diferente
  3. Solución con start.py

    • Añade /code al sys.path explícitamente
    • Verifica archivos antes de importar
    • Proporciona diagnóstico útil

📞 ¿Aún tienes problemas?

Si después de seguir todos los pasos sigue fallando:

  1. Captura los logs completos del startup
  2. Verifica el contenido de start.py, app.py, y Dockerfile
  3. Comparte el error específico que aparece

✅ Con estas correcciones, el proyecto debería funcionar correctamente en Hugging Face Spaces!