Jordan001237 commited on
Commit
9f5016c
Β·
1 Parent(s): ed5aaff

Add application file

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