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 lines891011121314151617181920214 unmodified lines262728293031323334357 unmodified linescurl \&& 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# 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.pyEXPOSE 7860# DémarrerCMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]7 unmodified lines8910111213141516174 unmodified lines222324252627287 unmodified linescurl \&& rm -rf /var/lib/apt/lists/*# 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 .EXPOSE 7860# DémarrerCMD ["uvicorn", "api:app", "--host", "0.0.0.0", "--port", "7860"]
10 unmodified lines111213141516171819202122232425262714 unmodified lines4243444546474811 unmodified lines60616263646525 unmodified lines9192939495963 unmodified lines100101102103104105106107108106 unmodified lines21521621721821922022188 unmodified lines3103113123133143153163173183193205 unmodified lines32632732832933033133233333433533610 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 Llamafrom llama_cpp.server.app import create_app, Settingsexcept ImportError:# Fallback si llama_cpp_python n'est pas installéLlama = None# ========== CONFIGURATION ==========MODEL_REPO = "bartowski/DeepSeek-Coder-1.3B-Instruct-GGUF"MODEL_FILES = ["DeepSeek-Coder-1.3B-Instruct-Q4_K_M.gguf", # 900MB - Bon compromis14 unmodified linesstream: bool = Falseclass ChatMessage(BaseModel):role: str = Field(..., regex="^(user|assistant|system)$")content: strclass ChatRequest(BaseModel):11 unmodified linesdef find_or_download_model(self):"""Trouver ou télécharger le modèle GGUF"""# 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.llmprint("🔧 Chargement du modèle...")self.loading = True3 unmodified linesself.model_path = self.find_or_download_model()# Configurer le modèle (optimisé pour Hugging Face 16GB RAM)n_gpu_layers = -1 # Utiliser GPU si disponiblen_threads = 4 # 4 threads CPUn_ctx = 2048 # Contexte limité pour économiser la RAMprint(f"🔄 Chargement depuis: {self.model_path}")print(f"⚙️ Configuration: GPU layers={n_gpu_layers}, Threads={n_threads}, Context={n_ctx}")106 unmodified linesdescription="API ultra-rapide avec llama_cpp_python",version="2.0.0",docs_url="/docs",redoc_url="/redoc",lifespan=lifespan)88 unmodified linesasync def list_models():"""Lister les modèles disponibles"""models = []if 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,"loaded": model_manager.llm is not None})5 unmodified linesexamples = [{"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}\''},{"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}\''}]return {"examples": examples}10 unmodified lines111213141516171819202122232425262728293031323314 unmodified lines4849505152535411 unmodified lines66676869707172737425 unmodified lines1001011021031041051061071083 unmodified lines112113114115116117118119120106 unmodified lines22722822923023123223388 unmodified lines3223233243253263273283293303313325 unmodified lines33833934034134234334434534634734810 unmodified linesfrom fastapi import FastAPI, HTTPExceptionfrom fastapi.middleware.cors import CORSMiddlewarefrom pydantic import BaseModel, Field# Import llama_cpptry:from llama_cpp import Llamaexcept 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_downloadHF_AVAILABLE = Trueexcept ImportError:HF_AVAILABLE = FalseMODEL_REPO = "bartowski/DeepSeek-Coder-1.3B-Instruct-GGUF"MODEL_FILES = ["DeepSeek-Coder-1.3B-Instruct-Q4_K_M.gguf", # 900MB - Bon compromis14 unmodified linesstream: bool = Falseclass ChatMessage(BaseModel):role: str = Field(..., pattern="^(user|assistant|system)$")content: strclass ChatRequest(BaseModel):11 unmodified linesdef 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.llmif Llama is None:raise Exception("llama_cpp n'est pas installé")print("🔧 Chargement du modèle...")self.loading = True3 unmodified linesself.model_path = self.find_or_download_model()# Configurer le modèle (optimisé pour Hugging Face 16GB RAM)n_gpu_layers = 0 # Pas de GPU sur Hugging Face Spaces gratuitn_threads = 2 # 2 threads CPU (conservateur)n_ctx = 1024 # Contexte limité pour économiser la RAMprint(f"🔄 Chargement depuis: {self.model_path}")print(f"⚙️ Configuration: GPU layers={n_gpu_layers}, Threads={n_threads}, Context={n_ctx}")106 unmodified linesdescription="API ultra-rapide avec llama_cpp_python",version="2.0.0",docs_url="/docs",redoc_url=None,lifespan=lifespan)88 unmodified linesasync def list_models():"""Lister les modèles disponibles"""models = []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": round(os.path.getsize(model_manager.model_path) / 1024 / 1024, 2),"loaded": model_manager.llm is not None})5 unmodified linesexamples = [{"endpoint": "POST /generate","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://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}
1234567891 unmodified line11121314151626 unmodified lines4344454647484950"""Télécharger le modèle DeepSeek-Coder au format GGUF"""from huggingface_hub import hf_hub_downloadimport os# ConfigurationMODEL_REPO = "bartowski/DeepSeek-Coder-1.3B-Instruct-GGUF"MODEL_FILE = "DeepSeek-Coder-1.3B-Instruct-Q4_K_M.gguf"1 unmodified linedef download_model():"""Télécharger le modèle GGUF"""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_pathexcept:print("❌ Impossible de télécharger aucun modèle")return Noneif __name__ == "__main__":1234567891011121314151 unmodified line1718192021222324252626 unmodified lines5354555657585960"""Télécharger le modèle DeepSeek-Coder au format GGUF"""import ostry:from huggingface_hub import hf_hub_downloadHF_AVAILABLE = Trueexcept ImportError:HF_AVAILABLE = Falseprint("❌ 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 linedef download_model():"""Télécharger le modèle GGUF"""if not HF_AVAILABLE:print("❌ Impossible de télécharger: huggingface-hub non disponible")return Noneos.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_pathexcept Exception as e2:print(f"❌ Impossible de télécharger aucun modèle: {e2}")return Noneif __name__ == "__main__":
1234fastapiuvicornllama-cpp-python==0.2.77pydantic12345fastapiuvicorn[standard]==0.24.0llama-cpp-python==0.2.77pydantic==2.5.0huggingface-hub==0.20.3
Dockerfile+5-12
api.py+23-11
download_model.py+13-3
requirements.txt+3-2