Spaces:
Sleeping
Sleeping
pakito312 commited on
Commit ·
5143de5
1
Parent(s): ca1c16e
update
Browse filesFiles changed (4)
- Dockerfile+5-12
- api.py+23-11
- download_model.py+13-3
- requirements.txt+3-2
7 unmodified lines89101112131415161718111213141516174 unmodified lines22232429303125262735287 unmodified lines curl \ && rm -rf /var/lib/apt/lists/*
# Installer llama-cpp-python avec support CUDA (si disponible)RUN pip install --no-cache-dir \ llama-cpp-python[server] \ fastapi \ uvicorn \ pydantic \ requests \ huggingface-hub# Installer les dépendances PythonCOPY requirements.txt .RUN pip install --no-cache-dir -r requirements.txtRUN pip install --no-cache-dir huggingface-hub
# Créer un utilisateur non-rootRUN useradd -m -u 1000 user4 unmodified linesCOPY --chown=user:user api.py .COPY --chown=user:user download_model.py .
# Télécharger le modèle GGUF au build (optionnel)# RUN python download_model.py
EXPOSE 7860
# DémarrerCMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]CMD ["uvicorn", "api:app", "--host", "0.0.0.0", "--port", "7860"]10 unmodified lines1112131414151617191819202122232425262728293031323314 unmodified lines484950455152535411 unmodified lines66676869707172737425 unmodified lines1001011021031041051061071083 unmodified lines112113114103104105115116117118119120106 unmodified lines22722822921823023123223388 unmodified lines3223233243133253263273283173293303313325 unmodified lines33833934032934134234334433334534634734810 unmodified linesfrom fastapi import FastAPI, HTTPExceptionfrom fastapi.middleware.cors import CORSMiddlewarefrom pydantic import BaseModel, Fieldfrom huggingface_hub import hf_hub_download
# Import llama_cpptry: from llama_cpp import Llama from llama_cpp.server.app import create_app, Settingsexcept ImportError: # Fallback si llama_cpp_python n'est pas installé Llama = None
# ========== CONFIGURATION ==========# IMPORTANT: huggingface_hub doit être importé APRÈS les vérifications# car il peut causer des conflits d'importtry: from huggingface_hub import hf_hub_download HF_AVAILABLE = Trueexcept ImportError: HF_AVAILABLE = False
MODEL_REPO = "bartowski/DeepSeek-Coder-1.3B-Instruct-GGUF"MODEL_FILES = [ "DeepSeek-Coder-1.3B-Instruct-Q4_K_M.gguf", # 900MB - Bon compromis14 unmodified lines stream: bool = False
class ChatMessage(BaseModel): role: str = Field(..., regex="^(user|assistant|system)$") role: str = Field(..., pattern="^(user|assistant|system)$") content: str
class ChatRequest(BaseModel):11 unmodified lines def find_or_download_model(self): """Trouver ou télécharger le modèle GGUF""" if not HF_AVAILABLE: raise Exception("huggingface-hub n'est pas installé") # Vérifier si un modèle existe déjà for model_file in MODEL_FILES: local_path = os.path.join(MODEL_DIR, model_file)25 unmodified lines """Charger le modèle avec llama_cpp""" if self.llm is not None: return self.llm if Llama is None: raise Exception("llama_cpp n'est pas installé") print("🔧 Chargement du modèle...") self.loading = True3 unmodified lines self.model_path = self.find_or_download_model() # Configurer le modèle (optimisé pour Hugging Face 16GB RAM) n_gpu_layers = -1 # Utiliser GPU si disponible n_threads = 4 # 4 threads CPU n_ctx = 2048 # Contexte limité pour économiser la RAM n_gpu_layers = 0 # Pas de GPU sur Hugging Face Spaces gratuit n_threads = 2 # 2 threads CPU (conservateur) n_ctx = 1024 # Contexte limité pour économiser la RAM print(f"🔄 Chargement depuis: {self.model_path}") print(f"⚙️ Configuration: GPU layers={n_gpu_layers}, Threads={n_threads}, Context={n_ctx}")106 unmodified lines description="API ultra-rapide avec llama_cpp_python", version="2.0.0", docs_url="/docs", redoc_url="/redoc", redoc_url=None, lifespan=lifespan)
88 unmodified linesasync def list_models(): """Lister les modèles disponibles""" models = [] if model_manager.model_path: if model_manager.model_path and os.path.exists(model_manager.model_path): models.append({ "name": "deepseek-coder-1.3b", "path": model_manager.model_path, "size_mb": os.path.getsize(model_manager.model_path) / 1024 / 1024 if os.path.exists(model_manager.model_path) else 0, "size_mb": round(os.path.getsize(model_manager.model_path) / 1024 / 1024, 2), "loaded": model_manager.llm is not None }) 5 unmodified lines examples = [ { "endpoint": "POST /generate", "curl": 'curl -X POST https://your-api.space/generate -H "Content-Type: application/json" -d \'{"prompt": "def fibonacci(n):", "temperature": 0.2}\'' "curl": 'curl -X POST https://digitaldev2024-allma.hf.space/generate -H "Content-Type: application/json" -d \'{"prompt": "def fibonacci(n):", "temperature": 0.2}\'' }, { "endpoint": "POST /chat", "curl": 'curl -X POST https://your-api.space/chat -H "Content-Type: application/json" -d \'{"messages": [{"role": "user", "content": "Write Python code for binary search"}], "temperature": 0.2}\'' "curl": 'curl -X POST https://digitaldev2024-allma.hf.space/chat -H "Content-Type: application/json" -d \'{"messages": [{"role": "user", "content": "Write Python code for binary search"}], "temperature": 0.2}\'' } ] return {"examples": examples}12344567891011121314151 unmodified line1718192021222324252626 unmodified lines53545546475657585960"""Télécharger le modèle DeepSeek-Coder au format GGUF"""from huggingface_hub import hf_hub_downloadimport os
try: from huggingface_hub import hf_hub_download HF_AVAILABLE = Trueexcept ImportError: HF_AVAILABLE = False print("❌ huggingface-hub n'est pas installé")
# ConfigurationMODEL_REPO = "bartowski/DeepSeek-Coder-1.3B-Instruct-GGUF"MODEL_FILE = "DeepSeek-Coder-1.3B-Instruct-Q4_K_M.gguf"1 unmodified line
def download_model(): """Télécharger le modèle GGUF""" if not HF_AVAILABLE: print("❌ Impossible de télécharger: huggingface-hub non disponible") return None os.makedirs(LOCAL_PATH, exist_ok=True) print(f"📥 Téléchargement de {MODEL_FILE}...")26 unmodified lines ) print(f"✅ Modèle de secours téléchargé") return model_path except: print("❌ Impossible de télécharger aucun modèle") except Exception as e2: print(f"❌ Impossible de télécharger aucun modèle: {e2}") return None
if __name__ == "__main__":1223445fastapiuvicornuvicorn[standard]==0.24.0llama-cpp-python==0.2.77pydanticpydantic==2.5.0huggingface-hub==0.20.3Dockerfile+5-12
api.py+23-11
download_model.py+13-3
requirements.txt+3-2