Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,39 +1,148 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
def answer(question: str) -> str:
|
| 2 |
question = (question or "").strip()
|
| 3 |
if not question:
|
| 4 |
return "Pose-moi une question sur l'art 🙂"
|
| 5 |
|
|
|
|
|
|
|
| 6 |
try:
|
| 7 |
-
|
| 8 |
-
response = client.chat_completion(
|
| 9 |
-
messages=[
|
| 10 |
-
{"role": "system", "content": SYSTEM_PROMPT.strip()},
|
| 11 |
-
{"role": "user", "content": question},
|
| 12 |
-
],
|
| 13 |
-
max_tokens=400,
|
| 14 |
-
temperature=0.7,
|
| 15 |
-
top_p=0.95,
|
| 16 |
-
)
|
| 17 |
|
| 18 |
-
#
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
content = getattr(message, "content", None)
|
| 22 |
-
if content is None and isinstance(message, dict):
|
| 23 |
-
content = message.get("content", "")
|
| 24 |
|
| 25 |
-
|
| 26 |
-
if
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
return "Je n'ai pas réussi à générer une réponse cette fois-ci."
|
| 28 |
|
| 29 |
-
return
|
| 30 |
|
| 31 |
except Exception:
|
| 32 |
-
import traceback
|
| 33 |
tb = traceback.format_exc()
|
| 34 |
return (
|
| 35 |
-
"### Erreur
|
| 36 |
"```text\n"
|
| 37 |
f"{tb}\n"
|
| 38 |
"```"
|
| 39 |
-
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import textwrap
|
| 3 |
+
import traceback
|
| 4 |
+
import requests
|
| 5 |
+
import gradio as gr
|
| 6 |
+
|
| 7 |
+
# 1. Récupérer ton token Hugging Face (secret HF_TOKEN dans Settings)
|
| 8 |
+
HF_TOKEN = os.environ.get("HF_TOKEN")
|
| 9 |
+
|
| 10 |
+
if not HF_TOKEN:
|
| 11 |
+
raise RuntimeError(
|
| 12 |
+
"La variable d'environnement HF_TOKEN n'est pas définie. "
|
| 13 |
+
"Va dans Settings → Variables and secrets → Secrets et ajoute HF_TOKEN "
|
| 14 |
+
"avec ton token Hugging Face."
|
| 15 |
+
)
|
| 16 |
+
|
| 17 |
+
# 2. Modèle de chat open-source hébergé par Hugging Face
|
| 18 |
+
MODEL_ID = "HuggingFaceH4/zephyr-7b-beta"
|
| 19 |
+
API_URL = f"https://api-inference.huggingface.co/models/{MODEL_ID}"
|
| 20 |
+
|
| 21 |
+
HEADERS = {"Authorization": f"Bearer {HF_TOKEN}"}
|
| 22 |
+
|
| 23 |
+
SYSTEM_PROMPT = """
|
| 24 |
+
Tu es ArtGPT, un assistant spécialisé à 100% dans l'art :
|
| 25 |
+
illustration, dessin, peinture, graphisme, composition, lumière,
|
| 26 |
+
histoire de l'art, mouvements artistiques, direction artistique,
|
| 27 |
+
portfolio, conseils logiciels et création visuelle.
|
| 28 |
+
|
| 29 |
+
Règles :
|
| 30 |
+
- Réponds uniquement en français.
|
| 31 |
+
- Si la question n’est pas liée à l’art ou à la création visuelle,
|
| 32 |
+
tu rediriges gentiment vers ces thèmes.
|
| 33 |
+
- Donne des réponses claires, structurées, pédagogiques.
|
| 34 |
+
- Propose volontiers des exercices pratiques.
|
| 35 |
+
"""
|
| 36 |
+
|
| 37 |
+
def build_prompt(question: str) -> str:
|
| 38 |
+
"""Construire un prompt texte pour le modèle."""
|
| 39 |
+
return textwrap.dedent(
|
| 40 |
+
f"""
|
| 41 |
+
{SYSTEM_PROMPT.strip()}
|
| 42 |
+
|
| 43 |
+
Utilisateur : {question.strip()}
|
| 44 |
+
Assistant :
|
| 45 |
+
"""
|
| 46 |
+
).strip()
|
| 47 |
+
|
| 48 |
+
def query_hf(prompt: str) -> str:
|
| 49 |
+
"""Appel brut à l'API de Hugging Face."""
|
| 50 |
+
payload = {
|
| 51 |
+
"inputs": prompt,
|
| 52 |
+
"parameters": {
|
| 53 |
+
"max_new_tokens": 400,
|
| 54 |
+
"temperature": 0.7,
|
| 55 |
+
"top_p": 0.95,
|
| 56 |
+
"repetition_penalty": 1.05,
|
| 57 |
+
"do_sample": True,
|
| 58 |
+
}
|
| 59 |
+
}
|
| 60 |
+
|
| 61 |
+
response = requests.post(API_URL, headers=HEADERS, json=payload, timeout=90)
|
| 62 |
+
|
| 63 |
+
# Si le HTTP code n'est pas 200, on lève pour afficher ensuite l'erreur proprement
|
| 64 |
+
try:
|
| 65 |
+
response.raise_for_status()
|
| 66 |
+
except Exception:
|
| 67 |
+
return (
|
| 68 |
+
"### Erreur HTTP Hugging Face\n\n"
|
| 69 |
+
"```text\n"
|
| 70 |
+
f"Status code: {response.status_code}\n"
|
| 71 |
+
f"Body: {response.text}\n"
|
| 72 |
+
"```"
|
| 73 |
+
)
|
| 74 |
+
|
| 75 |
+
data = response.json()
|
| 76 |
+
|
| 77 |
+
# Format typique de l'API Inference: liste d'objets avec generated_text
|
| 78 |
+
if isinstance(data, list) and data and isinstance(data[0], dict):
|
| 79 |
+
generated = data[0].get("generated_text", "")
|
| 80 |
+
# Certains modèles renvoient un dict avec 'error'
|
| 81 |
+
elif isinstance(data, dict) and "error" in data:
|
| 82 |
+
return (
|
| 83 |
+
"### Erreur du modèle Hugging Face\n\n"
|
| 84 |
+
"```text\n"
|
| 85 |
+
f"{data['error']}\n"
|
| 86 |
+
"```"
|
| 87 |
+
)
|
| 88 |
+
else:
|
| 89 |
+
# Format inattendu: on affiche tout pour debug
|
| 90 |
+
return (
|
| 91 |
+
"### Réponse inattendue de l'API Hugging Face\n\n"
|
| 92 |
+
"```text\n"
|
| 93 |
+
f"{data}\n"
|
| 94 |
+
"```"
|
| 95 |
+
)
|
| 96 |
+
|
| 97 |
+
return generated
|
| 98 |
+
|
| 99 |
def answer(question: str) -> str:
|
| 100 |
question = (question or "").strip()
|
| 101 |
if not question:
|
| 102 |
return "Pose-moi une question sur l'art 🙂"
|
| 103 |
|
| 104 |
+
prompt = build_prompt(question)
|
| 105 |
+
|
| 106 |
try:
|
| 107 |
+
generated = query_hf(prompt)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 108 |
|
| 109 |
+
# Si l'API a déjà renvoyé un bloc d'erreur formaté markdown, on le retourne tel quel
|
| 110 |
+
if generated.startswith("### Erreur") or generated.startswith("### Réponse inattendue"):
|
| 111 |
+
return generated
|
|
|
|
|
|
|
|
|
|
| 112 |
|
| 113 |
+
# Nettoyage: certains modèles renvoient prompt + completion
|
| 114 |
+
if generated.startswith(prompt):
|
| 115 |
+
generated = generated[len(prompt):]
|
| 116 |
+
|
| 117 |
+
generated = generated.strip()
|
| 118 |
+
if not generated:
|
| 119 |
return "Je n'ai pas réussi à générer une réponse cette fois-ci."
|
| 120 |
|
| 121 |
+
return generated
|
| 122 |
|
| 123 |
except Exception:
|
|
|
|
| 124 |
tb = traceback.format_exc()
|
| 125 |
return (
|
| 126 |
+
"### Erreur Python côté Space\n\n"
|
| 127 |
"```text\n"
|
| 128 |
f"{tb}\n"
|
| 129 |
"```"
|
| 130 |
+
)
|
| 131 |
+
|
| 132 |
+
demo = gr.Interface(
|
| 133 |
+
fn=answer,
|
| 134 |
+
inputs=gr.Textbox(
|
| 135 |
+
label="Pose ta question sur l'art",
|
| 136 |
+
placeholder="Ex : Donne-moi un exercice pour progresser en composition d’affiche.",
|
| 137 |
+
),
|
| 138 |
+
outputs=gr.Markdown(label="Réponse d’ArtGPT"),
|
| 139 |
+
title="🎨 ArtGPT — Assistant IA pour artistes",
|
| 140 |
+
description=(
|
| 141 |
+
"Pose une question sur l'illustration, le dessin, la couleur, la composition, "
|
| 142 |
+
"l'histoire de l'art, le graphisme ou la direction artistique. "
|
| 143 |
+
"ArtGPT te répond de manière claire et pédagogique."
|
| 144 |
+
),
|
| 145 |
+
)
|
| 146 |
+
|
| 147 |
+
if __name__ == "__main__":
|
| 148 |
+
demo.launch()
|