tyagonzales66 commited on
Commit
fefcf20
·
verified ·
1 Parent(s): 84e8f63

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +27 -12
app.py CHANGED
@@ -1,17 +1,37 @@
1
  from fastapi import FastAPI, Request, HTTPException
2
  import os
 
3
  from typing import Dict, Any
4
  from transformers import pipeline
 
5
 
6
  app = FastAPI()
7
 
8
  # Initialisation du pipeline pour l'API d'inférence Hugging Face
9
  BOT_USERNAME = "@DiscussionBot"
10
  MODEL = "gpt2"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
  try:
12
- pipe = pipeline("text-generation", model=MODEL, token=os.getenv("HF_TOKEN"))
13
  except Exception as e:
14
- print(f"Failed to initialize pipeline: {str(e)}")
15
  raise
16
 
17
  @app.get("/")
@@ -50,19 +70,14 @@ async def webhook(request: Request) -> Dict[str, Any]:
50
  ):
51
  print(f"Processing comment: {data['comment']['content']}")
52
 
53
- # Préparation du prompt au format "messages"
54
- messages = [
55
- {
56
- "role": "user",
57
- "content": 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']}"
58
- }
59
- ]
60
 
61
  # Inférence avec le pipeline
62
  try:
63
- output = pipe(messages, max_new_tokens=100, num_return_sequences=1)
64
  print(f"Pipeline response: {output}")
65
- continuation_text = output[0]["generated_text"][-1]["content"].strip()
66
  except Exception as e:
67
  error_message = f"Inference failed: {str(e)}"
68
  print(error_message)
@@ -74,7 +89,7 @@ async def webhook(request: Request) -> Dict[str, Any]:
74
  comment_response = requests.post(
75
  comment_url,
76
  headers={
77
- "Authorization": f"Bearer {os.getenv('HF_TOKEN')}",
78
  "Content-Type": "application/json",
79
  },
80
  json={"comment": continuation_text},
 
1
  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
  # Initialisation du pipeline pour l'API d'inférence Hugging Face
11
  BOT_USERNAME = "@DiscussionBot"
12
  MODEL = "gpt2"
13
+
14
+ # Définir un répertoire de cache accessible
15
+ CACHE_DIR = os.getenv("HF_HOME", "/app/cache")
16
+ os.makedirs(CACHE_DIR, exist_ok=True) # Créer le répertoire s'il n'existe pas
17
+
18
+ # Vérification du jeton et connexion à Hugging Face
19
+ try:
20
+ HF_TOKEN = os.getenv("HF_TOKEN")
21
+ if not HF_TOKEN:
22
+ print("Warning: HF_TOKEN is not set. Using public model gpt2 which may not require a token.")
23
+ else:
24
+ login(token=HF_TOKEN) # Authentifie avec le jeton
25
+ print("Successfully authenticated with Hugging Face")
26
+ except Exception as e:
27
+ print(f"Failed to authenticate with Hugging Face: {str(e)}")
28
+ # Continue si le modèle ne nécessite pas de jeton
29
+
30
+ # Initialisation du pipeline
31
  try:
32
+ pipe = pipeline("text-generation", model=MODEL, token=HF_TOKEN if HF_TOKEN else None, cache_dir=CACHE_DIR)
33
  except Exception as e:
34
+ print(f"Failed to initialize pipeline for model {MODEL}: {str(e)}")
35
  raise
36
 
37
  @app.get("/")
 
70
  ):
71
  print(f"Processing comment: {data['comment']['content']}")
72
 
73
+ # Préparation du prompt comme une chaîne de texte
74
+ 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']}"
 
 
 
 
 
75
 
76
  # Inférence avec le pipeline
77
  try:
78
+ output = pipe(input_text, max_new_tokens=100, num_return_sequences=1)
79
  print(f"Pipeline response: {output}")
80
+ continuation_text = output[0]["generated_text"].replace(input_text, "").strip()
81
  except Exception as e:
82
  error_message = f"Inference failed: {str(e)}"
83
  print(error_message)
 
89
  comment_response = requests.post(
90
  comment_url,
91
  headers={
92
+ "Authorization": f"Bearer {HF_TOKEN}",
93
  "Content-Type": "application/json",
94
  },
95
  json={"comment": continuation_text},