Spaces:
Sleeping
Sleeping
Commit ·
48a1c33
1
Parent(s): 648855b
MVP Finaliser principale fonction implementer: recherche web, synthese vocal, generation de flyer a partir de la brochure
Browse files- .env.example +0 -0
- README.md +0 -14
- app.py +0 -85
- app/api/brochure.py +104 -0
- app/api/flyer.py +34 -0
- app/api/search.py +17 -0
- app/api/tts.py +27 -0
- app/core/config.py +17 -0
- app/schemas/schemas.py +72 -0
- app/services/image_service.py +93 -0
- app/services/llm_service.py +158 -0
- app/services/scraper.py +93 -0
- app/services/tts_service.py +50 -0
- app/services/web_search.py +37 -0
- llm_service.py +0 -135
- main.py +41 -0
- models.py +0 -18
- pyproject.toml +21 -11
- requirements.txt +165 -0
- scraper.py +0 -62
- uv.lock +0 -0
.env.example
ADDED
|
File without changes
|
README.md
DELETED
|
@@ -1,14 +0,0 @@
|
|
| 1 |
-
---
|
| 2 |
-
title: Brum001
|
| 3 |
-
emoji: 📑
|
| 4 |
-
colorFrom: blue
|
| 5 |
-
colorTo: indigo
|
| 6 |
-
sdk: gradio
|
| 7 |
-
sdk_version: 4.26.0
|
| 8 |
-
app_file: app.py
|
| 9 |
-
pinned: false
|
| 10 |
-
---
|
| 11 |
-
|
| 12 |
-
# Brochure AI Generator
|
| 13 |
-
Générez une brochure professionnelle à partir d'une URL d'entreprise.
|
| 14 |
-
Propulsé par **Groq (Llama 3)** et **BeautifulSoup**.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
app.py
DELETED
|
@@ -1,85 +0,0 @@
|
|
| 1 |
-
import gradio as gr
|
| 2 |
-
from scraper import Website, scrape_multiple
|
| 3 |
-
from llm_service import extract_relevant_links, generate_brochure_stream
|
| 4 |
-
|
| 5 |
-
def create_brochure(company_name: str, url: str):
|
| 6 |
-
"""
|
| 7 |
-
Pipeline complet :
|
| 8 |
-
1. Scrape la page principale
|
| 9 |
-
2. Extrait les liens pertinents via LLM
|
| 10 |
-
3. Scrape les sous-pages
|
| 11 |
-
4. Génère la brochure en streaming
|
| 12 |
-
"""
|
| 13 |
-
if not company_name.strip() or not url.strip():
|
| 14 |
-
yield "⚠️ Veuillez renseigner le nom de l'entreprise et l'URL."
|
| 15 |
-
return
|
| 16 |
-
|
| 17 |
-
if not url.startswith("http"):
|
| 18 |
-
url = "https://" + url
|
| 19 |
-
|
| 20 |
-
# Étape 1 : Scrape la page principale
|
| 21 |
-
yield "🔍 Analyse de la page principale..."
|
| 22 |
-
try:
|
| 23 |
-
main_site = Website(url)
|
| 24 |
-
except ValueError as e:
|
| 25 |
-
yield f"❌ Erreur de scraping : {e}"
|
| 26 |
-
return
|
| 27 |
-
|
| 28 |
-
# Étape 2 : LLM extrait les liens pertinents
|
| 29 |
-
yield "🤖 Identification des sections pertinentes..."
|
| 30 |
-
links_response = extract_relevant_links(url, main_site.links)
|
| 31 |
-
|
| 32 |
-
relevant_urls = [item.url for item in links_response.links[:4]] # Max 4 sous-pages
|
| 33 |
-
all_urls = [url] + relevant_urls
|
| 34 |
-
|
| 35 |
-
yield f"📄 {len(relevant_urls)} sous-pages trouvées. Scraping en cours..."
|
| 36 |
-
|
| 37 |
-
# Étape 3 : Scrape toutes les pages
|
| 38 |
-
aggregated_content = scrape_multiple(all_urls)
|
| 39 |
-
|
| 40 |
-
# Étape 4 : Génère la brochure en streaming
|
| 41 |
-
yield "✍️ Génération de la brochure...\n\n"
|
| 42 |
-
for partial_result in generate_brochure_stream(company_name, aggregated_content):
|
| 43 |
-
yield partial_result
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
# Interface Gradio
|
| 47 |
-
with gr.Blocks(title="AI Brochure Generator", theme=gr.themes.Soft()) as demo:
|
| 48 |
-
gr.Markdown(
|
| 49 |
-
"""
|
| 50 |
-
# 🏢 AI Brochure Generator
|
| 51 |
-
Génère automatiquement une brochure professionnelle à partir du site web d'une entreprise.
|
| 52 |
-
*Propulsé par Llama 3.3-70b via Groq*
|
| 53 |
-
"""
|
| 54 |
-
)
|
| 55 |
-
|
| 56 |
-
with gr.Row():
|
| 57 |
-
company_input = gr.Textbox(
|
| 58 |
-
label="Nom de l'entreprise",
|
| 59 |
-
placeholder="Ex: Anthropic",
|
| 60 |
-
)
|
| 61 |
-
url_input = gr.Textbox(
|
| 62 |
-
label="URL du site web",
|
| 63 |
-
placeholder="Ex: https://anthropic.com",
|
| 64 |
-
)
|
| 65 |
-
|
| 66 |
-
generate_btn = gr.Button("🚀 Générer la brochure", variant="primary")
|
| 67 |
-
|
| 68 |
-
output = gr.Markdown(label="Brochure générée")
|
| 69 |
-
|
| 70 |
-
gr.Examples(
|
| 71 |
-
examples=[
|
| 72 |
-
["Anthropic", "https://anthropic.com"],
|
| 73 |
-
["Hugging Face", "https://huggingface.co"],
|
| 74 |
-
],
|
| 75 |
-
inputs=[company_input, url_input],
|
| 76 |
-
)
|
| 77 |
-
|
| 78 |
-
generate_btn.click(
|
| 79 |
-
fn=create_brochure,
|
| 80 |
-
inputs=[company_input, url_input],
|
| 81 |
-
outputs=output,
|
| 82 |
-
)
|
| 83 |
-
|
| 84 |
-
if __name__ == "__main__":
|
| 85 |
-
demo.launch()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
app/api/brochure.py
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
from fastapi import APIRouter
|
| 3 |
+
from fastapi.responses import StreamingResponse
|
| 4 |
+
from app.schemas.schemas import BrochureRequest
|
| 5 |
+
from app.services.web_search import search_company
|
| 6 |
+
from app.services.scraper import scrape_url, scrape_multiple
|
| 7 |
+
from app.services.llm_service import extract_relevant_links, generate_brochure_stream
|
| 8 |
+
|
| 9 |
+
router = APIRouter(prefix="/api/brochure", tags=["brochure"])
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def _make_event(type_: str, **kwargs) -> str:
|
| 13 |
+
"""
|
| 14 |
+
Formate un événement SSE.
|
| 15 |
+
Format standard : "data: {json}\\n\\n"
|
| 16 |
+
Le double \\n est obligatoire — c'est le délimiteur du protocole SSE.
|
| 17 |
+
"""
|
| 18 |
+
payload = {"type": type_, **kwargs}
|
| 19 |
+
return f"data: {json.dumps(payload, ensure_ascii=False)}\n\n"
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
async def _brochure_generator(request: BrochureRequest):
|
| 23 |
+
"""
|
| 24 |
+
Générateur async qui orchestre tout le pipeline et yield des events SSE.
|
| 25 |
+
|
| 26 |
+
Pipeline :
|
| 27 |
+
1. Résoudre l'URL (recherche si absente)
|
| 28 |
+
2. Scraper la page principale
|
| 29 |
+
3. LLM extrait les liens pertinents
|
| 30 |
+
4. Scraper les sous-pages
|
| 31 |
+
5. Streamer la brochure token par token
|
| 32 |
+
"""
|
| 33 |
+
|
| 34 |
+
# ── Étape 1 : Résoudre l'URL ───────────────────────────────────────────────
|
| 35 |
+
url = request.url
|
| 36 |
+
|
| 37 |
+
if not url:
|
| 38 |
+
yield _make_event("status", message=f"🔍 Recherche de {request.company_name}...")
|
| 39 |
+
try:
|
| 40 |
+
results = search_company(request.company_name, max_results=3)
|
| 41 |
+
if not results:
|
| 42 |
+
yield _make_event("error", message="Aucun résultat trouvé. Vérifiez le nom.")
|
| 43 |
+
return
|
| 44 |
+
url = results[0].url
|
| 45 |
+
yield _make_event("status", message=f"✓ Site trouvé : {url}")
|
| 46 |
+
except Exception as e:
|
| 47 |
+
yield _make_event("error", message=f"Erreur de recherche : {e}")
|
| 48 |
+
return
|
| 49 |
+
|
| 50 |
+
# ── Étape 2 : Scraper la page principale ──────────────────────────────────
|
| 51 |
+
yield _make_event("status", message="📄 Analyse de la page principale...")
|
| 52 |
+
try:
|
| 53 |
+
main_page = scrape_url(url)
|
| 54 |
+
except ValueError as e:
|
| 55 |
+
yield _make_event("error", message=str(e))
|
| 56 |
+
return
|
| 57 |
+
|
| 58 |
+
# ── Étape 3 : Extraire les liens pertinents ────────────────────────────────
|
| 59 |
+
yield _make_event("status", message="🤖 Identification des sections clés...")
|
| 60 |
+
links_response = extract_relevant_links(url, main_page.links)
|
| 61 |
+
relevant_urls = [item.url for item in links_response.links[:4]]
|
| 62 |
+
|
| 63 |
+
if relevant_urls:
|
| 64 |
+
yield _make_event("status", message=f"📑 {len(relevant_urls)} sections identifiées...")
|
| 65 |
+
|
| 66 |
+
# ── Étape 4 : Scraper toutes les pages ────────────────────────────────────
|
| 67 |
+
all_urls = [url] + relevant_urls
|
| 68 |
+
yield _make_event("status", message=f"🔄 Extraction du contenu ({len(all_urls)} pages)...")
|
| 69 |
+
aggregated = scrape_multiple(all_urls, max_chars_per_page=3000)
|
| 70 |
+
|
| 71 |
+
# ── Étape 5 : Générer la brochure en streaming ────────────────────────────
|
| 72 |
+
yield _make_event("status", message="✍️ Génération de la brochure...")
|
| 73 |
+
yield _make_event("start") # Signal au frontend : afficher la zone de résultat
|
| 74 |
+
|
| 75 |
+
full_brochure = ""
|
| 76 |
+
for token in generate_brochure_stream(request.company_name, aggregated):
|
| 77 |
+
full_brochure += token
|
| 78 |
+
yield _make_event("token", content=token)
|
| 79 |
+
|
| 80 |
+
# ── Étape 6 : Signal de fin ────────────────────────────────────────────────
|
| 81 |
+
yield _make_event("done", brochure=full_brochure, url=url)
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
@router.post("/stream")
|
| 85 |
+
async def stream_brochure(request: BrochureRequest):
|
| 86 |
+
"""
|
| 87 |
+
Endpoint SSE — génère la brochure en streaming.
|
| 88 |
+
|
| 89 |
+
Le frontend consomme ce flux via fetch() + ReadableStream (pas EventSource
|
| 90 |
+
car EventSource ne supporte pas POST nativement).
|
| 91 |
+
|
| 92 |
+
Headers importants :
|
| 93 |
+
- Cache-Control: no-cache → désactive le cache pour le streaming
|
| 94 |
+
- X-Accel-Buffering: no → désactive le buffering nginx (crucial en prod)
|
| 95 |
+
"""
|
| 96 |
+
return StreamingResponse(
|
| 97 |
+
_brochure_generator(request),
|
| 98 |
+
media_type="text/event-stream",
|
| 99 |
+
headers={
|
| 100 |
+
"Cache-Control": "no-cache",
|
| 101 |
+
"X-Accel-Buffering": "no",
|
| 102 |
+
"Access-Control-Allow-Origin": "*",
|
| 103 |
+
},
|
| 104 |
+
)
|
app/api/flyer.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import APIRouter, HTTPException
|
| 2 |
+
from app.schemas.schemas import FlyerRequest, FlyerResponse
|
| 3 |
+
from app.services.llm_service import build_flyer_prompt
|
| 4 |
+
from app.services.image_service import generate_flyer_image
|
| 5 |
+
|
| 6 |
+
router = APIRouter(prefix="/api/flyer", tags=["flyer"])
|
| 7 |
+
|
| 8 |
+
@router.post("", response_model=FlyerResponse)
|
| 9 |
+
def generate_flyer(request: FlyerRequest):
|
| 10 |
+
"""
|
| 11 |
+
Pipeline en 2 étapes :
|
| 12 |
+
1. LLM transforme la brochure markdown → prompt visuel pour FLUX.1
|
| 13 |
+
2. FLUX.1-schnell génère l'image (1024×1024)
|
| 14 |
+
|
| 15 |
+
Retourne le PNG en base64 pour affichage direct dans <img> :
|
| 16 |
+
img.src = `data:image/png;base64,${response.image_base64}`
|
| 17 |
+
"""
|
| 18 |
+
try:
|
| 19 |
+
# Étape 1 : Construire le prompt visuel
|
| 20 |
+
visual_prompt = build_flyer_prompt(
|
| 21 |
+
request.company_name,
|
| 22 |
+
request.brochure_text,
|
| 23 |
+
request.style,
|
| 24 |
+
)
|
| 25 |
+
|
| 26 |
+
# Étape 2 : Générer l'image
|
| 27 |
+
image_b64, provider = generate_flyer_image(visual_prompt)
|
| 28 |
+
|
| 29 |
+
return FlyerResponse(
|
| 30 |
+
image_base64=image_b64,
|
| 31 |
+
prompt_used=f"[{provider}] {visual_prompt}",
|
| 32 |
+
)
|
| 33 |
+
except Exception as e:
|
| 34 |
+
raise HTTPException(status_code=500, detail=str(e))
|
app/api/search.py
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import APIRouter, HTTPException, Query
|
| 2 |
+
from app.schemas import SearchResponse
|
| 3 |
+
from app.services.web_search import search_company
|
| 4 |
+
|
| 5 |
+
router = APIRouter(prefix="/api/search", tags=["search"])
|
| 6 |
+
|
| 7 |
+
@router.get("", response_model=SearchResponse)
|
| 8 |
+
def search(q: str = Query(..., min_length=2, description="Nom de l'entreprise à rechercher")):
|
| 9 |
+
"""
|
| 10 |
+
Recherche le site web d'une entreprise via DuckDuckGo.
|
| 11 |
+
Utilisé quand l'utilisateur ne connaît pas l'URL exacte.
|
| 12 |
+
"""
|
| 13 |
+
try:
|
| 14 |
+
results = search_company(q)
|
| 15 |
+
return SearchResponse(results=results)
|
| 16 |
+
except RuntimeError as e:
|
| 17 |
+
raise HTTPException(status_code=503, detail=str(e))
|
app/api/tts.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import base64
|
| 2 |
+
from fastapi import APIRouter, HTTPException
|
| 3 |
+
from app.schemas import TTSRequest, TTSResponse
|
| 4 |
+
from app.services.tts_service import synthesize_speech
|
| 5 |
+
|
| 6 |
+
router = APIRouter(prefix="/api/tts", tags=["tts"])
|
| 7 |
+
|
| 8 |
+
@router.post("", response_model=TTSResponse)
|
| 9 |
+
async def text_to_speech(request: TTSRequest):
|
| 10 |
+
"""
|
| 11 |
+
Synthétise le texte en MP3 via edge-tts.
|
| 12 |
+
|
| 13 |
+
Retourne le MP3 encodé en base64 — le frontend le joue directement
|
| 14 |
+
avec un élément <audio> et une data URL :
|
| 15 |
+
audio.src = `data:audio/mp3;base64,${response.audio_base64}`
|
| 16 |
+
|
| 17 |
+
Note : endpoint async car edge-tts est entièrement async.
|
| 18 |
+
FastAPI gère les endpoints async nativement — pas besoin d'asyncio.run().
|
| 19 |
+
"""
|
| 20 |
+
try:
|
| 21 |
+
audio_bytes, voice = await synthesize_speech(request.text, request.language)
|
| 22 |
+
return TTSResponse(
|
| 23 |
+
audio_base64=base64.b64encode(audio_bytes).decode(),
|
| 24 |
+
voice_used=voice,
|
| 25 |
+
)
|
| 26 |
+
except Exception as e:
|
| 27 |
+
raise HTTPException(status_code=500, detail=f"TTS échoué : {e}")
|
app/core/config.py
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pydantic_settings import BaseSettings, SettingsConfigDict
|
| 2 |
+
|
| 3 |
+
class Settings(BaseSettings):
|
| 4 |
+
"""
|
| 5 |
+
Pydantic-settings charge automatiquement les variables depuis .env
|
| 6 |
+
Avantage vs os.getenv : validation au démarrage, pas au runtime
|
| 7 |
+
"""
|
| 8 |
+
groq_api_key: str
|
| 9 |
+
hf_token: str
|
| 10 |
+
tts_voice_fr: str = "fr-FR-DeniseNeural"
|
| 11 |
+
tts_voice_en: str = "en-US-JennyNeural"
|
| 12 |
+
|
| 13 |
+
# Config : lire depuis .env, insensible à la casse
|
| 14 |
+
model_config = SettingsConfigDict(env_file=".env", case_sensitive=False)
|
| 15 |
+
|
| 16 |
+
# Singleton — importé depuis n'importe quel service
|
| 17 |
+
settings = Settings()
|
app/schemas/schemas.py
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pydantic import BaseModel, HttpUrl, field_validator
|
| 2 |
+
from typing import Optional
|
| 3 |
+
|
| 4 |
+
# ── Recherche web ──────────────────────────────────────────────────────────────
|
| 5 |
+
|
| 6 |
+
class SearchResult(BaseModel):
|
| 7 |
+
title: str
|
| 8 |
+
url: str
|
| 9 |
+
snippet: str
|
| 10 |
+
|
| 11 |
+
class SearchResponse(BaseModel):
|
| 12 |
+
results: list[SearchResult]
|
| 13 |
+
|
| 14 |
+
# ── Extraction de liens ────────────────────────────────────────────────────────
|
| 15 |
+
|
| 16 |
+
class LinkItem(BaseModel):
|
| 17 |
+
"""Un lien pertinent extrait d'une page web par le LLM"""
|
| 18 |
+
type: str # "about page", "careers", "products"...
|
| 19 |
+
url: str
|
| 20 |
+
|
| 21 |
+
class LinksResponse(BaseModel):
|
| 22 |
+
"""Réponse structurée du LLM — garantit un JSON valide même si le modèle hallucine"""
|
| 23 |
+
links: list[LinkItem]
|
| 24 |
+
|
| 25 |
+
# ── Génération de brochure ─────────────────────────────────────────────────────
|
| 26 |
+
|
| 27 |
+
class BrochureRequest(BaseModel):
|
| 28 |
+
company_name: str
|
| 29 |
+
url: Optional[str] = None # Si None → on utilise la recherche web
|
| 30 |
+
|
| 31 |
+
@field_validator("company_name")
|
| 32 |
+
@classmethod
|
| 33 |
+
def name_not_empty(cls, v: str) -> str:
|
| 34 |
+
if not v.strip():
|
| 35 |
+
raise ValueError("Le nom de l'entreprise est requis")
|
| 36 |
+
return v.strip()
|
| 37 |
+
|
| 38 |
+
@field_validator("url")
|
| 39 |
+
@classmethod
|
| 40 |
+
def normalize_url(cls, v: Optional[str]) -> Optional[str]:
|
| 41 |
+
if v and not v.startswith("http"):
|
| 42 |
+
return "https://" + v
|
| 43 |
+
return v
|
| 44 |
+
|
| 45 |
+
# ── Synthèse vocale ────────────────────────────────────────────────────────────
|
| 46 |
+
|
| 47 |
+
class TTSRequest(BaseModel):
|
| 48 |
+
text: str
|
| 49 |
+
language: str = "fr" # "fr" ou "en"
|
| 50 |
+
|
| 51 |
+
class TTSResponse(BaseModel):
|
| 52 |
+
audio_base64: str # MP3 encodé en base64
|
| 53 |
+
voice_used: str
|
| 54 |
+
|
| 55 |
+
# ── Génération de flyer ────────────────────────────────────────────────────────
|
| 56 |
+
|
| 57 |
+
class FlyerRequest(BaseModel):
|
| 58 |
+
brochure_text: str # Le markdown de la brochure complète
|
| 59 |
+
company_name: str
|
| 60 |
+
style: str = "modern" # "modern" | "elegant" | "bold" | "minimal"
|
| 61 |
+
|
| 62 |
+
class FlyerResponse(BaseModel):
|
| 63 |
+
image_base64: str # PNG encodé en base64
|
| 64 |
+
prompt_used: str # Pour debug et portfolio
|
| 65 |
+
|
| 66 |
+
# ── SSE Events (streaming brochure) ───────────────────────────────────────────
|
| 67 |
+
# Ces modèles ne sont pas envoyés comme body mais sérialisés en JSON dans les data SSE
|
| 68 |
+
|
| 69 |
+
class SSEEvent(BaseModel):
|
| 70 |
+
type: str # "status" | "token" | "done" | "error"
|
| 71 |
+
content: Optional[str] = None # token de texte
|
| 72 |
+
message: Optional[str] = None # message de statut
|
app/services/image_service.py
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import base64
|
| 2 |
+
import io
|
| 3 |
+
import httpx
|
| 4 |
+
from app.core.config import settings
|
| 5 |
+
|
| 6 |
+
# FLUX.1-schnell : modèle de génération d'images de Black Forest Labs (2024)
|
| 7 |
+
# C'est le modèle open-source le plus performant actuellement — supérieur à SD XL
|
| 8 |
+
# Disponible gratuitement via HF Inference API (rate limité)
|
| 9 |
+
#
|
| 10 |
+
# ALTERNATIVE 1 : FLUX.1-dev (même famille, plus de détails, plus lent)
|
| 11 |
+
# Trigger : si le client exige une qualité maximale, budget = 0
|
| 12 |
+
#
|
| 13 |
+
# ALTERNATIVE 2 : Pollinations.ai (https://image.pollinations.ai)
|
| 14 |
+
# Avantage : 100% gratuit, pas d'API key, CORS ouvert
|
| 15 |
+
# Inconvénient : moins stable que HF, résolution limitée
|
| 16 |
+
# Trigger : HF rate limit répété ou HF_TOKEN absent
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
HF_API_URL = "https://api-inference.huggingface.co/models/black-forest-labs/FLUX.1-schnell"
|
| 20 |
+
POLLINATIONS_URL = "https://image.pollinations.ai/prompt/{prompt}"
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def generate_flyer_image(prompt: str) -> tuple[str, str]:
|
| 24 |
+
"""
|
| 25 |
+
Génère une image de flyer via FLUX.1-schnell sur HF Inference API.
|
| 26 |
+
|
| 27 |
+
Retourne : (base64_png, provider_used)
|
| 28 |
+
|
| 29 |
+
Fallback automatique vers Pollinations.ai si HF échoue.
|
| 30 |
+
"""
|
| 31 |
+
# Enrichir le prompt pour un résultat flyer/marketing
|
| 32 |
+
full_prompt = (
|
| 33 |
+
f"{prompt}, "
|
| 34 |
+
"professional marketing flyer, high resolution, "
|
| 35 |
+
"clean typography, commercial photography quality, 4k"
|
| 36 |
+
)
|
| 37 |
+
|
| 38 |
+
# Tentative 1 : HF FLUX.1-schnell
|
| 39 |
+
try:
|
| 40 |
+
return _generate_hf(full_prompt), "HF FLUX.1-schnell"
|
| 41 |
+
except Exception as e:
|
| 42 |
+
print(f"[image_service] HF échoué ({e}), fallback vers Pollinations.ai")
|
| 43 |
+
|
| 44 |
+
# Tentative 2 : Pollinations.ai (gratuit, no-auth)
|
| 45 |
+
try:
|
| 46 |
+
return _generate_pollinations(full_prompt), "Pollinations.ai"
|
| 47 |
+
except Exception as e:
|
| 48 |
+
raise RuntimeError(f"Génération d'image échouée sur tous les providers : {e}")
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def _generate_hf(prompt: str) -> str:
|
| 52 |
+
"""
|
| 53 |
+
Appel à l'API HF Inference pour FLUX.1-schnell.
|
| 54 |
+
Retourne le PNG en base64.
|
| 55 |
+
"""
|
| 56 |
+
headers = {"Authorization": f"Bearer {settings.hf_token}"}
|
| 57 |
+
payload = {
|
| 58 |
+
"inputs": prompt,
|
| 59 |
+
"parameters": {
|
| 60 |
+
"width": 1024,
|
| 61 |
+
"height": 1024,
|
| 62 |
+
"num_inference_steps": 4, # FLUX schnell = 1-4 steps suffisent
|
| 63 |
+
},
|
| 64 |
+
}
|
| 65 |
+
|
| 66 |
+
with httpx.Client(timeout=60) as client:
|
| 67 |
+
response = client.post(HF_API_URL, headers=headers, json=payload)
|
| 68 |
+
|
| 69 |
+
if response.status_code == 503:
|
| 70 |
+
raise RuntimeError("Modèle HF en cours de chargement (cold start)")
|
| 71 |
+
if response.status_code == 429:
|
| 72 |
+
raise RuntimeError("Rate limit HF atteint")
|
| 73 |
+
response.raise_for_status()
|
| 74 |
+
|
| 75 |
+
# HF retourne directement les bytes de l'image (pas de JSON)
|
| 76 |
+
image_bytes = response.content
|
| 77 |
+
return base64.b64encode(image_bytes).decode()
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def _generate_pollinations(prompt: str) -> str:
|
| 81 |
+
"""
|
| 82 |
+
Fallback via Pollinations.ai — aucune clé requise.
|
| 83 |
+
Encode le prompt dans l'URL.
|
| 84 |
+
"""
|
| 85 |
+
import urllib.parse
|
| 86 |
+
encoded = urllib.parse.quote(prompt[:500])
|
| 87 |
+
url = f"https://image.pollinations.ai/prompt/{encoded}?width=1024&height=1024&nologo=true"
|
| 88 |
+
|
| 89 |
+
with httpx.Client(timeout=60) as client:
|
| 90 |
+
response = client.get(url)
|
| 91 |
+
response.raise_for_status()
|
| 92 |
+
|
| 93 |
+
return base64.b64encode(response.content).decode()
|
app/services/llm_service.py
ADDED
|
@@ -0,0 +1,158 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
from typing import Generator
|
| 3 |
+
from groq import Groq
|
| 4 |
+
from app.core.config import settings
|
| 5 |
+
from app.schemas.schemas import LinksResponse, LinkItem
|
| 6 |
+
|
| 7 |
+
client = Groq(api_key=settings.groq_api_key)
|
| 8 |
+
|
| 9 |
+
# Llama 3.3-70b : meilleur modèle gratuit disponible sur Groq en 2025
|
| 10 |
+
# ALTERNATIVE : llama-3.1-8b-instant → 10x plus rapide, qualité légèrement inférieure
|
| 11 |
+
# Trigger pour switcher : latence > 10s ou rate limit répété
|
| 12 |
+
MODEL_FAST = "llama-3.3-70b-versatile"
|
| 13 |
+
MODEL_LIGHT = "llama-3.1-8b-instant"
|
| 14 |
+
|
| 15 |
+
# ── Prompts système ────────────────────────────────────────────────────────────
|
| 16 |
+
|
| 17 |
+
LINK_SYSTEM_PROMPT = """Tu analyses des liens d'une page web pour créer une brochure d'entreprise.
|
| 18 |
+
Sélectionne uniquement les liens vers : About/À propos, Équipe, Produits/Services, Carrières, Contact, Presse.
|
| 19 |
+
Ignore : réseaux sociaux, CGU, cookies, PDF, connexion, panier, termes légaux.
|
| 20 |
+
RÉPONDS UNIQUEMENT en JSON valide, sans texte avant ni après, sans markdown.
|
| 21 |
+
Format exact :
|
| 22 |
+
{"links": [{"type": "about page", "url": "https://..."}, {"type": "products", "url": "https://..."}]}"""
|
| 23 |
+
|
| 24 |
+
BROCHURE_SYSTEM_PROMPT = """Tu es un expert en communication d'entreprise et marketing B2B.
|
| 25 |
+
Tu rédiges des brochures professionnelles structurées en Markdown, percutantes et claires.
|
| 26 |
+
|
| 27 |
+
Structure à respecter impérativement :
|
| 28 |
+
# [Nom de l'entreprise]
|
| 29 |
+
> [Tagline ou accroche percutante extraite du site]
|
| 30 |
+
|
| 31 |
+
## À propos
|
| 32 |
+
[2-3 paragraphes sur l'entreprise, sa mission, son histoire]
|
| 33 |
+
|
| 34 |
+
## Nos solutions
|
| 35 |
+
[Description des produits/services principaux, avec avantages clés]
|
| 36 |
+
|
| 37 |
+
## Pourquoi nous choisir
|
| 38 |
+
[3-5 points différenciants, en bullet points]
|
| 39 |
+
|
| 40 |
+
## Notre équipe / Culture
|
| 41 |
+
[Si info disponible sur le site]
|
| 42 |
+
|
| 43 |
+
## Nous rejoindre
|
| 44 |
+
[Si section carrières disponible]
|
| 45 |
+
|
| 46 |
+
## Contact & Coordonnées
|
| 47 |
+
|
| 48 |
+
---
|
| 49 |
+
Ton : professionnel, positif, orienté valeur client.
|
| 50 |
+
Adapte la langue à celle du site web source.
|
| 51 |
+
N'invente rien — base-toi uniquement sur le contenu fourni."""
|
| 52 |
+
|
| 53 |
+
FLYER_PROMPT_SYSTEM = """Tu génères des prompts de qualité pour la génération d'images avec FLUX.1.
|
| 54 |
+
À partir d'une brochure d'entreprise, génère un prompt pour créer un flyer professionnel.
|
| 55 |
+
Le prompt doit être en anglais, très détaillé visuellement.
|
| 56 |
+
Réponds UNIQUEMENT avec le prompt brut, sans introduction ni explication."""
|
| 57 |
+
|
| 58 |
+
# ── Fonctions ──────────────────────────────────────────────────────────────────
|
| 59 |
+
|
| 60 |
+
def extract_relevant_links(base_url: str, links: list[str]) -> LinksResponse:
|
| 61 |
+
"""
|
| 62 |
+
Appel LLM léger (8b) pour filtrer les liens — tâche simple, pas besoin de 70b.
|
| 63 |
+
Utilise le modèle rapide pour minimiser la latence sur cette étape intermédiaire.
|
| 64 |
+
"""
|
| 65 |
+
links_text = "\n".join(links[:60])
|
| 66 |
+
|
| 67 |
+
response = client.chat.completions.create(
|
| 68 |
+
model=MODEL_LIGHT,
|
| 69 |
+
messages=[
|
| 70 |
+
{"role": "system", "content": LINK_SYSTEM_PROMPT},
|
| 71 |
+
{"role": "user", "content": f"URL de base : {base_url}\n\nLiens :\n{links_text}"},
|
| 72 |
+
],
|
| 73 |
+
temperature=0.05, # Quasi-déterministe pour JSON stable
|
| 74 |
+
max_tokens=600,
|
| 75 |
+
)
|
| 76 |
+
|
| 77 |
+
raw = response.choices[0].message.content.strip()
|
| 78 |
+
|
| 79 |
+
# Nettoyage défensif : certains modèles wrappent dans ```json ... ```
|
| 80 |
+
if "```" in raw:
|
| 81 |
+
raw = raw.split("```")[1]
|
| 82 |
+
if raw.startswith("json"):
|
| 83 |
+
raw = raw[4:]
|
| 84 |
+
raw = raw.strip().rstrip("`")
|
| 85 |
+
|
| 86 |
+
try:
|
| 87 |
+
data = json.loads(raw)
|
| 88 |
+
return LinksResponse(**data)
|
| 89 |
+
except Exception:
|
| 90 |
+
return LinksResponse(links=[]) # Fallback propre — pas de crash
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def generate_brochure_stream(
|
| 94 |
+
company_name: str,
|
| 95 |
+
aggregated_content: str,
|
| 96 |
+
) -> Generator[str, None, None]:
|
| 97 |
+
"""
|
| 98 |
+
Génère la brochure en streaming SSE.
|
| 99 |
+
|
| 100 |
+
Yield : chaque token du LLM au fur et à mesure.
|
| 101 |
+
Le résultat cumulé est maintenu côté frontend via append.
|
| 102 |
+
|
| 103 |
+
SSE format attendu par le frontend :
|
| 104 |
+
data: {"type": "token", "content": "texte"}\\n\\n
|
| 105 |
+
"""
|
| 106 |
+
user_prompt = (
|
| 107 |
+
f"Crée une brochure complète pour : {company_name}\n\n"
|
| 108 |
+
f"Contenu extrait du site :\n{aggregated_content[:10000]}"
|
| 109 |
+
)
|
| 110 |
+
|
| 111 |
+
stream = client.chat.completions.create(
|
| 112 |
+
model=MODEL_FAST,
|
| 113 |
+
messages=[
|
| 114 |
+
{"role": "system", "content": BROCHURE_SYSTEM_PROMPT},
|
| 115 |
+
{"role": "user", "content": user_prompt},
|
| 116 |
+
],
|
| 117 |
+
stream=True,
|
| 118 |
+
temperature=0.7,
|
| 119 |
+
max_tokens=2000,
|
| 120 |
+
)
|
| 121 |
+
|
| 122 |
+
for chunk in stream:
|
| 123 |
+
delta = chunk.choices[0].delta.content or ""
|
| 124 |
+
if delta:
|
| 125 |
+
yield delta
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def build_flyer_prompt(company_name: str, brochure_text: str, style: str) -> str:
|
| 129 |
+
"""
|
| 130 |
+
Fait appel au LLM pour transformer la brochure en prompt visuel pour FLUX.1.
|
| 131 |
+
Le LLM extrait : couleurs de marque, secteur, valeurs, pour un prompt cohérent.
|
| 132 |
+
"""
|
| 133 |
+
style_hints = {
|
| 134 |
+
"modern": "modern corporate design, clean lines, geometric shapes, professional",
|
| 135 |
+
"elegant": "luxury elegant design, serif fonts implied, gold accents, premium feel",
|
| 136 |
+
"bold": "bold graphic design, high contrast, strong typography, impactful",
|
| 137 |
+
"minimal": "minimalist design, lots of white space, simple shapes, refined",
|
| 138 |
+
}
|
| 139 |
+
|
| 140 |
+
response = client.chat.completions.create(
|
| 141 |
+
model=MODEL_LIGHT,
|
| 142 |
+
messages=[
|
| 143 |
+
{"role": "system", "content": FLYER_PROMPT_SYSTEM},
|
| 144 |
+
{
|
| 145 |
+
"role": "user",
|
| 146 |
+
"content": (
|
| 147 |
+
f"Company: {company_name}\n"
|
| 148 |
+
f"Style direction: {style_hints.get(style, style_hints['modern'])}\n\n"
|
| 149 |
+
f"Brochure content (excerpt):\n{brochure_text[:2000]}\n\n"
|
| 150 |
+
"Generate a detailed image generation prompt for a professional marketing flyer."
|
| 151 |
+
),
|
| 152 |
+
},
|
| 153 |
+
],
|
| 154 |
+
temperature=0.8,
|
| 155 |
+
max_tokens=300,
|
| 156 |
+
)
|
| 157 |
+
|
| 158 |
+
return response.choices[0].message.content.strip()
|
app/services/scraper.py
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import httpx
|
| 2 |
+
from bs4 import BeautifulSoup
|
| 3 |
+
|
| 4 |
+
HEADERS = {
|
| 5 |
+
"User-Agent": (
|
| 6 |
+
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
|
| 7 |
+
"AppleWebKit/537.36 (KHTML, like Gecko) "
|
| 8 |
+
"Chrome/124.0.0.0 Safari/537.36"
|
| 9 |
+
),
|
| 10 |
+
"Accept-Language": "fr-FR,fr;q=0.9,en;q=0.8",
|
| 11 |
+
}
|
| 12 |
+
|
| 13 |
+
# Tags à supprimer — tout ce qui n'est pas du contenu textuel utile
|
| 14 |
+
NOISE_TAGS = ["script", "style", "img", "input", "button", "nav", "footer",
|
| 15 |
+
"header", "aside", "form", "noscript", "iframe", "svg"]
|
| 16 |
+
|
| 17 |
+
class ScrapedPage:
|
| 18 |
+
"""Représente une page web scrapée et nettoyée"""
|
| 19 |
+
|
| 20 |
+
def __init__(self, url: str, title: str, text: str, links: list[str]):
|
| 21 |
+
self.url = url
|
| 22 |
+
self.title = title
|
| 23 |
+
self.text = text
|
| 24 |
+
self.links = links
|
| 25 |
+
|
| 26 |
+
def get_contents(self, max_chars: int = 4000) -> str:
|
| 27 |
+
"""
|
| 28 |
+
Retourne le contenu formaté, tronqué à max_chars.
|
| 29 |
+
On tronque ici (pas au niveau LLM) pour contrôler le coût en tokens.
|
| 30 |
+
"""
|
| 31 |
+
return f"## Source : {self.url}\n**Titre :** {self.title}\n\n{self.text[:max_chars]}"
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def scrape_url(url: str) -> ScrapedPage:
|
| 35 |
+
"""
|
| 36 |
+
Scrape une URL de façon synchrone.
|
| 37 |
+
|
| 38 |
+
httpx vs requests : httpx supporte HTTP/2 nativement, meilleure gestion
|
| 39 |
+
des timeouts, et la même API s'utilise en async avec `async with httpx.AsyncClient()`.
|
| 40 |
+
C'est l'outil de référence pour FastAPI.
|
| 41 |
+
"""
|
| 42 |
+
try:
|
| 43 |
+
with httpx.Client(headers=HEADERS, timeout=15, follow_redirects=True) as client:
|
| 44 |
+
response = client.get(url)
|
| 45 |
+
response.raise_for_status()
|
| 46 |
+
except httpx.TimeoutException:
|
| 47 |
+
raise ValueError(f"Timeout sur {url}")
|
| 48 |
+
except httpx.HTTPStatusError as e:
|
| 49 |
+
raise ValueError(f"HTTP {e.response.status_code} sur {url}")
|
| 50 |
+
except Exception as e:
|
| 51 |
+
raise ValueError(f"Impossible de charger {url} : {e}")
|
| 52 |
+
|
| 53 |
+
soup = BeautifulSoup(response.content, "html.parser")
|
| 54 |
+
|
| 55 |
+
title = ""
|
| 56 |
+
if soup.title and soup.title.string:
|
| 57 |
+
title = soup.title.string.strip()
|
| 58 |
+
|
| 59 |
+
# Nettoyer le DOM
|
| 60 |
+
for tag in soup(NOISE_TAGS):
|
| 61 |
+
tag.decompose()
|
| 62 |
+
|
| 63 |
+
text = ""
|
| 64 |
+
if soup.body:
|
| 65 |
+
# separator="\n" pour garder la structure paragraphes
|
| 66 |
+
text = soup.body.get_text(separator="\n", strip=True)
|
| 67 |
+
# Réduire les lignes vides multiples
|
| 68 |
+
lines = [l for l in text.splitlines() if l.strip()]
|
| 69 |
+
text = "\n".join(lines)
|
| 70 |
+
|
| 71 |
+
# Extraire les liens absolus uniquement
|
| 72 |
+
raw_links = [a.get("href", "") for a in soup.find_all("a")]
|
| 73 |
+
links = [
|
| 74 |
+
l for l in raw_links
|
| 75 |
+
if l.startswith("http") and len(l) < 300
|
| 76 |
+
]
|
| 77 |
+
|
| 78 |
+
return ScrapedPage(url=url, title=title, text=text, links=links)
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def scrape_multiple(urls: list[str], max_chars_per_page: int = 3000) -> str:
|
| 82 |
+
"""
|
| 83 |
+
Scrape plusieurs URLs et agrège le contenu.
|
| 84 |
+
Les erreurs par page ne font pas planter l'ensemble.
|
| 85 |
+
"""
|
| 86 |
+
parts = []
|
| 87 |
+
for url in urls:
|
| 88 |
+
try:
|
| 89 |
+
page = scrape_url(url)
|
| 90 |
+
parts.append(page.get_contents(max_chars=max_chars_per_page))
|
| 91 |
+
except ValueError as e:
|
| 92 |
+
parts.append(f"## Source : {url}\n[Erreur: {e}]")
|
| 93 |
+
return "\n\n---\n\n".join(parts)
|
app/services/tts_service.py
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import asyncio
|
| 2 |
+
import edge_tts
|
| 3 |
+
from app.core.config import settings
|
| 4 |
+
|
| 5 |
+
# Mapping langue → voix neurales Microsoft
|
| 6 |
+
# edge-tts utilise le moteur TTS de Microsoft Edge — qualité production, zéro coût
|
| 7 |
+
# Liste complète : uv run edge-tts --list-voices
|
| 8 |
+
VOICE_MAP = {
|
| 9 |
+
"fr": settings.tts_voice_fr, # fr-FR-DeniseNeural (par défaut)
|
| 10 |
+
"en": settings.tts_voice_en, # en-US-JennyNeural (par défaut)
|
| 11 |
+
"de": "de-DE-KatjaNeural",
|
| 12 |
+
"es": "es-ES-ElviraNeural",
|
| 13 |
+
}
|
| 14 |
+
|
| 15 |
+
# ALTERNATIVE : ElevenLabs API (elevenlabs.io)
|
| 16 |
+
# Avantage : qualité supérieure, voix customisables, clonage de voix
|
| 17 |
+
# Inconvénient : 10k chars/mois en free tier, payant au-delà
|
| 18 |
+
# Trigger pour switcher : client exige voix custom ou qualité broadcast
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
async def synthesize_speech(text: str, language: str = "fr") -> tuple[bytes, str]:
|
| 22 |
+
"""
|
| 23 |
+
Convertit un texte en MP3 via edge-tts.
|
| 24 |
+
|
| 25 |
+
Retourne : (audio_bytes, voice_name)
|
| 26 |
+
|
| 27 |
+
edge-tts est entièrement async — on utilise asyncio.run() uniquement
|
| 28 |
+
si appelé depuis du code synchrone. Dans FastAPI async, on fait juste await.
|
| 29 |
+
|
| 30 |
+
Limite pratique : textes très longs (>5000 chars) → chunker en paragraphes.
|
| 31 |
+
Pour une brochure complète, prendre uniquement le résumé ou les sections clés.
|
| 32 |
+
"""
|
| 33 |
+
voice = VOICE_MAP.get(language, VOICE_MAP["fr"])
|
| 34 |
+
|
| 35 |
+
# Tronquer à 4000 chars pour éviter les timeouts — assez pour une brochure
|
| 36 |
+
text_clean = text[:4000].strip()
|
| 37 |
+
|
| 38 |
+
communicate = edge_tts.Communicate(text_clean, voice)
|
| 39 |
+
|
| 40 |
+
audio_chunks: list[bytes] = []
|
| 41 |
+
async for chunk in communicate.stream():
|
| 42 |
+
if chunk["type"] == "audio":
|
| 43 |
+
audio_chunks.append(chunk["data"])
|
| 44 |
+
|
| 45 |
+
audio_bytes = b"".join(audio_chunks)
|
| 46 |
+
|
| 47 |
+
if not audio_bytes:
|
| 48 |
+
raise RuntimeError("edge-tts n'a retourné aucune donnée audio")
|
| 49 |
+
|
| 50 |
+
return audio_bytes, voice
|
app/services/web_search.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from duckduckgo_search import DDGS
|
| 2 |
+
from app.schemas.schemas import SearchResult
|
| 3 |
+
|
| 4 |
+
def search_company(query: str, max_results: int = 6) -> list[SearchResult]:
|
| 5 |
+
"""
|
| 6 |
+
Recherche web via DuckDuckGo — zéro API key, zéro coût.
|
| 7 |
+
|
| 8 |
+
Stratégie : on cherche "[company] official website" pour maximiser la chance
|
| 9 |
+
d'obtenir l'URL officielle en premier résultat.
|
| 10 |
+
|
| 11 |
+
ALTERNATIVE : Tavily API (tavily.com) — 1000 recherches/mois gratuit,
|
| 12 |
+
meilleure qualité pour les agents AI. Trigger : si DDG bloque (rate limit
|
| 13 |
+
ou résultats vides répétés). Avantage : conçu pour les LLM pipelines.
|
| 14 |
+
"""
|
| 15 |
+
enriched_query = f"{query} official website"
|
| 16 |
+
|
| 17 |
+
try:
|
| 18 |
+
with DDGS() as ddgs:
|
| 19 |
+
raw_results = list(ddgs.text(enriched_query, max_results=max_results))
|
| 20 |
+
except Exception as e:
|
| 21 |
+
raise RuntimeError(f"Recherche DuckDuckGo échouée : {e}")
|
| 22 |
+
|
| 23 |
+
# Filtrer les résultats non-pertinents (Wikipedia, réseaux sociaux)
|
| 24 |
+
skip_domains = {"wikipedia.org", "facebook.com", "linkedin.com", "twitter.com", "x.com"}
|
| 25 |
+
|
| 26 |
+
results = []
|
| 27 |
+
for r in raw_results:
|
| 28 |
+
url = r.get("href", "")
|
| 29 |
+
if any(domain in url for domain in skip_domains):
|
| 30 |
+
continue
|
| 31 |
+
results.append(SearchResult(
|
| 32 |
+
title=r.get("title", ""),
|
| 33 |
+
url=url,
|
| 34 |
+
snippet=r.get("body", "")[:200],
|
| 35 |
+
))
|
| 36 |
+
|
| 37 |
+
return results[:5] # Max 5 résultats propres
|
llm_service.py
DELETED
|
@@ -1,135 +0,0 @@
|
|
| 1 |
-
import os
|
| 2 |
-
import json
|
| 3 |
-
from groq import Groq
|
| 4 |
-
from typing import Generator
|
| 5 |
-
from dotenv import load_dotenv
|
| 6 |
-
from huggingface_hub import InferenceClient
|
| 7 |
-
|
| 8 |
-
from models import LinksResponse
|
| 9 |
-
|
| 10 |
-
load_dotenv()
|
| 11 |
-
|
| 12 |
-
# -------------- Initialisation du models ----------------
|
| 13 |
-
|
| 14 |
-
# Groq avec ces API ultra rapide
|
| 15 |
-
|
| 16 |
-
MODEL = "llama-3.3-70b-versatile"
|
| 17 |
-
groq_api_key = os.getenv("GROQ_API_KEY")
|
| 18 |
-
|
| 19 |
-
def groq_clients():
|
| 20 |
-
client = Groq(
|
| 21 |
-
api_key=groq_api_key
|
| 22 |
-
)
|
| 23 |
-
return client
|
| 24 |
-
|
| 25 |
-
# Si Groq atteint ca limite on utilisera HF
|
| 26 |
-
def hf_client():
|
| 27 |
-
client = InferenceClient(
|
| 28 |
-
model="mistralai/Mistral-7B-Instruct-v0.3",
|
| 29 |
-
token=os.getenv("HF_TOKEN")
|
| 30 |
-
)
|
| 31 |
-
return client
|
| 32 |
-
|
| 33 |
-
# Choix du llm par defaut celui degroq
|
| 34 |
-
client = groq_clients()
|
| 35 |
-
|
| 36 |
-
# -------- PROMPTS SYSTEMS --------------
|
| 37 |
-
|
| 38 |
-
LINK_SYSTEM_PROMPT = """Tu es un assistant qui analyse les liens d'une page web.
|
| 39 |
-
Ton rôle : identifier les liens les plus pertinents pour créer une brochure d'entreprise.
|
| 40 |
-
Liens pertinents : About, À propos, Équipe, Carrières, Produits, Services, Contact.
|
| 41 |
-
Exclure : réseaux sociaux externes, CGU, cookies, liens techniques.
|
| 42 |
-
|
| 43 |
-
IMPORTANT : Réponds UNIQUEMENT avec du JSON valide, sans texte avant ou après.
|
| 44 |
-
Format exact :
|
| 45 |
-
{
|
| 46 |
-
"links": [
|
| 47 |
-
{"type": "about page", "url": "https://example.com/about"},
|
| 48 |
-
{"type": "careers page", "url": "https://example.com/careers"}
|
| 49 |
-
]
|
| 50 |
-
}"""
|
| 51 |
-
|
| 52 |
-
BROCHURE_SYSTEM_PROMPT = """Tu es un expert en marketing et communication d'entreprise.
|
| 53 |
-
Tu crées des brochures professionnelles, structurées et convaincantes en Markdown.
|
| 54 |
-
|
| 55 |
-
Structure obligatoire :
|
| 56 |
-
# [Nom de l'entreprise]
|
| 57 |
-
## À propos
|
| 58 |
-
## Nos produits / services
|
| 59 |
-
## Pourquoi nous choisir
|
| 60 |
-
## Nous rejoindre (si info dispo)
|
| 61 |
-
## Contact
|
| 62 |
-
|
| 63 |
-
Ton : professionnel, positif, orienté client.
|
| 64 |
-
Langue : adapter à la langue du site web."""
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
def extract_relevant_links(base_url: str, links: list[str]) -> LinksResponse:
|
| 68 |
-
"""
|
| 69 |
-
Utilise le LLM pour filtrer les liens pertinents pour la brochure.
|
| 70 |
-
Retourne un LinksResponse validé par Pydantic — jamais de crash JSON.
|
| 71 |
-
"""
|
| 72 |
-
links_text = "\n".join(links[:50]) # Max 50 liens pour éviter overflow
|
| 73 |
-
|
| 74 |
-
user_prompt = f"""URL de base : {base_url}
|
| 75 |
-
|
| 76 |
-
Liste des liens trouvés :
|
| 77 |
-
{links_text}
|
| 78 |
-
|
| 79 |
-
Sélectionne les liens pertinents pour une brochure d'entreprise."""
|
| 80 |
-
|
| 81 |
-
response = client.chat.completions.create(
|
| 82 |
-
model=MODEL,
|
| 83 |
-
messages=[
|
| 84 |
-
{"role": "system", "content": LINK_SYSTEM_PROMPT},
|
| 85 |
-
{"role": "user", "content": user_prompt},
|
| 86 |
-
],
|
| 87 |
-
temperature=0.1, # Bas pour des sorties JSON stables
|
| 88 |
-
max_tokens=500,
|
| 89 |
-
)
|
| 90 |
-
|
| 91 |
-
raw_json = response.choices[0].message.content.strip()
|
| 92 |
-
|
| 93 |
-
# Nettoyage robuste — certains modèles ajoutent des ```json ... ```
|
| 94 |
-
if raw_json.startswith("```"):
|
| 95 |
-
raw_json = raw_json.split("```")[1]
|
| 96 |
-
if raw_json.startswith("json"):
|
| 97 |
-
raw_json = raw_json[4:]
|
| 98 |
-
|
| 99 |
-
try:
|
| 100 |
-
data = json.loads(raw_json)
|
| 101 |
-
return LinksResponse(**data)
|
| 102 |
-
except (json.JSONDecodeError, Exception):
|
| 103 |
-
# Fallback : retourner liste vide plutôt que crash
|
| 104 |
-
return LinksResponse(links=[])
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
def generate_brochure_stream(
|
| 108 |
-
company_name: str,
|
| 109 |
-
aggregated_content: str,
|
| 110 |
-
) -> Generator[str, None, None]:
|
| 111 |
-
"""
|
| 112 |
-
Génère la brochure en streaming — l'utilisateur voit le texte s'écrire token par token.
|
| 113 |
-
Retourne un générateur Python (yield).
|
| 114 |
-
"""
|
| 115 |
-
user_prompt = f"""Crée une brochure professionnelle pour l'entreprise : {company_name}
|
| 116 |
-
|
| 117 |
-
Voici le contenu extrait de leur site web :
|
| 118 |
-
{aggregated_content[:8000]}"""
|
| 119 |
-
|
| 120 |
-
stream = client.chat.completions.create(
|
| 121 |
-
model=MODEL,
|
| 122 |
-
messages=[
|
| 123 |
-
{"role": "system", "content": BROCHURE_SYSTEM_PROMPT},
|
| 124 |
-
{"role": "user", "content": user_prompt},
|
| 125 |
-
],
|
| 126 |
-
stream=True,
|
| 127 |
-
temperature=0.5,
|
| 128 |
-
max_tokens=1500,
|
| 129 |
-
)
|
| 130 |
-
|
| 131 |
-
result = ""
|
| 132 |
-
for chunk in stream:
|
| 133 |
-
delta = chunk.choices[0].delta.content or ""
|
| 134 |
-
result += delta
|
| 135 |
-
yield result # Gradio reçoit l'état complet à chaque token
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
main.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import FastAPI
|
| 2 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 3 |
+
from fastapi.staticfiles import StaticFiles
|
| 4 |
+
import os
|
| 5 |
+
|
| 6 |
+
from app.api import search, brochure, tts, flyer
|
| 7 |
+
|
| 8 |
+
app = FastAPI(
|
| 9 |
+
title="BrochureAI Pro",
|
| 10 |
+
description="Génère des brochures professionnelles à partir d'une URL ou d'un nom d'entreprise",
|
| 11 |
+
version="1.0.0",
|
| 12 |
+
)
|
| 13 |
+
|
| 14 |
+
# ── CORS ───────────────────────────────────────────────────────────────────────
|
| 15 |
+
# CORS (Cross-Origin Resource Sharing) : permet au frontend (ex: localhost:5500)
|
| 16 |
+
# d'appeler le backend (localhost:8000) sans que le navigateur bloque la requête.
|
| 17 |
+
# En production : remplacer ["*"] par le domaine exact du frontend.
|
| 18 |
+
app.add_middleware(
|
| 19 |
+
CORSMiddleware,
|
| 20 |
+
allow_origins=["*"],
|
| 21 |
+
allow_credentials=True,
|
| 22 |
+
allow_methods=["*"],
|
| 23 |
+
allow_headers=["*"],
|
| 24 |
+
)
|
| 25 |
+
|
| 26 |
+
# ── Routers ────────────────────────────────────────────────────────────────────
|
| 27 |
+
app.include_router(search.router)
|
| 28 |
+
app.include_router(brochure.router)
|
| 29 |
+
app.include_router(tts.router)
|
| 30 |
+
app.include_router(flyer.router)
|
| 31 |
+
|
| 32 |
+
# ── Healthcheck ────────────────────────────────────────────────────────────────
|
| 33 |
+
@app.get("/health")
|
| 34 |
+
def health():
|
| 35 |
+
return {"status": "ok", "version": "1.0.0"}
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
# ── Dev server ─────────────────────────────────────────────────────────────────
|
| 39 |
+
if __name__ == "__main__":
|
| 40 |
+
import uvicorn
|
| 41 |
+
uvicorn.run("app.main:app", host="0.0.0.0", port=8000, reload=True)
|
models.py
DELETED
|
@@ -1,18 +0,0 @@
|
|
| 1 |
-
from pydantic import BaseModel
|
| 2 |
-
from typing import List
|
| 3 |
-
|
| 4 |
-
class LinkItem(BaseModel):
|
| 5 |
-
"""
|
| 6 |
-
Représente un lien pertinent extrait d'une page web.
|
| 7 |
-
type : catégorie du lien (ex: "about page", "careers")
|
| 8 |
-
url : URL complète et absolue
|
| 9 |
-
"""
|
| 10 |
-
type: str
|
| 11 |
-
url: str
|
| 12 |
-
|
| 13 |
-
class LinksResponse(BaseModel):
|
| 14 |
-
"""
|
| 15 |
-
Réponse structurée du LLM pour l'extraction de liens.
|
| 16 |
-
Pydantic garantit que le JSON est valide — pas de crash.
|
| 17 |
-
"""
|
| 18 |
-
links: List[LinkItem]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
pyproject.toml
CHANGED
|
@@ -1,16 +1,26 @@
|
|
| 1 |
[project]
|
| 2 |
name = "brochure-generator"
|
| 3 |
version = "0.1.0"
|
| 4 |
-
description = "
|
| 5 |
-
|
| 6 |
-
requires-python = ">=3.14"
|
| 7 |
dependencies = [
|
| 8 |
-
"
|
| 9 |
-
"
|
| 10 |
-
"groq>=
|
| 11 |
-
"httpx>=0.
|
| 12 |
-
"
|
| 13 |
-
"pydantic>=2.
|
| 14 |
-
"
|
| 15 |
-
"
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
[project]
|
| 2 |
name = "brochure-generator"
|
| 3 |
version = "0.1.0"
|
| 4 |
+
description = "AI Brochure Generator Backend"
|
| 5 |
+
requires-python = ">=3.12"
|
|
|
|
| 6 |
dependencies = [
|
| 7 |
+
"fastapi>=0.115.0",
|
| 8 |
+
"uvicorn[standard]>=0.30.0",
|
| 9 |
+
"groq>=0.9.0",
|
| 10 |
+
"httpx>=0.27.0",
|
| 11 |
+
"beautifulsoup4>=4.12.0",
|
| 12 |
+
"pydantic>=2.7.0",
|
| 13 |
+
"pydantic-settings>=2.4.0",
|
| 14 |
+
"python-dotenv>=1.0.0",
|
| 15 |
+
"duckduckgo-search>=6.2.0",
|
| 16 |
+
"edge-tts>=6.1.0",
|
| 17 |
+
"huggingface_hub>=0.24.0",
|
| 18 |
+
"pillow>=10.0.0",
|
| 19 |
]
|
| 20 |
+
|
| 21 |
+
[build-system]
|
| 22 |
+
requires = ["hatchling"]
|
| 23 |
+
build-backend = "hatchling.build"
|
| 24 |
+
|
| 25 |
+
[tool.hatch.build.targets.wheel]
|
| 26 |
+
packages = ["backend"]
|
requirements.txt
ADDED
|
@@ -0,0 +1,165 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# This file was autogenerated by uv via the following command:
|
| 2 |
+
# uv export --no-hashes --no-dev -o requirements.txt
|
| 3 |
+
-e .
|
| 4 |
+
aiohappyeyeballs==2.6.1
|
| 5 |
+
# via aiohttp
|
| 6 |
+
aiohttp==3.13.5
|
| 7 |
+
# via edge-tts
|
| 8 |
+
aiosignal==1.4.0
|
| 9 |
+
# via aiohttp
|
| 10 |
+
annotated-doc==0.0.4
|
| 11 |
+
# via
|
| 12 |
+
# fastapi
|
| 13 |
+
# typer
|
| 14 |
+
annotated-types==0.7.0
|
| 15 |
+
# via pydantic
|
| 16 |
+
anyio==4.13.0
|
| 17 |
+
# via
|
| 18 |
+
# groq
|
| 19 |
+
# httpx
|
| 20 |
+
# starlette
|
| 21 |
+
# watchfiles
|
| 22 |
+
attrs==26.1.0
|
| 23 |
+
# via aiohttp
|
| 24 |
+
beautifulsoup4==4.14.3
|
| 25 |
+
# via brochure-generator
|
| 26 |
+
certifi==2026.2.25
|
| 27 |
+
# via
|
| 28 |
+
# edge-tts
|
| 29 |
+
# httpcore
|
| 30 |
+
# httpx
|
| 31 |
+
click==8.3.2
|
| 32 |
+
# via
|
| 33 |
+
# duckduckgo-search
|
| 34 |
+
# typer
|
| 35 |
+
# uvicorn
|
| 36 |
+
colorama==0.4.6 ; sys_platform == 'win32'
|
| 37 |
+
# via
|
| 38 |
+
# click
|
| 39 |
+
# tqdm
|
| 40 |
+
# uvicorn
|
| 41 |
+
distro==1.9.0
|
| 42 |
+
# via groq
|
| 43 |
+
duckduckgo-search==8.1.1
|
| 44 |
+
# via brochure-generator
|
| 45 |
+
edge-tts==7.2.8
|
| 46 |
+
# via brochure-generator
|
| 47 |
+
fastapi==0.135.3
|
| 48 |
+
# via brochure-generator
|
| 49 |
+
filelock==3.25.2
|
| 50 |
+
# via huggingface-hub
|
| 51 |
+
frozenlist==1.8.0
|
| 52 |
+
# via
|
| 53 |
+
# aiohttp
|
| 54 |
+
# aiosignal
|
| 55 |
+
fsspec==2026.3.0
|
| 56 |
+
# via huggingface-hub
|
| 57 |
+
groq==1.1.2
|
| 58 |
+
# via brochure-generator
|
| 59 |
+
h11==0.16.0
|
| 60 |
+
# via
|
| 61 |
+
# httpcore
|
| 62 |
+
# uvicorn
|
| 63 |
+
hf-xet==1.4.3 ; platform_machine == 'AMD64' or platform_machine == 'aarch64' or platform_machine == 'amd64' or platform_machine == 'arm64' or platform_machine == 'x86_64'
|
| 64 |
+
# via huggingface-hub
|
| 65 |
+
httpcore==1.0.9
|
| 66 |
+
# via httpx
|
| 67 |
+
httptools==0.7.1
|
| 68 |
+
# via uvicorn
|
| 69 |
+
httpx==0.28.1
|
| 70 |
+
# via
|
| 71 |
+
# brochure-generator
|
| 72 |
+
# groq
|
| 73 |
+
# huggingface-hub
|
| 74 |
+
huggingface-hub==1.9.2
|
| 75 |
+
# via brochure-generator
|
| 76 |
+
idna==3.11
|
| 77 |
+
# via
|
| 78 |
+
# anyio
|
| 79 |
+
# httpx
|
| 80 |
+
# yarl
|
| 81 |
+
lxml==6.0.2
|
| 82 |
+
# via duckduckgo-search
|
| 83 |
+
markdown-it-py==4.0.0
|
| 84 |
+
# via rich
|
| 85 |
+
mdurl==0.1.2
|
| 86 |
+
# via markdown-it-py
|
| 87 |
+
multidict==6.7.1
|
| 88 |
+
# via
|
| 89 |
+
# aiohttp
|
| 90 |
+
# yarl
|
| 91 |
+
packaging==26.0
|
| 92 |
+
# via huggingface-hub
|
| 93 |
+
pillow==12.2.0
|
| 94 |
+
# via brochure-generator
|
| 95 |
+
primp==1.2.2
|
| 96 |
+
# via duckduckgo-search
|
| 97 |
+
propcache==0.4.1
|
| 98 |
+
# via
|
| 99 |
+
# aiohttp
|
| 100 |
+
# yarl
|
| 101 |
+
pydantic==2.12.5
|
| 102 |
+
# via
|
| 103 |
+
# brochure-generator
|
| 104 |
+
# fastapi
|
| 105 |
+
# groq
|
| 106 |
+
# pydantic-settings
|
| 107 |
+
pydantic-core==2.41.5
|
| 108 |
+
# via pydantic
|
| 109 |
+
pydantic-settings==2.13.1
|
| 110 |
+
# via brochure-generator
|
| 111 |
+
pygments==2.20.0
|
| 112 |
+
# via rich
|
| 113 |
+
python-dotenv==1.2.2
|
| 114 |
+
# via
|
| 115 |
+
# brochure-generator
|
| 116 |
+
# pydantic-settings
|
| 117 |
+
# uvicorn
|
| 118 |
+
pyyaml==6.0.3
|
| 119 |
+
# via
|
| 120 |
+
# huggingface-hub
|
| 121 |
+
# uvicorn
|
| 122 |
+
rich==14.3.3
|
| 123 |
+
# via typer
|
| 124 |
+
shellingham==1.5.4
|
| 125 |
+
# via typer
|
| 126 |
+
sniffio==1.3.1
|
| 127 |
+
# via groq
|
| 128 |
+
soupsieve==2.8.3
|
| 129 |
+
# via beautifulsoup4
|
| 130 |
+
starlette==1.0.0
|
| 131 |
+
# via fastapi
|
| 132 |
+
tabulate==0.10.0
|
| 133 |
+
# via edge-tts
|
| 134 |
+
tqdm==4.67.3
|
| 135 |
+
# via huggingface-hub
|
| 136 |
+
typer==0.24.1
|
| 137 |
+
# via huggingface-hub
|
| 138 |
+
typing-extensions==4.15.0
|
| 139 |
+
# via
|
| 140 |
+
# aiosignal
|
| 141 |
+
# anyio
|
| 142 |
+
# beautifulsoup4
|
| 143 |
+
# edge-tts
|
| 144 |
+
# fastapi
|
| 145 |
+
# groq
|
| 146 |
+
# huggingface-hub
|
| 147 |
+
# pydantic
|
| 148 |
+
# pydantic-core
|
| 149 |
+
# starlette
|
| 150 |
+
# typing-inspection
|
| 151 |
+
typing-inspection==0.4.2
|
| 152 |
+
# via
|
| 153 |
+
# fastapi
|
| 154 |
+
# pydantic
|
| 155 |
+
# pydantic-settings
|
| 156 |
+
uvicorn==0.44.0
|
| 157 |
+
# via brochure-generator
|
| 158 |
+
uvloop==0.22.1 ; platform_python_implementation != 'PyPy' and sys_platform != 'cygwin' and sys_platform != 'win32'
|
| 159 |
+
# via uvicorn
|
| 160 |
+
watchfiles==1.1.1
|
| 161 |
+
# via uvicorn
|
| 162 |
+
websockets==16.0
|
| 163 |
+
# via uvicorn
|
| 164 |
+
yarl==1.23.0
|
| 165 |
+
# via aiohttp
|
scraper.py
DELETED
|
@@ -1,62 +0,0 @@
|
|
| 1 |
-
import httpx
|
| 2 |
-
from bs4 import BeautifulSoup
|
| 3 |
-
from typing import Optional
|
| 4 |
-
|
| 5 |
-
HEADERS = {
|
| 6 |
-
"User-Agent": (
|
| 7 |
-
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
|
| 8 |
-
"AppleWebKit/537.36 (KHTML, like Gecko) "
|
| 9 |
-
"Chrome/120.0.0.0 Safari/537.36"
|
| 10 |
-
)
|
| 11 |
-
}
|
| 12 |
-
|
| 13 |
-
class Website:
|
| 14 |
-
def __init__(self, url: str):
|
| 15 |
-
self.url = url
|
| 16 |
-
self.title = ""
|
| 17 |
-
self.text = ""
|
| 18 |
-
self.links: list[str] = []
|
| 19 |
-
self._fetch()
|
| 20 |
-
|
| 21 |
-
def _fetch(self):
|
| 22 |
-
try:
|
| 23 |
-
response = httpx.get(self.url, headers=HEADERS, timeout=15, follow_redirects=True)
|
| 24 |
-
response.raise_for_status()
|
| 25 |
-
except httpx.HTTPError as e:
|
| 26 |
-
raise ValueError(f"Impossible de charger la page {self.url} : {e}")
|
| 27 |
-
|
| 28 |
-
soup = BeautifulSoup(response.content, "html.parser")
|
| 29 |
-
|
| 30 |
-
self.title = soup.title.string.strip() if soup.title else "Sans titre"
|
| 31 |
-
|
| 32 |
-
# Supprimer les elements non-textuels
|
| 33 |
-
for tag in soup(["script", "style", "img", "input", "nav", "footer"]):
|
| 34 |
-
tag.decompose()
|
| 35 |
-
|
| 36 |
-
self.text = soup.get_text(separator="\n", strip=True) if soup.body else ""
|
| 37 |
-
|
| 38 |
-
# Extraire les liens ansolus uniquement
|
| 39 |
-
raw_links = [a.get("href") for a in soup.find_all("a") if a.get("href")]
|
| 40 |
-
self.links = [
|
| 41 |
-
link for link in raw_links
|
| 42 |
-
if link.startswith("http") and len(link) < 200
|
| 43 |
-
]
|
| 44 |
-
|
| 45 |
-
def get_contents(self) -> str:
|
| 46 |
-
# Tronquer a 500 chars pour ne pas depasser le context window
|
| 47 |
-
truncated = self.text[:5000]
|
| 48 |
-
return f"**Titre:** {self.titre} \n\n**Contenu:**\n{truncated}"
|
| 49 |
-
|
| 50 |
-
def scrape_multiple(urls: list[str]) -> str:
|
| 51 |
-
"""
|
| 52 |
-
Scrape plusieurs URLs et agrege leur contenu.
|
| 53 |
-
Utilise pour combiner page principale + sous-pages (about, careers...)
|
| 54 |
-
"""
|
| 55 |
-
combined = ""
|
| 56 |
-
for url in urls:
|
| 57 |
-
try:
|
| 58 |
-
site = Website(url)
|
| 59 |
-
combined += f"\n\n---\n## Source: {url}\n{site.get_contents()}"
|
| 60 |
-
except Exception as e:
|
| 61 |
-
combined += f"\n\n## Source: {url}\n[Erreur: {e}]"
|
| 62 |
-
return combined
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
uv.lock
CHANGED
|
The diff for this file is too large to render.
See raw diff
|
|
|