Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -2,43 +2,17 @@ from fastapi import FastAPI, Request, HTTPException
|
|
| 2 |
import os
|
| 3 |
import requests
|
| 4 |
from typing import Dict, Any
|
| 5 |
-
from transformers import pipeline
|
| 6 |
-
from huggingface_hub import login
|
| 7 |
|
| 8 |
app = FastAPI()
|
| 9 |
|
| 10 |
-
#
|
| 11 |
BOT_USERNAME = "@DiscussionBot"
|
| 12 |
-
|
|
|
|
| 13 |
|
| 14 |
-
#
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
os.makedirs(CACHE_DIR, exist_ok=True) # Créer le répertoire s'il n'existe pas
|
| 18 |
-
print(f"Cache directory set to {CACHE_DIR}")
|
| 19 |
-
except Exception as e:
|
| 20 |
-
print(f"Warning: Unable to create cache directory {CACHE_DIR}: {str(e)}")
|
| 21 |
-
raise
|
| 22 |
-
|
| 23 |
-
# Vérification du jeton et connexion à Hugging Face
|
| 24 |
-
try:
|
| 25 |
-
HF_TOKEN = os.getenv("HF_TOKEN")
|
| 26 |
-
if not HF_TOKEN:
|
| 27 |
-
print("Warning: HF_TOKEN is not set. Using public model gpt2 which may not require a token.")
|
| 28 |
-
else:
|
| 29 |
-
login(token=HF_TOKEN) # Authentifie avec le jeton
|
| 30 |
-
print("Successfully authenticated with Hugging Face")
|
| 31 |
-
except Exception as e:
|
| 32 |
-
print(f"Failed to authenticate with Hugging Face: {str(e)}")
|
| 33 |
-
# Continue si le modèle ne nécessite pas de jeton
|
| 34 |
-
|
| 35 |
-
# Initialisation du pipeline
|
| 36 |
-
try:
|
| 37 |
-
pipe = pipeline("text-generation", model=MODEL, token=HF_TOKEN if HF_TOKEN else None, cache_dir=CACHE_DIR)
|
| 38 |
-
print(f"Successfully initialized pipeline for model {MODEL}")
|
| 39 |
-
except Exception as e:
|
| 40 |
-
print(f"Failed to initialize pipeline for model {MODEL}: {str(e)}")
|
| 41 |
-
raise
|
| 42 |
|
| 43 |
@app.get("/")
|
| 44 |
async def root(request: Request) -> Dict[str, Any]:
|
|
@@ -76,14 +50,34 @@ async def webhook(request: Request) -> Dict[str, Any]:
|
|
| 76 |
):
|
| 77 |
print(f"Processing comment: {data['comment']['content']}")
|
| 78 |
|
| 79 |
-
# Préparation du prompt
|
| 80 |
input_text = f"Faites comme si vous étiez un robot qui répond aux discussions sur l'apprentissage automatique et répondez au commentaire suivant :\n{data['comment']['content']}"
|
| 81 |
|
| 82 |
-
#
|
| 83 |
try:
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 87 |
except Exception as e:
|
| 88 |
error_message = f"Inference failed: {str(e)}"
|
| 89 |
print(error_message)
|
|
|
|
| 2 |
import os
|
| 3 |
import requests
|
| 4 |
from typing import Dict, Any
|
|
|
|
|
|
|
| 5 |
|
| 6 |
app = FastAPI()
|
| 7 |
|
| 8 |
+
# Configuration de l'API d'inférence Hugging Face
|
| 9 |
BOT_USERNAME = "@DiscussionBot"
|
| 10 |
+
INFERENCE_API_URL = "https://api-inference.huggingface.co/models/gpt2"
|
| 11 |
+
HF_TOKEN = os.getenv("HF_TOKEN")
|
| 12 |
|
| 13 |
+
# Vérification du jeton API
|
| 14 |
+
if not HF_TOKEN:
|
| 15 |
+
raise ValueError("HF_TOKEN environment variable is not set. Please set it with a valid Hugging Face API token.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
|
| 17 |
@app.get("/")
|
| 18 |
async def root(request: Request) -> Dict[str, Any]:
|
|
|
|
| 50 |
):
|
| 51 |
print(f"Processing comment: {data['comment']['content']}")
|
| 52 |
|
| 53 |
+
# Préparation du prompt pour l'API d'inférence
|
| 54 |
input_text = f"Faites comme si vous étiez un robot qui répond aux discussions sur l'apprentissage automatique et répondez au commentaire suivant :\n{data['comment']['content']}"
|
| 55 |
|
| 56 |
+
# Requête à l'API d'inférence
|
| 57 |
try:
|
| 58 |
+
response = requests.post(
|
| 59 |
+
INFERENCE_API_URL,
|
| 60 |
+
headers={
|
| 61 |
+
"Authorization": f"Bearer {HF_TOKEN}",
|
| 62 |
+
"Content-Type": "application/json",
|
| 63 |
+
},
|
| 64 |
+
json={
|
| 65 |
+
"inputs": input_text,
|
| 66 |
+
"parameters": {
|
| 67 |
+
"max_new_tokens": 100,
|
| 68 |
+
"num_return_sequences": 1
|
| 69 |
+
}
|
| 70 |
+
}
|
| 71 |
+
)
|
| 72 |
+
response.raise_for_status() # Lever une exception pour les erreurs HTTP
|
| 73 |
+
output = response.json()
|
| 74 |
+
print(f"API response: {output}")
|
| 75 |
+
|
| 76 |
+
# Extraction du texte généré
|
| 77 |
+
if isinstance(output, list) and len(output) > 0:
|
| 78 |
+
continuation_text = output[0]["generated_text"].replace(input_text, "").strip()
|
| 79 |
+
else:
|
| 80 |
+
raise ValueError("Unexpected response format from inference API")
|
| 81 |
except Exception as e:
|
| 82 |
error_message = f"Inference failed: {str(e)}"
|
| 83 |
print(error_message)
|