00-5: ComfyUI Local - Test Rapide

Navigation : Index | << Précédent | Suivant >>

Objectif: Valider connexion et génération basique ComfyUI local

Prérequis: - ComfyUI démarré sur port 8188 - Modèle Qwen-Image-Edit-2509-FP8 chargé - Custom nodes Qwen installés

Durée: ~2-3 minutes

Cell 1: Import et Configuration

# Import guards - availability flags for external dependencies

try:
    from dotenv import load_dotenv
    DOTENV_AVAILABLE = True
except ImportError:
    DOTENV_AVAILABLE = False
    print(f'  dotenv non disponible - certaines fonctionnalites seront limitees')


# Imports
import sys
import os
from dotenv import load_dotenv

# Ajouter shared helpers au path
# Note: Papermill exécute depuis le répertoire du notebook, pas depuis la racine
# On utilise donc un chemin absolu pour garantir la compatibilité
shared_path = r'MyIA.AI.Notebooks\GenAI\shared'
if shared_path not in sys.path:
    sys.path.insert(0, shared_path)

# Import avec gestion d'erreur
try:
    from helpers.comfyui_client import create_client, ComfyUIConfig
    print("✅ Imports réussis")
    comfyui_helpers_available = True
except ImportError as e:
    print(f"⚠️ Import ComfyUI helpers non disponible: {e}")
    comfyui_helpers_available = False
except Exception as e:
    print(f"⚠️ Erreur import ComfyUI helpers: {e}")
    comfyui_helpers_available = False
⚠️ Import ComfyUI helpers non disponible: No module named 'helpers'

Cell 2: Test Connexion ComfyUI

# Test connexion rapide via create_client()
print("🔍 Test connexion ComfyUI...")

client = None
comfyui_accessible = False

if not comfyui_helpers_available:
    print("\n⏭️ Helpers ComfyUI non disponibles - test ignoré")
else:
    try:
        test_client = create_client()
        
        # Test basique avec /system_stats
        stats = test_client.get_system_stats()
        
        print("\n✅ ComfyUI accessible!")
        comfyui_accessible = True
        
        if stats:
            system = stats.get('system', {})
            print(f"\n📊 Statistiques Système:")
            print(f"   - PyTorch: {system.get('pytorch_version', 'N/A')}")
            print(f"   - CUDA: {system.get('cuda', 'N/A')}")
            print(f"   - ComfyUI: {system.get('comfyui_version', 'N/A')}")
            print(f"   - Python: {system.get('python_version', 'N/A')}")
        
    except ConnectionError as e:
        print("\n❌ ComfyUI non accessible (ConnectionError)!")
        print(f"   Erreur: {e}")
        print("   Vérifier que le service est démarré sur port 8188")
    except Exception as e:
        print("\n❌ ComfyUI non accessible!")
        print(f"   Erreur: {type(e).__name__}: {e}")
        print("   Vérifier que le service est démarré sur port 8188")
🔍 Test connexion ComfyUI...

⏭️ Helpers ComfyUI non disponibles - test ignoré

Interpretation du test de connexion

La connexion a ComfyUI a ete testee via l’endpoint /system_stats.

Résultat attendu : - Si ComfyUI est accessible : Statistiques système affichees (PyTorch, CUDA, ComfyUI version) - Si ComfyUI n’est pas accessible : Message d’erreur avec instructions

Composantes verifiees : - Service ComfyUI demarre sur le port 8188 - Endpoint API repondant - Compatilite PyTorch/CUDA

Note technique : Si la connexion echoue, verifiez que ComfyUI est demarre avec docker ps ou en accedant a http://localhost:8188 dans un navigateur.

Cell 3: Créer Client ComfyUI

# Créer client
try:
    # Charger configuration
    load_dotenv()
    token = os.getenv("COMFYUI_API_TOKEN") or os.getenv("QWEN_API_TOKEN")
    
    if token:
        print("🔐 Token trouvé dans l'environnement")
        config = ComfyUIConfig(api_token=token)
        client = create_client(config)
    else:
        print("⚠️ Aucun token trouvé, tentative de connexion anonyme...")
        client = create_client()

    print("✅ Client ComfyUI créé avec succès")
except ConnectionError as e:
    print(f"❌ Erreur connexion: {e}")
    client = None
except Exception as e:
    print(f"❌ Erreur création client: {type(e).__name__}: {e}")
    client = None
🔐 Token trouvé dans l'environnement
❌ Erreur création client: NameError: name 'ComfyUIConfig' is not defined

Cell 4: Génération Text-to-Image Simple

# Génération image test
prompt_id = None

if client:
    print("🎨 Lancement génération...")
    print("   Prompt: 'A beautiful sunset over mountains'")
    print("   Résolution: 512x512")
    print("   Steps: 20")
    print("\n⏳ Génération en cours (5-10 secondes)...\n")
    
    try:
        prompt_id = client.generate_text2image(
            prompt="A beautiful sunset over mountains",
            negative_prompt="blurry, low quality, distorted",
            width=512,
            height=512,
            steps=20,
            cfg=7.0,
            seed=42,  # Reproductible
            save_prefix="test_phase13a"
        )
        
        if prompt_id:
            print(f"\n✅ Génération réussie!")
            print(f"   Prompt ID: {prompt_id}")
            print(f"\n💾 Image sauvegardée dans ComfyUI output/")
        else:
            print("\n❌ Génération échouée")
            print("   Vérifier logs ComfyUI pour détails")
    except Exception as e:
        print(f"\n❌ Erreur génération: {type(e).__name__}: {e}")
        prompt_id = None
else:
    print("❌ Client non initialisé - génération ignorée")
❌ Client non initialisé - génération ignorée

Cell 5: Résumé Test

# Résumé
print("="*60)
print("📋 RÉSUMÉ TEST PHASE 13A")
print("="*60)

if client and prompt_id:
    print("\n✅ Status: SUCCESS")
    print("\n🎯 Accomplissements:")
    print("   ✅ ComfyUI accessible")
    print("   ✅ Client Python opérationnel")
    print("   ✅ Génération text-to-image validée")
    print("   ✅ Bridge ComfyUI fonctionnel")
    
    print("\n🚀 Prêt pour Phase 13B:")
    print("   - Implémentation notebook 02-1 complet")
    print("   - Workflows avancés (image-to-image, etc.)")
    print("   - Intégration pédagogique complète")
else:
    print("\n⚠️ Status: PARTIAL")
    print("\n❌ Problèmes détectés:")
    if not client:
        print("   - Connexion ComfyUI échouée")
    if client and not prompt_id:
        print("   - Génération échouée (workflow incompatible?)")
    
    print("\n📚 Troubleshooting:")
    print("   1. Vérifier ComfyUI démarré: http://localhost:8188")
    print("   2. Vérifier modèle Qwen chargé")
    print("   3. Consulter logs ComfyUI")
    print("   4. Voir: TROUBLESHOOTING.md")

print("\n" + "="*60)
============================================================
📋 RÉSUMÉ TEST PHASE 13A
============================================================

⚠️ Status: PARTIAL

❌ Problèmes détectés:
   - Connexion ComfyUI échouée

📚 Troubleshooting:
   1. Vérifier ComfyUI démarré: http://localhost:8188
   2. Vérifier modèle Qwen chargé
   3. Consulter logs ComfyUI
   4. Voir: TROUBLESHOOTING.md

============================================================
Retour au sommet