Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -4,7 +4,6 @@ import requests
|
|
| 4 |
from typing import Dict, Any
|
| 5 |
from openai import OpenAI
|
| 6 |
import httpx
|
| 7 |
-
import time
|
| 8 |
|
| 9 |
app = FastAPI()
|
| 10 |
|
|
@@ -16,35 +15,39 @@ MODEL = "mistralai/mixtral-8x7b-instruct-v0.1"
|
|
| 16 |
|
| 17 |
# Vérification de la clé API NVIDIA
|
| 18 |
if not NVIDIA_API_KEY:
|
| 19 |
-
raise ValueError("NVIDIA_API_KEY environment variable is not set.")
|
| 20 |
|
| 21 |
-
# Vérification du jeton Hugging Face
|
| 22 |
HF_TOKEN = os.getenv("HF_TOKEN")
|
| 23 |
if not HF_TOKEN:
|
| 24 |
-
raise ValueError("HF_TOKEN environment variable is not set.")
|
| 25 |
|
| 26 |
-
# Initialisation du client NVIDIA
|
| 27 |
try:
|
| 28 |
client = OpenAI(
|
| 29 |
base_url=NVIDIA_API_URL,
|
| 30 |
api_key=NVIDIA_API_KEY,
|
| 31 |
-
http_client=httpx.Client(
|
| 32 |
)
|
|
|
|
| 33 |
except Exception as e:
|
| 34 |
-
|
|
|
|
| 35 |
|
| 36 |
@app.get("/")
|
| 37 |
async def root(request: Request) -> Dict[str, Any]:
|
| 38 |
"""
|
| 39 |
Gère les requêtes GET et renvoie une réponse JSON simple.
|
| 40 |
"""
|
| 41 |
-
|
| 42 |
"method": request.method,
|
| 43 |
"host": request.headers.get("host", "unknown"),
|
| 44 |
"user_agent": request.headers.get("user-agent", "unknown"),
|
| 45 |
"query_test": request.query_params.get("test", None),
|
| 46 |
"message": "Webhook server is running. Use POST to interact with the bot."
|
| 47 |
}
|
|
|
|
|
|
|
| 48 |
|
| 49 |
@app.post("/")
|
| 50 |
async def webhook(request: Request) -> Dict[str, Any]:
|
|
@@ -53,7 +56,9 @@ async def webhook(request: Request) -> Dict[str, Any]:
|
|
| 53 |
"""
|
| 54 |
try:
|
| 55 |
if request.headers.get("X-Webhook-Secret") != os.getenv("WEBHOOK_SECRET"):
|
| 56 |
-
|
|
|
|
|
|
|
| 57 |
|
| 58 |
data = await request.json()
|
| 59 |
event = data.get("event", {})
|
|
@@ -63,6 +68,8 @@ async def webhook(request: Request) -> Dict[str, Any]:
|
|
| 63 |
and event.get("scope") == "discussion.comment"
|
| 64 |
and BOT_USERNAME in data.get("comment", {}).get("content", "")
|
| 65 |
):
|
|
|
|
|
|
|
| 66 |
# Préparation du prompt pour l'API NVIDIA
|
| 67 |
messages = [
|
| 68 |
{
|
|
@@ -81,44 +88,50 @@ async def webhook(request: Request) -> Dict[str, Any]:
|
|
| 81 |
max_tokens=100,
|
| 82 |
stream=True
|
| 83 |
)
|
|
|
|
| 84 |
continuation_text = ""
|
| 85 |
for chunk in completion:
|
| 86 |
if chunk.choices[0].delta.content is not None:
|
| 87 |
continuation_text += chunk.choices[0].delta.content
|
| 88 |
continuation_text = continuation_text.strip()
|
|
|
|
|
|
|
| 89 |
if not continuation_text:
|
| 90 |
raise ValueError("No text generated by NVIDIA API")
|
| 91 |
except Exception as e:
|
| 92 |
-
|
|
|
|
|
|
|
| 93 |
|
| 94 |
-
# Publication du commentaire
|
| 95 |
comment_url = data["discussion"]["url"]["api"] + "/comment"
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
raise HTTPException(status_code=429, detail="Rate limit exceeded after retries")
|
| 115 |
|
|
|
|
| 116 |
return {"success": False}
|
| 117 |
|
| 118 |
except HTTPException as he:
|
| 119 |
raise he
|
| 120 |
except Exception as e:
|
| 121 |
-
|
|
|
|
|
|
|
| 122 |
|
| 123 |
if __name__ == "__main__":
|
| 124 |
import uvicorn
|
|
|
|
| 4 |
from typing import Dict, Any
|
| 5 |
from openai import OpenAI
|
| 6 |
import httpx
|
|
|
|
| 7 |
|
| 8 |
app = FastAPI()
|
| 9 |
|
|
|
|
| 15 |
|
| 16 |
# Vérification de la clé API NVIDIA
|
| 17 |
if not NVIDIA_API_KEY:
|
| 18 |
+
raise ValueError("NVIDIA_API_KEY environment variable is not set. Please set it with a valid NVIDIA API key.")
|
| 19 |
|
| 20 |
+
# Vérification du jeton Hugging Face pour la publication des commentaires
|
| 21 |
HF_TOKEN = os.getenv("HF_TOKEN")
|
| 22 |
if not HF_TOKEN:
|
| 23 |
+
raise ValueError("HF_TOKEN environment variable is not set. Please set it with a valid Hugging Face API token.")
|
| 24 |
|
| 25 |
+
# Initialisation du client NVIDIA avec un client HTTP personnalisé
|
| 26 |
try:
|
| 27 |
client = OpenAI(
|
| 28 |
base_url=NVIDIA_API_URL,
|
| 29 |
api_key=NVIDIA_API_KEY,
|
| 30 |
+
http_client=httpx.Client()
|
| 31 |
)
|
| 32 |
+
print("Successfully initialized NVIDIA API client")
|
| 33 |
except Exception as e:
|
| 34 |
+
print(f"Failed to initialize NVIDIA API client: {str(e)}")
|
| 35 |
+
raise
|
| 36 |
|
| 37 |
@app.get("/")
|
| 38 |
async def root(request: Request) -> Dict[str, Any]:
|
| 39 |
"""
|
| 40 |
Gère les requêtes GET et renvoie une réponse JSON simple.
|
| 41 |
"""
|
| 42 |
+
request_details = {
|
| 43 |
"method": request.method,
|
| 44 |
"host": request.headers.get("host", "unknown"),
|
| 45 |
"user_agent": request.headers.get("user-agent", "unknown"),
|
| 46 |
"query_test": request.query_params.get("test", None),
|
| 47 |
"message": "Webhook server is running. Use POST to interact with the bot."
|
| 48 |
}
|
| 49 |
+
print(f"GET request received: {request_details}")
|
| 50 |
+
return request_details
|
| 51 |
|
| 52 |
@app.post("/")
|
| 53 |
async def webhook(request: Request) -> Dict[str, Any]:
|
|
|
|
| 56 |
"""
|
| 57 |
try:
|
| 58 |
if request.headers.get("X-Webhook-Secret") != os.getenv("WEBHOOK_SECRET"):
|
| 59 |
+
error_message = "Secret incorrect"
|
| 60 |
+
print(error_message)
|
| 61 |
+
raise HTTPException(status_code=400, detail=error_message)
|
| 62 |
|
| 63 |
data = await request.json()
|
| 64 |
event = data.get("event", {})
|
|
|
|
| 68 |
and event.get("scope") == "discussion.comment"
|
| 69 |
and BOT_USERNAME in data.get("comment", {}).get("content", "")
|
| 70 |
):
|
| 71 |
+
print(f"Processing comment: {data['comment']['content']}")
|
| 72 |
+
|
| 73 |
# Préparation du prompt pour l'API NVIDIA
|
| 74 |
messages = [
|
| 75 |
{
|
|
|
|
| 88 |
max_tokens=100,
|
| 89 |
stream=True
|
| 90 |
)
|
| 91 |
+
# Collecter les morceaux de texte généré
|
| 92 |
continuation_text = ""
|
| 93 |
for chunk in completion:
|
| 94 |
if chunk.choices[0].delta.content is not None:
|
| 95 |
continuation_text += chunk.choices[0].delta.content
|
| 96 |
continuation_text = continuation_text.strip()
|
| 97 |
+
print(f"NVIDIA API response: {continuation_text}")
|
| 98 |
+
|
| 99 |
if not continuation_text:
|
| 100 |
raise ValueError("No text generated by NVIDIA API")
|
| 101 |
except Exception as e:
|
| 102 |
+
error_message = f"Inference failed: {str(e)}"
|
| 103 |
+
print(error_message)
|
| 104 |
+
raise HTTPException(status_code=500, detail=error_message)
|
| 105 |
|
| 106 |
+
# Publication du commentaire
|
| 107 |
comment_url = data["discussion"]["url"]["api"] + "/comment"
|
| 108 |
+
print(f"Posting to comment URL: {comment_url}")
|
| 109 |
+
comment_response = requests.post(
|
| 110 |
+
comment_url,
|
| 111 |
+
headers={
|
| 112 |
+
"Authorization": f"Bearer {HF_TOKEN}",
|
| 113 |
+
"Content-Type": "application/json",
|
| 114 |
+
},
|
| 115 |
+
json={"comment": continuation_text},
|
| 116 |
+
)
|
| 117 |
+
|
| 118 |
+
if comment_response.status_code == 200:
|
| 119 |
+
print("Comment posted successfully")
|
| 120 |
+
return {"success": True}
|
| 121 |
+
else:
|
| 122 |
+
error_message = f"Failed to post comment: {comment_response.text}"
|
| 123 |
+
print(error_message)
|
| 124 |
+
raise HTTPException(status_code=500, detail=error_message)
|
|
|
|
|
|
|
| 125 |
|
| 126 |
+
print("Comment does not meet criteria, no action taken")
|
| 127 |
return {"success": False}
|
| 128 |
|
| 129 |
except HTTPException as he:
|
| 130 |
raise he
|
| 131 |
except Exception as e:
|
| 132 |
+
error_message = f"Unexpected error in POST request: {str(e)}"
|
| 133 |
+
print(error_message)
|
| 134 |
+
raise HTTPException(status_code=500, detail=error_message)
|
| 135 |
|
| 136 |
if __name__ == "__main__":
|
| 137 |
import uvicorn
|