Spaces:
Runtime error
Runtime error
File size: 12,567 Bytes
9f5016c | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 | """
π LΓ©o β BibliothΓ©caire IA (Hugging Face Spaces)
==================================================
Stack :
- LLM : meta-llama/Llama-3.1-8B-Instruct via HF Inference API
- Streaming : InferenceClient stream
- Tool : search_book() β Open Library API (gratuit, sans clΓ©)
- Couvertures: Open Library Covers API
- Audio OUT : gTTS β gr.Audio autoplay
"""
# ββ Imports βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
import os
import json
import re
import tempfile
import requests
from io import BytesIO
import gradio as gr
from PIL import Image
from gtts import gTTS
from huggingface_hub import InferenceClient
# ββ Initialisation ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
HF_TOKEN = os.getenv("HF_TOKEN") # dΓ©fini dans HF Spaces β Settings β Secrets
MODEL = "meta-llama/Llama-3.1-8B-Instruct"
client = InferenceClient(model=MODEL, token=HF_TOKEN)
# ββ System prompt βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
SYSTEM_PROMPT = """Tu es LΓ©o, un bibliothΓ©caire passionnΓ© et Γ©rudit avec 20 ans d'expΓ©rience.
Tu aides les utilisateurs Γ :
- Trouver des livres selon leurs goΓ»ts, humeurs ou besoins
- DΓ©couvrir des auteurs et des genres littΓ©raires
- Obtenir des rΓ©sumΓ©s, analyses et recommandations de livres
- Chercher des informations prΓ©cises sur un titre ou un auteur
Ton style : chaleureux, enthousiaste pour la littΓ©rature, pΓ©dagogue.
Tu rΓ©ponds toujours en franΓ§ais sauf si l'utilisateur parle une autre langue.
Quand l'utilisateur mentionne un titre ou demande un livre prΓ©cis, tu DOIS appeler
l'outil search_book en rΓ©pondant UNIQUEMENT avec ce JSON (rien d'autre avant) :
{"tool": "search_book", "args": {"title": "<titre>", "author": "<auteur ou vide>"}}
Sinon, rΓ©ponds normalement en texte.
"""
# ββ Open Library Tool βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def search_book(title: str, author: str = "") -> dict:
"""Cherche un livre via Open Library API."""
print(f"π Recherche : '{title}' β '{author}'")
query = f"{title} {author}".strip().replace(" ", "+")
url = (
f"https://openlibrary.org/search.json"
f"?q={query}&limit=1&fields=title,author_name,first_publish_year,cover_i,subject"
)
try:
resp = requests.get(url, timeout=10)
data = resp.json()
if not data.get("docs"):
return {"found": False, "message": f"Aucun rΓ©sultat pour '{title}'"}
doc = data["docs"][0]
cover_id = doc.get("cover_i")
return {
"found": True,
"title": doc.get("title", title),
"author": ", ".join(doc.get("author_name", ["Inconnu"])),
"year": doc.get("first_publish_year", "?"),
"cover_url": f"https://covers.openlibrary.org/b/id/{cover_id}-L.jpg" if cover_id else None,
"subjects": doc.get("subject", [])[:5],
}
except Exception as e:
return {"found": False, "message": str(e)}
def fetch_cover(cover_url: str) -> Image.Image | None:
if not cover_url:
return None
try:
resp = requests.get(cover_url, timeout=10)
if resp.status_code == 200:
return Image.open(BytesIO(resp.content))
except Exception as e:
print(f"Cover error: {e}")
return None
# ββ TTS βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def talker(message: str) -> str:
clean = re.sub(r"[*_`#>\[\]()\{\}]", "", message)
clean = re.sub(r"https?://\S+", "", clean).strip()[:500]
tts = gTTS(text=clean, lang="fr")
tmp = tempfile.NamedTemporaryFile(suffix=".mp3", delete=False)
tts.save(tmp.name)
return tmp.name
# ββ Normalisation Gradio ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def extract_text(raw) -> str:
if isinstance(raw, list):
return " ".join(p["text"] for p in raw if isinstance(p, dict) and "text" in p)
return raw or ""
# ββ DΓ©tection d'un tool call JSON dans la rΓ©ponse du LLM βββββββββββββββββββββ
TOOL_RE = re.compile(r'\{"tool"\s*:\s*"search_book".*?\}', re.DOTALL)
def parse_tool_call(text: str) -> dict | None:
m = TOOL_RE.search(text)
if m:
try:
return json.loads(m.group())
except json.JSONDecodeError:
pass
return None
# ββ Chat principal (streaming) ββββββββββββββββββββββββββββββββββββββββββββββββ
def chat(history):
"""
GΓ©nΓ©rateur β yields (history, cover_image, audio_path).
Utilise HF InferenceClient avec stream=True.
"""
# Construction des messages
messages = [{"role": "system", "content": SYSTEM_PROMPT}]
for msg in history:
role = "assistant" if msg["role"] == "assistant" else "user"
messages.append({"role": role, "content": extract_text(msg["content"])})
cover_img = None
reply = ""
tool_fired = False
# ββ Premier passage streaming βββββββββββββββββββββββββββββββββββββββββββββ
stream = client.chat_completion(messages=messages, max_tokens=1024, stream=True)
for chunk in stream:
delta = chunk.choices[0].delta.content or ""
reply += delta
# Dès qu'on détecte un tool call JSON complet, on coupe le stream
if not tool_fired and parse_tool_call(reply):
tool_fired = True
break
# Sinon on streame token par token
if not tool_fired:
yield history + [{"role": "assistant", "content": reply}], None, None
# ββ Gestion du tool call ββββββββββββββββββββββββββββββββββββββββββββββββββ
if tool_fired:
tc = parse_tool_call(reply)
args = tc.get("args", {})
book_info = search_book(**args)
if book_info.get("found"):
cover_img = fetch_cover(book_info.get("cover_url"))
# Injecter le rΓ©sultat dans les messages et relancer
messages.append({"role": "assistant", "content": reply})
messages.append({
"role": "user",
"content": (
f"[RΓ©sultat de la recherche]\n{json.dumps(book_info, ensure_ascii=False)}\n\n"
"Maintenant prΓ©sente ce livre Γ l'utilisateur de faΓ§on enthousiaste "
"en te basant sur ces informations."
),
})
reply = ""
stream = client.chat_completion(messages=messages, max_tokens=1024, stream=True)
for chunk in stream:
delta = chunk.choices[0].delta.content or ""
reply += delta
yield history + [{"role": "assistant", "content": reply}], cover_img, None
# ββ Audio une fois la rΓ©ponse complΓ¨te ββββββββββββββββββββββββββββββββββββ
audio_path = None
try:
audio_path = talker(reply)
except Exception as e:
print(f"TTS error: {e}")
final_history = history + [{"role": "assistant", "content": reply}]
yield final_history, cover_img, audio_path
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Interface Gradio
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
CSS = """
@import url('https://fonts.googleapis.com/css2?family=Playfair+Display:ital,wght@0,400;0,700;1,400&family=Crimson+Text:ital@0;1&display=swap');
:root {
--parchment: #f5efe0;
--leather: #8b4513;
--gold: #c9a84c;
--ink: #2c1810;
--sage: #6b7c5e;
--cream: #fdf6e3;
}
body, .gradio-container {
background-color: var(--parchment) !important;
font-family: 'Crimson Text', Georgia, serif !important;
color: var(--ink) !important;
}
#title-block {
text-align: center;
padding: 2rem 1rem 1rem;
border-bottom: 3px double var(--gold);
margin-bottom: 1.5rem;
}
#title-block h1 {
font-family: 'Playfair Display', serif !important;
font-size: 2.4rem !important;
color: var(--leather) !important;
letter-spacing: 0.05em;
margin: 0;
}
#title-block p {
font-style: italic;
color: var(--sage) !important;
font-size: 1.1rem;
margin-top: 0.3rem;
}
#chatbot { background: var(--cream) !important; border: 1px solid var(--gold) !important; }
#cover-box { border: 3px solid var(--gold) !important; background: var(--cream) !important; }
footer { display: none !important; }
"""
WELCOME = [{"role": "assistant", "content": (
"Bonjour et bienvenue ! π Je suis **LΓ©o**, votre bibliothΓ©caire IA.\n\n"
"Je peux vous aider Γ :\n"
"- **Trouver un livre** selon vos goΓ»ts ou votre humeur\n"
"- **DΓ©couvrir des auteurs** et des genres littΓ©raires\n"
"- **Obtenir un rΓ©sumΓ©** ou une analyse d'un ouvrage\n"
"- **Recommander des lectures** personnalisΓ©es\n\n"
"Que puis-je faire pour vous aujourd'hui ? π"
)}]
with gr.Blocks(css=CSS, title="π LΓ©o β BibliothΓ©caire IA") as ui:
gr.HTML("""
<div id="title-block">
<h1>π LΓ©o β BibliothΓ©caire IA</h1>
<p>Votre guide littΓ©raire personnel Β· Llama 3.1 8B Β· Open Library</p>
</div>
""")
with gr.Row():
with gr.Column(scale=3):
chatbot = gr.Chatbot(
height=480,
label="Conversation avec LΓ©o",
elem_id="chatbot",
)
with gr.Row():
entry = gr.Textbox(
placeholder="Demandez un livre, un auteur, une recommandation...",
label="", scale=5, container=False,
)
send_btn = gr.Button("Envoyer β", scale=1, variant="primary")
clear_btn = gr.Button("ποΈ Nouvelle conversation", variant="secondary")
with gr.Column(scale=2):
cover_output = gr.Image(
height=420, label="π Couverture", elem_id="cover-box"
)
audio_output = gr.Audio(
label="π RΓ©ponse vocale", autoplay=True, visible=True
)
gr.HTML("""
<div style="text-align:center;margin-top:1rem;font-style:italic;
color:#6b7c5e;font-size:0.95rem;">
Β« Un livre est un jardin qu'on porte dans sa poche. Β»
</div>
""")
# ββ Interactions ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def do_entry(message, history):
if not message.strip():
return "", history
return "", history + [{"role": "user", "content": message}]
entry.submit(do_entry, [entry, chatbot], [entry, chatbot]).then(
chat, [chatbot], [chatbot, cover_output, audio_output]
)
send_btn.click(do_entry, [entry, chatbot], [entry, chatbot]).then(
chat, [chatbot], [chatbot, cover_output, audio_output]
)
clear_btn.click(
lambda: (WELCOME, None, None),
outputs=[chatbot, cover_output, audio_output],
queue=False,
)
ui.load(lambda: WELCOME, outputs=[chatbot])
ui.launch() |