Jordan001237's picture
Add application file
9f5016c
Raw History Blame Contribute Delete
12.6 kB
"""
πŸ“š 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()