Spaces:
Sleeping
Sleeping
Commit ·
235d083
0
Parent(s):
Clean repository without PDF files
Browse files- .dockerignore +8 -0
- .gitignore +2 -0
- .streamlit/config.toml +15 -0
- Dockerfile +30 -0
- README.md +8 -0
- __pycache__/main.cpython-311.pyc +0 -0
- __pycache__/vectorizer.cpython-311.pyc +0 -0
- assets/styles.css +594 -0
- chatbot.py +600 -0
- faiss_index/faiss_index.bin +0 -0
- faiss_index/metadata.pkl +0 -0
- faiss_index/statistics.pkl +0 -0
- main.py +565 -0
- packages.txt +2 -0
- requirements.txt +8 -0
- vectorizer.py +808 -0
.dockerignore
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
__pycache__/
|
| 2 |
+
*.pyc
|
| 3 |
+
.git/
|
| 4 |
+
.gitignore
|
| 5 |
+
*.pdf
|
| 6 |
+
data/
|
| 7 |
+
faiss_index/
|
| 8 |
+
.env
|
.gitignore
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
data/*.pdf
|
| 2 |
+
*.pdf
|
.streamlit/config.toml
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
[theme]
|
| 3 |
+
# Thème clair personnalisé
|
| 4 |
+
primaryColor = "#FF9408"
|
| 5 |
+
backgroundColor = "#F3F4F5"
|
| 6 |
+
secondaryBackgroundColor = "#DBE0E1"
|
| 7 |
+
textColor = "#100C08"
|
| 8 |
+
font = "sans serif"
|
| 9 |
+
|
| 10 |
+
[server]
|
| 11 |
+
headless = true
|
| 12 |
+
port = 8501
|
| 13 |
+
|
| 14 |
+
[browser]
|
| 15 |
+
gatherUsageStats = false
|
Dockerfile
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM python:3.11-slim
|
| 2 |
+
|
| 3 |
+
WORKDIR /app
|
| 4 |
+
|
| 5 |
+
# Installer les dépendances système
|
| 6 |
+
RUN apt-get update && apt-get install -y \
|
| 7 |
+
build-essential \
|
| 8 |
+
&& rm -rf /var/lib/apt/lists/*
|
| 9 |
+
|
| 10 |
+
# Configurer Streamlit pour utiliser /tmp
|
| 11 |
+
ENV STREAMLIT_SERVER_HEADLESS=true
|
| 12 |
+
ENV STREAMLIT_SERVER_PORT=7860
|
| 13 |
+
ENV STREAMLIT_SERVER_ADDRESS=0.0.0.0
|
| 14 |
+
ENV STREAMLIT_BROWSER_GATHER_USAGE_STATS=false
|
| 15 |
+
ENV HOME=/tmp
|
| 16 |
+
|
| 17 |
+
# Copier les fichiers de dépendances
|
| 18 |
+
COPY requirements.txt .
|
| 19 |
+
|
| 20 |
+
# Installer les dépendances Python
|
| 21 |
+
RUN pip install --no-cache-dir -r requirements.txt
|
| 22 |
+
|
| 23 |
+
# Copier le reste de l'application
|
| 24 |
+
COPY . .
|
| 25 |
+
|
| 26 |
+
# Exposer le port 7860 (requis par Hugging Face)
|
| 27 |
+
EXPOSE 7860
|
| 28 |
+
|
| 29 |
+
# Commande de démarrage
|
| 30 |
+
CMD ["python", "-m", "streamlit", "run", "chatbot.py", "--server.port=7860", "--server.address=0.0.0.0", "--server.enableCORS=false", "--server.enableXsrfProtection=false"]
|
README.md
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
title: AskPDF Chatbot
|
| 3 |
+
emoji: 📚
|
| 4 |
+
colorFrom: blue
|
| 5 |
+
colorTo: green
|
| 6 |
+
sdk: docker
|
| 7 |
+
pinned: false
|
| 8 |
+
---
|
__pycache__/main.cpython-311.pyc
ADDED
|
Binary file (26.5 kB). View file
|
|
|
__pycache__/vectorizer.cpython-311.pyc
ADDED
|
Binary file (44.1 kB). View file
|
|
|
assets/styles.css
ADDED
|
@@ -0,0 +1,594 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/* styles.css - Interface Moderne Épurée */
|
| 2 |
+
|
| 3 |
+
/* === PALETTE DE COULEURS === */
|
| 4 |
+
:root {
|
| 5 |
+
/* Couleurs principales */
|
| 6 |
+
--merin-fire: #FF9408;
|
| 7 |
+
--smoky-black: #100C08;
|
| 8 |
+
--chef-hat: #F3F4F5;
|
| 9 |
+
--drifting-cloud: #DBE0E1;
|
| 10 |
+
--sauce-piquante: #CA3F16;
|
| 11 |
+
--bacchic-burgundy: #95122C;
|
| 12 |
+
|
| 13 |
+
/* Application minimaliste */
|
| 14 |
+
--primary-color: var(--merin-fire);
|
| 15 |
+
--background-color: #FFFFFF;
|
| 16 |
+
--surface-color: var(--chef-hat);
|
| 17 |
+
--text-primary: var(--smoky-black);
|
| 18 |
+
--text-secondary: #6B7280;
|
| 19 |
+
--border-color: var(--drifting-cloud);
|
| 20 |
+
|
| 21 |
+
/* Design system */
|
| 22 |
+
--border-radius: 16px;
|
| 23 |
+
--border-radius-small: 8px;
|
| 24 |
+
--spacing-xs: 8px;
|
| 25 |
+
--spacing-sm: 16px;
|
| 26 |
+
--spacing-md: 24px;
|
| 27 |
+
--spacing-lg: 32px;
|
| 28 |
+
--spacing-xl: 48px;
|
| 29 |
+
--shadow-sm: 0 1px 3px rgba(0, 0, 0, 0.08);
|
| 30 |
+
--shadow-md: 0 4px 12px rgba(0, 0, 0, 0.08);
|
| 31 |
+
--shadow-lg: 0 8px 24px rgba(0, 0, 0, 0.1);
|
| 32 |
+
--transition: all 0.2s ease;
|
| 33 |
+
}
|
| 34 |
+
|
| 35 |
+
/* === RESET ET BASE === */
|
| 36 |
+
* {
|
| 37 |
+
color: var(--text-primary);
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
+
.main {
|
| 41 |
+
background-color: var(--background-color);
|
| 42 |
+
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Inter', sans-serif;
|
| 43 |
+
min-height: 100vh;
|
| 44 |
+
}
|
| 45 |
+
|
| 46 |
+
.block-container {
|
| 47 |
+
padding: var(--spacing-lg) var(--spacing-md);
|
| 48 |
+
max-width: 1200px;
|
| 49 |
+
margin: 0 auto;
|
| 50 |
+
}
|
| 51 |
+
|
| 52 |
+
/* === SIDEBAR === */
|
| 53 |
+
.css-1d391kg, [data-testid="stSidebar"] {
|
| 54 |
+
background-color: #FFFFFF;
|
| 55 |
+
border-right: 1px solid var(--border-color);
|
| 56 |
+
box-shadow: var(--shadow-sm);
|
| 57 |
+
}
|
| 58 |
+
|
| 59 |
+
.css-1d391kg *, [data-testid="stSidebar"] * {
|
| 60 |
+
color: var(--text-primary);
|
| 61 |
+
}
|
| 62 |
+
|
| 63 |
+
/* === TITRES === */
|
| 64 |
+
h1 {
|
| 65 |
+
color: var(--text-primary);
|
| 66 |
+
font-weight: 700;
|
| 67 |
+
text-align: center;
|
| 68 |
+
margin-bottom: var(--spacing-lg);
|
| 69 |
+
font-size: 2.5rem;
|
| 70 |
+
letter-spacing: -0.02em;
|
| 71 |
+
}
|
| 72 |
+
|
| 73 |
+
h2 {
|
| 74 |
+
color: var(--text-primary);
|
| 75 |
+
font-weight: 600;
|
| 76 |
+
font-size: 1.5rem;
|
| 77 |
+
margin-bottom: var(--spacing-md);
|
| 78 |
+
margin-top: var(--spacing-lg);
|
| 79 |
+
}
|
| 80 |
+
|
| 81 |
+
h3 {
|
| 82 |
+
color: var(--text-primary);
|
| 83 |
+
font-weight: 600;
|
| 84 |
+
font-size: 1.125rem;
|
| 85 |
+
margin-bottom: var(--spacing-sm);
|
| 86 |
+
}
|
| 87 |
+
|
| 88 |
+
/* === BOUTONS === */
|
| 89 |
+
.stButton > button {
|
| 90 |
+
background-color: var(--primary-color);
|
| 91 |
+
color: white;
|
| 92 |
+
border: none;
|
| 93 |
+
border-radius: var(--border-radius);
|
| 94 |
+
font-weight: 600;
|
| 95 |
+
font-size: 1rem;
|
| 96 |
+
transition: var(--transition);
|
| 97 |
+
padding: 14px 28px;
|
| 98 |
+
box-shadow: none;
|
| 99 |
+
cursor: pointer;
|
| 100 |
+
width: 100%;
|
| 101 |
+
}
|
| 102 |
+
|
| 103 |
+
.stButton > button:hover {
|
| 104 |
+
background-color: #E68507;
|
| 105 |
+
transform: translateY(-1px);
|
| 106 |
+
box-shadow: var(--shadow-md);
|
| 107 |
+
}
|
| 108 |
+
|
| 109 |
+
.stButton > button:active {
|
| 110 |
+
transform: translateY(0);
|
| 111 |
+
}
|
| 112 |
+
|
| 113 |
+
/* === MESSAGES DE CHAT === */
|
| 114 |
+
.stChatMessage {
|
| 115 |
+
border-radius: var(--border-radius);
|
| 116 |
+
margin: var(--spacing-md) 0;
|
| 117 |
+
padding: var(--spacing-md);
|
| 118 |
+
border: 1px solid var(--border-color);
|
| 119 |
+
background-color: #FFFFFF;
|
| 120 |
+
transition: var(--transition);
|
| 121 |
+
}
|
| 122 |
+
|
| 123 |
+
.stChatMessage:hover {
|
| 124 |
+
box-shadow: var(--shadow-sm);
|
| 125 |
+
}
|
| 126 |
+
|
| 127 |
+
/* Messages utilisateur */
|
| 128 |
+
[data-testid="stChatMessage"]:has([data-testid="user"]) {
|
| 129 |
+
background-color: var(--surface-color);
|
| 130 |
+
border: 1px solid var(--border-color);
|
| 131 |
+
}
|
| 132 |
+
|
| 133 |
+
/* Messages assistant */
|
| 134 |
+
[data-testid="stChatMessage"]:has([data-testid="assistant"]) {
|
| 135 |
+
background-color: #FFFFFF;
|
| 136 |
+
border: 1px solid var(--border-color);
|
| 137 |
+
}
|
| 138 |
+
|
| 139 |
+
[data-testid="stChatMessage"]:has([data-testid="assistant"]):hover {
|
| 140 |
+
border-color: var(--primary-color);
|
| 141 |
+
}
|
| 142 |
+
|
| 143 |
+
/* === MÉTRIQUES === */
|
| 144 |
+
.stMetric {
|
| 145 |
+
background-color: #FFFFFF;
|
| 146 |
+
border-radius: var(--border-radius);
|
| 147 |
+
padding: var(--spacing-md);
|
| 148 |
+
border: 1px solid var(--border-color);
|
| 149 |
+
transition: var(--transition);
|
| 150 |
+
}
|
| 151 |
+
|
| 152 |
+
.stMetric:hover {
|
| 153 |
+
border-color: var(--primary-color);
|
| 154 |
+
box-shadow: var(--shadow-sm);
|
| 155 |
+
}
|
| 156 |
+
|
| 157 |
+
.stMetric label {
|
| 158 |
+
color: var(--text-secondary);
|
| 159 |
+
font-weight: 600;
|
| 160 |
+
font-size: 0.875rem;
|
| 161 |
+
text-transform: uppercase;
|
| 162 |
+
letter-spacing: 0.5px;
|
| 163 |
+
}
|
| 164 |
+
|
| 165 |
+
.stMetric [data-testid="stMetricValue"] {
|
| 166 |
+
color: var(--text-primary);
|
| 167 |
+
font-weight: 700;
|
| 168 |
+
font-size: 2rem;
|
| 169 |
+
}
|
| 170 |
+
|
| 171 |
+
/* === ALERTES === */
|
| 172 |
+
.stSuccess {
|
| 173 |
+
background-color: #ECFDF5;
|
| 174 |
+
color: #065F46;
|
| 175 |
+
border-radius: var(--border-radius);
|
| 176 |
+
border: 1px solid #A7F3D0;
|
| 177 |
+
padding: var(--spacing-sm);
|
| 178 |
+
font-weight: 500;
|
| 179 |
+
}
|
| 180 |
+
|
| 181 |
+
.stError {
|
| 182 |
+
background-color: #FEF2F2;
|
| 183 |
+
color: #991B1B;
|
| 184 |
+
border-radius: var(--border-radius);
|
| 185 |
+
border: 1px solid #FECACA;
|
| 186 |
+
padding: var(--spacing-sm);
|
| 187 |
+
font-weight: 500;
|
| 188 |
+
}
|
| 189 |
+
|
| 190 |
+
.stWarning {
|
| 191 |
+
background-color: #FFFBEB;
|
| 192 |
+
color: #92400E;
|
| 193 |
+
border-radius: var(--border-radius);
|
| 194 |
+
border: 1px solid #FCD34D;
|
| 195 |
+
padding: var(--spacing-sm);
|
| 196 |
+
font-weight: 500;
|
| 197 |
+
}
|
| 198 |
+
|
| 199 |
+
.stInfo {
|
| 200 |
+
background-color: #FFF7ED;
|
| 201 |
+
color: #9A3412;
|
| 202 |
+
border-radius: var(--border-radius);
|
| 203 |
+
border: 1px solid #FDBA74;
|
| 204 |
+
padding: var(--spacing-sm);
|
| 205 |
+
font-weight: 500;
|
| 206 |
+
}
|
| 207 |
+
|
| 208 |
+
/* === EXPANDEURS === */
|
| 209 |
+
.streamlit-expanderHeader {
|
| 210 |
+
background-color: #FFFFFF;
|
| 211 |
+
border-radius: var(--border-radius);
|
| 212 |
+
padding: var(--spacing-sm);
|
| 213 |
+
border: 1px solid var(--border-color);
|
| 214 |
+
font-weight: 600;
|
| 215 |
+
color: var(--text-primary);
|
| 216 |
+
transition: var(--transition);
|
| 217 |
+
}
|
| 218 |
+
|
| 219 |
+
.streamlit-expanderHeader:hover {
|
| 220 |
+
background-color: var(--surface-color);
|
| 221 |
+
border-color: var(--primary-color);
|
| 222 |
+
}
|
| 223 |
+
|
| 224 |
+
.streamlit-expanderContent {
|
| 225 |
+
background-color: var(--surface-color);
|
| 226 |
+
border-radius: 0 0 var(--border-radius) var(--border-radius);
|
| 227 |
+
padding: var(--spacing-md);
|
| 228 |
+
border: 1px solid var(--border-color);
|
| 229 |
+
border-top: none;
|
| 230 |
+
margin-top: -1px;
|
| 231 |
+
}
|
| 232 |
+
|
| 233 |
+
/* === INPUTS === */
|
| 234 |
+
.stTextInput > div > div > input,
|
| 235 |
+
.stTextArea > div > div > textarea {
|
| 236 |
+
border-radius: var(--border-radius-small);
|
| 237 |
+
border: 1px solid var(--border-color);
|
| 238 |
+
padding: 12px 16px;
|
| 239 |
+
transition: var(--transition);
|
| 240 |
+
background-color: #FFFFFF;
|
| 241 |
+
color: var(--text-primary);
|
| 242 |
+
font-size: 1rem;
|
| 243 |
+
}
|
| 244 |
+
|
| 245 |
+
.stTextInput > div > div > input:focus,
|
| 246 |
+
.stTextArea > div > div > textarea:focus {
|
| 247 |
+
border-color: var(--primary-color);
|
| 248 |
+
box-shadow: 0 0 0 3px rgba(255, 148, 8, 0.1);
|
| 249 |
+
outline: none;
|
| 250 |
+
}
|
| 251 |
+
|
| 252 |
+
.stTextInput > div > div > input::placeholder,
|
| 253 |
+
.stTextArea > div > div > textarea::placeholder {
|
| 254 |
+
color: var(--text-secondary);
|
| 255 |
+
}
|
| 256 |
+
|
| 257 |
+
/* === CHAT INPUT === */
|
| 258 |
+
.stChatInputContainer {
|
| 259 |
+
border-top: 1px solid var(--border-color);
|
| 260 |
+
background-color: #FFFFFF;
|
| 261 |
+
padding: var(--spacing-md);
|
| 262 |
+
}
|
| 263 |
+
|
| 264 |
+
.stChatInput > div > div > input {
|
| 265 |
+
background-color: var(--surface-color);
|
| 266 |
+
border: 1px solid var(--border-color);
|
| 267 |
+
border-radius: var(--border-radius);
|
| 268 |
+
}
|
| 269 |
+
|
| 270 |
+
.stChatInput > div > div > input:focus {
|
| 271 |
+
border-color: var(--primary-color);
|
| 272 |
+
box-shadow: 0 0 0 3px rgba(255, 148, 8, 0.1);
|
| 273 |
+
}
|
| 274 |
+
|
| 275 |
+
/* === SLIDERS === */
|
| 276 |
+
.stSlider > div > div > div {
|
| 277 |
+
background-color: var(--drifting-cloud);
|
| 278 |
+
}
|
| 279 |
+
|
| 280 |
+
.stSlider > div > div > div > div {
|
| 281 |
+
background-color: var(--primary-color);
|
| 282 |
+
}
|
| 283 |
+
|
| 284 |
+
.stSlider label {
|
| 285 |
+
color: var(--text-primary);
|
| 286 |
+
font-weight: 500;
|
| 287 |
+
}
|
| 288 |
+
|
| 289 |
+
/* === FILE UPLOADER === */
|
| 290 |
+
.stFileUploader {
|
| 291 |
+
background-color: var(--surface-color);
|
| 292 |
+
border: 2px dashed var(--border-color);
|
| 293 |
+
border-radius: var(--border-radius);
|
| 294 |
+
padding: var(--spacing-lg);
|
| 295 |
+
transition: var(--transition);
|
| 296 |
+
text-align: center;
|
| 297 |
+
}
|
| 298 |
+
|
| 299 |
+
.stFileUploader:hover {
|
| 300 |
+
background-color: #FFFFFF;
|
| 301 |
+
border-color: var(--primary-color);
|
| 302 |
+
}
|
| 303 |
+
|
| 304 |
+
.stFileUploader label,
|
| 305 |
+
.stFileUploader span,
|
| 306 |
+
.stFileUploader div {
|
| 307 |
+
color: var(--text-primary);
|
| 308 |
+
}
|
| 309 |
+
|
| 310 |
+
.stFileUploader button {
|
| 311 |
+
background-color: var(--primary-color);
|
| 312 |
+
color: white;
|
| 313 |
+
border: none;
|
| 314 |
+
border-radius: var(--border-radius-small);
|
| 315 |
+
padding: 10px 20px;
|
| 316 |
+
font-weight: 600;
|
| 317 |
+
}
|
| 318 |
+
|
| 319 |
+
.stFileUploader button:hover {
|
| 320 |
+
background-color: #E68507;
|
| 321 |
+
}
|
| 322 |
+
|
| 323 |
+
/* === PROGRESS BAR === */
|
| 324 |
+
.stProgress > div > div > div {
|
| 325 |
+
background-color: var(--drifting-cloud);
|
| 326 |
+
border-radius: 999px;
|
| 327 |
+
}
|
| 328 |
+
|
| 329 |
+
.stProgress > div > div > div > div {
|
| 330 |
+
background: var(--primary-color);
|
| 331 |
+
border-radius: 999px;
|
| 332 |
+
}
|
| 333 |
+
|
| 334 |
+
/* === SELECTBOX === */
|
| 335 |
+
.stSelectbox > div > div {
|
| 336 |
+
border-radius: var(--border-radius-small);
|
| 337 |
+
border: 1px solid var(--border-color);
|
| 338 |
+
background-color: #FFFFFF;
|
| 339 |
+
transition: var(--transition);
|
| 340 |
+
}
|
| 341 |
+
|
| 342 |
+
.stSelectbox > div > div:hover,
|
| 343 |
+
.stSelectbox > div > div:focus-within {
|
| 344 |
+
border-color: var(--primary-color);
|
| 345 |
+
}
|
| 346 |
+
|
| 347 |
+
.stSelectbox label {
|
| 348 |
+
color: var(--text-primary);
|
| 349 |
+
font-weight: 500;
|
| 350 |
+
}
|
| 351 |
+
|
| 352 |
+
/* === CHECKBOX === */
|
| 353 |
+
.stCheckbox {
|
| 354 |
+
padding: var(--spacing-sm) 0;
|
| 355 |
+
}
|
| 356 |
+
|
| 357 |
+
.stCheckbox label {
|
| 358 |
+
color: var(--text-primary);
|
| 359 |
+
font-weight: 500;
|
| 360 |
+
}
|
| 361 |
+
|
| 362 |
+
.stCheckbox > label > div[data-testid="stCheckbox"] > div {
|
| 363 |
+
border: 2px solid var(--border-color);
|
| 364 |
+
border-radius: 4px;
|
| 365 |
+
}
|
| 366 |
+
|
| 367 |
+
.stCheckbox > label > div[data-testid="stCheckbox"] > div[data-checked="true"] {
|
| 368 |
+
background-color: var(--primary-color);
|
| 369 |
+
border-color: var(--primary-color);
|
| 370 |
+
}
|
| 371 |
+
|
| 372 |
+
/* === RADIO BUTTONS === */
|
| 373 |
+
.stRadio > div {
|
| 374 |
+
padding: var(--spacing-sm);
|
| 375 |
+
}
|
| 376 |
+
|
| 377 |
+
.stRadio label {
|
| 378 |
+
color: var(--text-primary);
|
| 379 |
+
font-weight: 500;
|
| 380 |
+
}
|
| 381 |
+
|
| 382 |
+
.stRadio > div > label > div[data-checked="true"] {
|
| 383 |
+
background-color: var(--primary-color);
|
| 384 |
+
}
|
| 385 |
+
|
| 386 |
+
/* === DIVIDERS === */
|
| 387 |
+
hr {
|
| 388 |
+
border: none;
|
| 389 |
+
border-top: 1px solid var(--border-color);
|
| 390 |
+
margin: var(--spacing-lg) 0;
|
| 391 |
+
}
|
| 392 |
+
|
| 393 |
+
/* === SPINNER === */
|
| 394 |
+
.stSpinner > div {
|
| 395 |
+
border-top-color: var(--primary-color);
|
| 396 |
+
}
|
| 397 |
+
|
| 398 |
+
/* === CODE BLOCKS === */
|
| 399 |
+
.stCodeBlock, pre {
|
| 400 |
+
background-color: var(--surface-color);
|
| 401 |
+
border-radius: var(--border-radius-small);
|
| 402 |
+
border: 1px solid var(--border-color);
|
| 403 |
+
padding: var(--spacing-sm);
|
| 404 |
+
}
|
| 405 |
+
|
| 406 |
+
.stCodeBlock code, pre code {
|
| 407 |
+
color: var(--text-primary);
|
| 408 |
+
font-family: 'Monaco', 'Menlo', 'Courier New', monospace;
|
| 409 |
+
font-size: 0.875rem;
|
| 410 |
+
}
|
| 411 |
+
|
| 412 |
+
/* === MARKDOWN === */
|
| 413 |
+
.stMarkdown {
|
| 414 |
+
color: var(--text-primary);
|
| 415 |
+
line-height: 1.6;
|
| 416 |
+
}
|
| 417 |
+
|
| 418 |
+
.stMarkdown p {
|
| 419 |
+
margin-bottom: var(--spacing-sm);
|
| 420 |
+
}
|
| 421 |
+
|
| 422 |
+
.stMarkdown ul, .stMarkdown ol {
|
| 423 |
+
margin-left: var(--spacing-md);
|
| 424 |
+
margin-bottom: var(--spacing-sm);
|
| 425 |
+
}
|
| 426 |
+
|
| 427 |
+
.stMarkdown li {
|
| 428 |
+
margin-bottom: var(--spacing-xs);
|
| 429 |
+
}
|
| 430 |
+
|
| 431 |
+
.stMarkdown a {
|
| 432 |
+
color: var(--primary-color);
|
| 433 |
+
text-decoration: none;
|
| 434 |
+
font-weight: 600;
|
| 435 |
+
}
|
| 436 |
+
|
| 437 |
+
.stMarkdown a:hover {
|
| 438 |
+
text-decoration: underline;
|
| 439 |
+
}
|
| 440 |
+
|
| 441 |
+
.stMarkdown strong {
|
| 442 |
+
font-weight: 700;
|
| 443 |
+
}
|
| 444 |
+
|
| 445 |
+
.stMarkdown code {
|
| 446 |
+
background-color: var(--surface-color);
|
| 447 |
+
color: var(--primary-color);
|
| 448 |
+
padding: 2px 6px;
|
| 449 |
+
border-radius: 4px;
|
| 450 |
+
font-family: 'Monaco', 'Menlo', monospace;
|
| 451 |
+
font-size: 0.875rem;
|
| 452 |
+
}
|
| 453 |
+
|
| 454 |
+
/* === SECTIONS SIDEBAR === */
|
| 455 |
+
.css-1d391kg .element-container,
|
| 456 |
+
[data-testid="stSidebar"] .element-container {
|
| 457 |
+
margin-bottom: var(--spacing-md);
|
| 458 |
+
}
|
| 459 |
+
|
| 460 |
+
/* Titres sidebar plus légers */
|
| 461 |
+
.css-1d391kg h3,
|
| 462 |
+
[data-testid="stSidebar"] h3 {
|
| 463 |
+
font-size: 0.875rem;
|
| 464 |
+
text-transform: uppercase;
|
| 465 |
+
letter-spacing: 0.5px;
|
| 466 |
+
color: var(--text-secondary);
|
| 467 |
+
font-weight: 600;
|
| 468 |
+
margin-top: var(--spacing-md);
|
| 469 |
+
margin-bottom: var(--spacing-sm);
|
| 470 |
+
}
|
| 471 |
+
|
| 472 |
+
/* === SCROLLBAR === */
|
| 473 |
+
::-webkit-scrollbar {
|
| 474 |
+
width: 8px;
|
| 475 |
+
height: 8px;
|
| 476 |
+
}
|
| 477 |
+
|
| 478 |
+
::-webkit-scrollbar-track {
|
| 479 |
+
background: var(--surface-color);
|
| 480 |
+
}
|
| 481 |
+
|
| 482 |
+
::-webkit-scrollbar-thumb {
|
| 483 |
+
background: var(--border-color);
|
| 484 |
+
border-radius: 4px;
|
| 485 |
+
}
|
| 486 |
+
|
| 487 |
+
::-webkit-scrollbar-thumb:hover {
|
| 488 |
+
background: var(--text-secondary);
|
| 489 |
+
}
|
| 490 |
+
|
| 491 |
+
/* === CARTES === */
|
| 492 |
+
.element-container {
|
| 493 |
+
transition: var(--transition);
|
| 494 |
+
}
|
| 495 |
+
|
| 496 |
+
/* === BADGE/TAG STYLE === */
|
| 497 |
+
.stTag {
|
| 498 |
+
background-color: var(--surface-color);
|
| 499 |
+
color: var(--primary-color);
|
| 500 |
+
padding: 4px 12px;
|
| 501 |
+
border-radius: 999px;
|
| 502 |
+
font-size: 0.875rem;
|
| 503 |
+
font-weight: 600;
|
| 504 |
+
display: inline-block;
|
| 505 |
+
border: 1px solid var(--primary-color);
|
| 506 |
+
}
|
| 507 |
+
|
| 508 |
+
/* === ANIMATIONS === */
|
| 509 |
+
@keyframes fadeIn {
|
| 510 |
+
from {
|
| 511 |
+
opacity: 0;
|
| 512 |
+
transform: translateY(10px);
|
| 513 |
+
}
|
| 514 |
+
to {
|
| 515 |
+
opacity: 1;
|
| 516 |
+
transform: translateY(0);
|
| 517 |
+
}
|
| 518 |
+
}
|
| 519 |
+
|
| 520 |
+
.main > div {
|
| 521 |
+
animation: fadeIn 0.3s ease;
|
| 522 |
+
}
|
| 523 |
+
|
| 524 |
+
/* === HEADER MODERNE === */
|
| 525 |
+
.stApp > header {
|
| 526 |
+
background-color: #FFFFFF;
|
| 527 |
+
border-bottom: 1px solid var(--border-color);
|
| 528 |
+
box-shadow: var(--shadow-sm);
|
| 529 |
+
}
|
| 530 |
+
|
| 531 |
+
/* === ESPACEMENT ET RESPIRATION === */
|
| 532 |
+
.row-widget {
|
| 533 |
+
margin-bottom: var(--spacing-sm);
|
| 534 |
+
}
|
| 535 |
+
|
| 536 |
+
/* === AMÉLIORATION VISUELLE DES SOURCES === */
|
| 537 |
+
[data-testid="stExpander"] {
|
| 538 |
+
border: 1px solid var(--border-color);
|
| 539 |
+
border-radius: var(--border-radius);
|
| 540 |
+
margin: var(--spacing-sm) 0;
|
| 541 |
+
background-color: #FFFFFF;
|
| 542 |
+
}
|
| 543 |
+
|
| 544 |
+
/* === RESPONSIVE === */
|
| 545 |
+
@media (max-width: 768px) {
|
| 546 |
+
h1 {
|
| 547 |
+
font-size: 2rem;
|
| 548 |
+
}
|
| 549 |
+
|
| 550 |
+
.block-container {
|
| 551 |
+
padding: var(--spacing-md) var(--spacing-sm);
|
| 552 |
+
}
|
| 553 |
+
|
| 554 |
+
.stButton > button {
|
| 555 |
+
padding: 12px 24px;
|
| 556 |
+
}
|
| 557 |
+
}
|
| 558 |
+
|
| 559 |
+
/* === ICÔNES ET EMOJIS === */
|
| 560 |
+
.stMarkdown p:has(> strong:first-child) {
|
| 561 |
+
display: flex;
|
| 562 |
+
align-items: center;
|
| 563 |
+
gap: var(--spacing-xs);
|
| 564 |
+
}
|
| 565 |
+
|
| 566 |
+
/* === STATS ET INFOS === */
|
| 567 |
+
.stMarkdown blockquote {
|
| 568 |
+
border-left: 3px solid var(--primary-color);
|
| 569 |
+
padding-left: var(--spacing-md);
|
| 570 |
+
margin: var(--spacing-md) 0;
|
| 571 |
+
color: var(--text-secondary);
|
| 572 |
+
font-style: italic;
|
| 573 |
+
}
|
| 574 |
+
|
| 575 |
+
/* === EMPHASE MINIMALE === */
|
| 576 |
+
.stMarkdown em {
|
| 577 |
+
color: var(--text-secondary);
|
| 578 |
+
font-style: italic;
|
| 579 |
+
}
|
| 580 |
+
|
| 581 |
+
/* === LISTE MODERNE === */
|
| 582 |
+
.stMarkdown ul {
|
| 583 |
+
list-style: none;
|
| 584 |
+
padding-left: 0;
|
| 585 |
+
}
|
| 586 |
+
|
| 587 |
+
.stMarkdown ul li::before {
|
| 588 |
+
content: "•";
|
| 589 |
+
color: var(--primary-color);
|
| 590 |
+
font-weight: bold;
|
| 591 |
+
display: inline-block;
|
| 592 |
+
width: 1em;
|
| 593 |
+
margin-left: var(--spacing-sm);
|
| 594 |
+
}
|
chatbot.py
ADDED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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Interface Streamlit avec upload multiple de PDFs + OpenAI
|
| 3 |
+
Version moderne et épurée
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import streamlit as st
|
| 7 |
+
import tempfile
|
| 8 |
+
import os
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
from vectorizer import OptimalPDFVectorizer, DocumentChunk
|
| 11 |
+
from typing import List, Dict, Optional
|
| 12 |
+
import time
|
| 13 |
+
import traceback
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def load_css(file_name):
|
| 17 |
+
"""Charge un fichier CSS externe"""
|
| 18 |
+
try:
|
| 19 |
+
with open(file_name, 'r', encoding='utf-8') as f:
|
| 20 |
+
st.markdown(f'<style>{f.read()}</style>', unsafe_allow_html=True)
|
| 21 |
+
except:
|
| 22 |
+
pass
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class MultiPDFChatbotWithOpenAI:
|
| 26 |
+
"""Chatbot pour traiter plusieurs PDFs avec réponses OpenAI"""
|
| 27 |
+
def __init__(self):
|
| 28 |
+
try:
|
| 29 |
+
self.vectorizer = OptimalPDFVectorizer(
|
| 30 |
+
use_ocr=True,
|
| 31 |
+
ocr_language='fra+eng',
|
| 32 |
+
auto_detect_scanned=True
|
| 33 |
+
)
|
| 34 |
+
self.processed_files = []
|
| 35 |
+
self.openai_client = None
|
| 36 |
+
except Exception as e:
|
| 37 |
+
st.error(f"Erreur lors de la création du vectorizer: {str(e)}")
|
| 38 |
+
raise
|
| 39 |
+
|
| 40 |
+
def setup_openai(self, api_key: str):
|
| 41 |
+
"""Configure OpenAI avec la clé API"""
|
| 42 |
+
try:
|
| 43 |
+
import openai
|
| 44 |
+
self.openai_client = openai.OpenAI(api_key=api_key)
|
| 45 |
+
return True
|
| 46 |
+
except ImportError:
|
| 47 |
+
st.error("Installez OpenAI : pip install openai")
|
| 48 |
+
return False
|
| 49 |
+
except Exception as e:
|
| 50 |
+
st.error(f"Erreur configuration OpenAI : {str(e)}")
|
| 51 |
+
return False
|
| 52 |
+
|
| 53 |
+
def process_multiple_pdfs(self, uploaded_files, max_pages: Optional[int] = None) -> Dict:
|
| 54 |
+
"""Traite plusieurs fichiers PDF uploadés"""
|
| 55 |
+
if not uploaded_files:
|
| 56 |
+
return {"error": "Aucun fichier uploadé"}
|
| 57 |
+
|
| 58 |
+
start_time = time.time()
|
| 59 |
+
all_chunks = []
|
| 60 |
+
self.processed_files = []
|
| 61 |
+
chunk_index = 0
|
| 62 |
+
|
| 63 |
+
progress_text = st.empty()
|
| 64 |
+
progress_bar = st.progress(0)
|
| 65 |
+
|
| 66 |
+
for i, uploaded_file in enumerate(uploaded_files):
|
| 67 |
+
progress_text.text(f"Traitement {i+1}/{len(uploaded_files)}: {uploaded_file.name}")
|
| 68 |
+
progress_bar.progress((i + 1) / len(uploaded_files))
|
| 69 |
+
|
| 70 |
+
try:
|
| 71 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix='.pdf') as tmp_file:
|
| 72 |
+
tmp_file.write(uploaded_file.getbuffer())
|
| 73 |
+
tmp_path = tmp_file.name
|
| 74 |
+
|
| 75 |
+
pages_text = self.vectorizer.extract_text_from_pdf(tmp_path, max_pages=max_pages)
|
| 76 |
+
file_chunks = self.vectorizer.create_chunks(pages_text, uploaded_file.name)
|
| 77 |
+
|
| 78 |
+
for chunk in file_chunks:
|
| 79 |
+
chunk.source_file = uploaded_file.name
|
| 80 |
+
chunk.chunk_index = chunk_index
|
| 81 |
+
all_chunks.append(chunk)
|
| 82 |
+
chunk_index += 1
|
| 83 |
+
|
| 84 |
+
self.processed_files.append({
|
| 85 |
+
'name': uploaded_file.name,
|
| 86 |
+
'pages': len(pages_text),
|
| 87 |
+
'chunks': len(file_chunks),
|
| 88 |
+
'size': uploaded_file.size
|
| 89 |
+
})
|
| 90 |
+
|
| 91 |
+
os.unlink(tmp_path)
|
| 92 |
+
st.success(f"{uploaded_file.name}: {len(pages_text)} pages, {len(file_chunks)} chunks")
|
| 93 |
+
|
| 94 |
+
except Exception as e:
|
| 95 |
+
st.error(f"Erreur avec {uploaded_file.name}: {str(e)}")
|
| 96 |
+
with st.expander("Détails de l'erreur"):
|
| 97 |
+
st.code(traceback.format_exc())
|
| 98 |
+
continue
|
| 99 |
+
|
| 100 |
+
if not all_chunks:
|
| 101 |
+
return {"error": "Aucun contenu extrait des PDFs"}
|
| 102 |
+
|
| 103 |
+
try:
|
| 104 |
+
st.info("Création des embeddings et de l'index de recherche...")
|
| 105 |
+
self.vectorizer.chunks = all_chunks
|
| 106 |
+
embeddings = self.vectorizer.create_embeddings(all_chunks)
|
| 107 |
+
self.vectorizer.index = self.vectorizer.build_faiss_index(embeddings)
|
| 108 |
+
|
| 109 |
+
processing_time = time.time() - start_time
|
| 110 |
+
|
| 111 |
+
return {
|
| 112 |
+
'success': True,
|
| 113 |
+
'files_processed': len(self.processed_files),
|
| 114 |
+
'total_chunks': len(all_chunks),
|
| 115 |
+
'processing_time': processing_time,
|
| 116 |
+
'files_info': self.processed_files
|
| 117 |
+
}
|
| 118 |
+
|
| 119 |
+
except Exception as e:
|
| 120 |
+
st.error(f"Erreur lors de la création de l'index: {str(e)}")
|
| 121 |
+
with st.expander("Détails de l'erreur"):
|
| 122 |
+
st.code(traceback.format_exc())
|
| 123 |
+
return {"error": f"Erreur index: {str(e)}"}
|
| 124 |
+
|
| 125 |
+
def search_with_sources(self, query: str, top_k: int = 5):
|
| 126 |
+
"""Recherche avec sources multi-fichiers"""
|
| 127 |
+
if not self.vectorizer.index:
|
| 128 |
+
return {"error": "Aucun document traité"}
|
| 129 |
+
|
| 130 |
+
try:
|
| 131 |
+
results = self.vectorizer.search(query, top_k)
|
| 132 |
+
|
| 133 |
+
enhanced_results = []
|
| 134 |
+
for chunk, score in results:
|
| 135 |
+
source_file = getattr(chunk, 'source_file', 'Fichier inconnu')
|
| 136 |
+
enhanced_results.append((chunk, score, source_file))
|
| 137 |
+
|
| 138 |
+
return enhanced_results
|
| 139 |
+
|
| 140 |
+
except Exception as e:
|
| 141 |
+
st.error(f"Erreur lors de la recherche: {str(e)}")
|
| 142 |
+
return {"error": f"Erreur recherche: {str(e)}"}
|
| 143 |
+
|
| 144 |
+
def generate_openai_response(self, query: str, search_results: List, model: str = "gpt-3.5-turbo"):
|
| 145 |
+
"""Génère une réponse OpenAI basée sur les résultats de recherche"""
|
| 146 |
+
if not self.openai_client:
|
| 147 |
+
return "Erreur : OpenAI non configuré"
|
| 148 |
+
|
| 149 |
+
if not search_results:
|
| 150 |
+
return "Aucune information trouvée dans vos documents."
|
| 151 |
+
|
| 152 |
+
# Construction du contexte sans numérotation visible
|
| 153 |
+
context_parts = []
|
| 154 |
+
for chunk, score, source_file in search_results:
|
| 155 |
+
context_parts.append(f"""
|
| 156 |
+
Document : {source_file} (Page {chunk.page_number})
|
| 157 |
+
Contenu : {chunk.text}
|
| 158 |
+
""")
|
| 159 |
+
|
| 160 |
+
context = "\n---\n".join(context_parts)
|
| 161 |
+
|
| 162 |
+
system_prompt = """Tu es un assistant spécialisé qui répond aux questions en te basant uniquement sur les documents fournis.
|
| 163 |
+
|
| 164 |
+
INSTRUCTIONS :
|
| 165 |
+
- Réponds uniquement avec les informations contenues dans les documents fournis
|
| 166 |
+
- Sois précis et détaillé
|
| 167 |
+
- Synthétise les informations de manière naturelle et fluide
|
| 168 |
+
- Ne mentionne le numéro des pages que si on te le demande
|
| 169 |
+
- Si les documents ne contiennent pas assez d'informations pour répondre complètement, dis-le clairement
|
| 170 |
+
- Ne cite pas de numéros de sources comme "Source 1" ou "Source 2"
|
| 171 |
+
"""
|
| 172 |
+
#- Tu peux mentionner les documents ou les pages quand c'est pertinent, mais de façon naturelle (ex: "D'après le document X" ou "Selon les informations page Y")
|
| 173 |
+
user_prompt = f"""
|
| 174 |
+
Question de l'utilisateur : {query}
|
| 175 |
+
|
| 176 |
+
Documents disponibles :
|
| 177 |
+
{context}
|
| 178 |
+
|
| 179 |
+
Réponds à la question en te basant sur ces documents uniquement."""
|
| 180 |
+
|
| 181 |
+
try:
|
| 182 |
+
response = self.openai_client.chat.completions.create(
|
| 183 |
+
model=model,
|
| 184 |
+
messages=[
|
| 185 |
+
{"role": "system", "content": system_prompt},
|
| 186 |
+
{"role": "user", "content": user_prompt}
|
| 187 |
+
],
|
| 188 |
+
temperature=0.3,
|
| 189 |
+
max_tokens=1000
|
| 190 |
+
)
|
| 191 |
+
|
| 192 |
+
return response.choices[0].message.content
|
| 193 |
+
|
| 194 |
+
except Exception as e:
|
| 195 |
+
return f"Erreur OpenAI : {str(e)}"
|
| 196 |
+
|
| 197 |
+
def check_dependencies():
|
| 198 |
+
"""Vérifie que toutes les dépendances sont installées"""
|
| 199 |
+
missing_deps = []
|
| 200 |
+
|
| 201 |
+
deps_to_check = [
|
| 202 |
+
("sentence_transformers", "sentence-transformers"),
|
| 203 |
+
("faiss", "faiss-cpu"),
|
| 204 |
+
("pdfplumber", "pdfplumber"),
|
| 205 |
+
("numpy", "numpy"),
|
| 206 |
+
("openai", "openai"),
|
| 207 |
+
("pytesseract", "pytesseract"),
|
| 208 |
+
("pdf2image", "pdf2image"),
|
| 209 |
+
("PIL", "Pillow")
|
| 210 |
+
]
|
| 211 |
+
|
| 212 |
+
for module_name, pip_name in deps_to_check:
|
| 213 |
+
try:
|
| 214 |
+
__import__(module_name)
|
| 215 |
+
except ImportError:
|
| 216 |
+
missing_deps.append(pip_name)
|
| 217 |
+
|
| 218 |
+
return missing_deps
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
def create_multi_pdf_interface():
|
| 222 |
+
"""Interface Streamlit moderne pour traiter plusieurs PDFs avec OpenAI"""
|
| 223 |
+
|
| 224 |
+
st.set_page_config(
|
| 225 |
+
page_title="AskPDF",
|
| 226 |
+
page_icon="✨",
|
| 227 |
+
layout="wide",
|
| 228 |
+
initial_sidebar_state="expanded"
|
| 229 |
+
)
|
| 230 |
+
|
| 231 |
+
load_css('assets/styles.css')
|
| 232 |
+
|
| 233 |
+
# Forcer le thème clair
|
| 234 |
+
st.markdown("""
|
| 235 |
+
<style>
|
| 236 |
+
/* Forcer le fond blanc sur tous les conteneurs */
|
| 237 |
+
.stApp {
|
| 238 |
+
background-color: #FFFFFF !important;
|
| 239 |
+
}
|
| 240 |
+
|
| 241 |
+
.main .block-container {
|
| 242 |
+
background-color: #FFFFFF !important;
|
| 243 |
+
}
|
| 244 |
+
|
| 245 |
+
/* Assurer que le texte est visible sur fond blanc */
|
| 246 |
+
.stApp, .main, .block-container {
|
| 247 |
+
color: #100C08 !important;
|
| 248 |
+
}
|
| 249 |
+
</style>
|
| 250 |
+
""", unsafe_allow_html=True)
|
| 251 |
+
|
| 252 |
+
# Style additionnel pour l'interface moderne
|
| 253 |
+
st.markdown("""
|
| 254 |
+
<style>
|
| 255 |
+
#MainMenu {visibility: hidden;}
|
| 256 |
+
footer {visibility: hidden;}
|
| 257 |
+
|
| 258 |
+
.main-title {
|
| 259 |
+
display: flex;
|
| 260 |
+
align-items: center;
|
| 261 |
+
justify-content: center;
|
| 262 |
+
gap: 16px;
|
| 263 |
+
margin-bottom: 8px;
|
| 264 |
+
}
|
| 265 |
+
|
| 266 |
+
.subtitle {
|
| 267 |
+
text-align: center;
|
| 268 |
+
color: #6B7280;
|
| 269 |
+
font-size: 1rem;
|
| 270 |
+
margin-bottom: 48px;
|
| 271 |
+
font-weight: 400;
|
| 272 |
+
}
|
| 273 |
+
|
| 274 |
+
.stat-card {
|
| 275 |
+
background: white;
|
| 276 |
+
border: 1px solid #DBE0E1;
|
| 277 |
+
border-radius: 12px;
|
| 278 |
+
padding: 16px;
|
| 279 |
+
text-align: center;
|
| 280 |
+
}
|
| 281 |
+
|
| 282 |
+
.stat-value {
|
| 283 |
+
font-size: 2rem;
|
| 284 |
+
font-weight: 700;
|
| 285 |
+
color: #100C08;
|
| 286 |
+
margin: 8px 0;
|
| 287 |
+
}
|
| 288 |
+
|
| 289 |
+
.stat-label {
|
| 290 |
+
font-size: 0.875rem;
|
| 291 |
+
color: #6B7280;
|
| 292 |
+
text-transform: uppercase;
|
| 293 |
+
letter-spacing: 0.5px;
|
| 294 |
+
font-weight: 600;
|
| 295 |
+
}
|
| 296 |
+
</style>
|
| 297 |
+
""", unsafe_allow_html=True)
|
| 298 |
+
|
| 299 |
+
# Titre principal
|
| 300 |
+
st.markdown("""
|
| 301 |
+
<div class="main-title">
|
| 302 |
+
<span style="font-size: 3rem;">👾</span>
|
| 303 |
+
<h1 style="margin: 0; font-size: 2.5rem;">Chatbot qui ✨SLAY✨</h1>
|
| 304 |
+
</div>
|
| 305 |
+
<p class="subtitle">Recherche intelligente avec FAISS + OpenAI</p>
|
| 306 |
+
""", unsafe_allow_html=True)
|
| 307 |
+
|
| 308 |
+
# Vérification des dépendances
|
| 309 |
+
missing_deps = check_dependencies()
|
| 310 |
+
if missing_deps:
|
| 311 |
+
st.error("Dépendances manquantes")
|
| 312 |
+
with st.expander("Voir les détails"):
|
| 313 |
+
for dep in missing_deps:
|
| 314 |
+
st.code(f"pip install {dep}")
|
| 315 |
+
st.stop()
|
| 316 |
+
|
| 317 |
+
# Initialisation
|
| 318 |
+
if 'chatbot' not in st.session_state:
|
| 319 |
+
try:
|
| 320 |
+
st.session_state.chatbot = MultiPDFChatbotWithOpenAI()
|
| 321 |
+
st.session_state.docs_processed = False
|
| 322 |
+
st.session_state.messages = []
|
| 323 |
+
st.session_state.openai_configured = False
|
| 324 |
+
|
| 325 |
+
except Exception as e:
|
| 326 |
+
st.error(f"Erreur initialisation : {str(e)}")
|
| 327 |
+
with st.expander("Détails de l'erreur"):
|
| 328 |
+
st.code(traceback.format_exc())
|
| 329 |
+
st.stop()
|
| 330 |
+
|
| 331 |
+
# Configuration automatique d'OpenAI
|
| 332 |
+
if not st.session_state.openai_configured:
|
| 333 |
+
api_key = os.getenv('OPENAI_API_KEY')
|
| 334 |
+
if api_key:
|
| 335 |
+
if st.session_state.chatbot.setup_openai(api_key):
|
| 336 |
+
st.session_state.openai_configured = True
|
| 337 |
+
|
| 338 |
+
# Sidebar
|
| 339 |
+
with st.sidebar:
|
| 340 |
+
st.markdown("### Configuration OpenAI")
|
| 341 |
+
|
| 342 |
+
if st.session_state.openai_configured:
|
| 343 |
+
st.success("Connecté")
|
| 344 |
+
model_choice = st.selectbox(
|
| 345 |
+
"Modèle",
|
| 346 |
+
["gpt-3.5-turbo", "gpt-4", "gpt-4-turbo"],
|
| 347 |
+
index=0
|
| 348 |
+
)
|
| 349 |
+
else:
|
| 350 |
+
st.error("Non configuré")
|
| 351 |
+
st.caption("Variable OPENAI_API_KEY requise")
|
| 352 |
+
|
| 353 |
+
st.divider()
|
| 354 |
+
|
| 355 |
+
st.markdown("### Upload de documents")
|
| 356 |
+
|
| 357 |
+
# Options avancées dans un expander
|
| 358 |
+
with st.expander("Options avancées"):
|
| 359 |
+
st.markdown("**Limitation de pages**")
|
| 360 |
+
limit_pages = st.checkbox(
|
| 361 |
+
"Activer la limitation",
|
| 362 |
+
value=False,
|
| 363 |
+
help="Traite uniquement les N premières pages de chaque fichier"
|
| 364 |
+
)
|
| 365 |
+
|
| 366 |
+
max_pages = None
|
| 367 |
+
if limit_pages:
|
| 368 |
+
max_pages = st.slider(
|
| 369 |
+
"Nombre de pages",
|
| 370 |
+
min_value=1,
|
| 371 |
+
max_value=1000,
|
| 372 |
+
value=50,
|
| 373 |
+
step=10
|
| 374 |
+
)
|
| 375 |
+
st.caption(f"Seules les {max_pages} premières pages seront traitées")
|
| 376 |
+
|
| 377 |
+
st.divider()
|
| 378 |
+
|
| 379 |
+
st.markdown("**Paramètres de recherche**")
|
| 380 |
+
top_k = st.slider("Nombre de sources", 1, 10, 5)
|
| 381 |
+
|
| 382 |
+
response_mode = st.radio(
|
| 383 |
+
"Mode de réponse",
|
| 384 |
+
["OpenAI (recommandé)", "Sources brutes"],
|
| 385 |
+
index=0 if st.session_state.openai_configured else 1
|
| 386 |
+
)
|
| 387 |
+
|
| 388 |
+
# Upload
|
| 389 |
+
uploaded_files = st.file_uploader(
|
| 390 |
+
"Sélectionnez vos PDFs",
|
| 391 |
+
type="pdf",
|
| 392 |
+
accept_multiple_files=True,
|
| 393 |
+
help="PDFs normaux ou scannés"
|
| 394 |
+
)
|
| 395 |
+
|
| 396 |
+
if uploaded_files:
|
| 397 |
+
st.caption(f"{len(uploaded_files)} fichier(s) sélectionné(s)")
|
| 398 |
+
with st.expander("Voir la liste"):
|
| 399 |
+
for file in uploaded_files:
|
| 400 |
+
st.text(f"• {file.name} ({file.size/1024:.1f} KB)")
|
| 401 |
+
|
| 402 |
+
if uploaded_files and st.button("Traiter les documents", type="primary"):
|
| 403 |
+
with st.spinner("Traitement en cours..."):
|
| 404 |
+
try:
|
| 405 |
+
result = st.session_state.chatbot.process_multiple_pdfs(uploaded_files, max_pages=max_pages)
|
| 406 |
+
|
| 407 |
+
if result.get('success'):
|
| 408 |
+
st.session_state.docs_processed = True
|
| 409 |
+
st.success(f"{result['files_processed']} fichiers traités")
|
| 410 |
+
|
| 411 |
+
# Statistiques
|
| 412 |
+
col1, col2 = st.columns(2)
|
| 413 |
+
with col1:
|
| 414 |
+
st.metric("Fichiers", result['files_processed'])
|
| 415 |
+
st.metric("Temps", f"{result['processing_time']:.1f}s")
|
| 416 |
+
with col2:
|
| 417 |
+
st.metric("Chunks", result['total_chunks'])
|
| 418 |
+
|
| 419 |
+
else:
|
| 420 |
+
st.error(result.get('error', 'Erreur inconnue'))
|
| 421 |
+
|
| 422 |
+
except Exception as e:
|
| 423 |
+
st.error(f"Erreur fatale: {str(e)}")
|
| 424 |
+
with st.expander("Détails de l'erreur"):
|
| 425 |
+
st.code(traceback.format_exc())
|
| 426 |
+
|
| 427 |
+
if st.session_state.docs_processed:
|
| 428 |
+
st.divider()
|
| 429 |
+
if st.button("Nouveau traitement"):
|
| 430 |
+
st.session_state.docs_processed = False
|
| 431 |
+
st.session_state.messages = []
|
| 432 |
+
st.session_state.chatbot = MultiPDFChatbotWithOpenAI()
|
| 433 |
+
st.session_state.openai_configured = False
|
| 434 |
+
st.rerun()
|
| 435 |
+
|
| 436 |
+
# Interface principale
|
| 437 |
+
if st.session_state.docs_processed:
|
| 438 |
+
# OCR Status
|
| 439 |
+
if hasattr(st.session_state.chatbot.vectorizer, 'ocr_available'):
|
| 440 |
+
if st.session_state.chatbot.vectorizer.ocr_available:
|
| 441 |
+
st.info("OCR Tesseract actif - Les PDFs scannés sont supportés")
|
| 442 |
+
|
| 443 |
+
st.markdown("### Discussion avec vos documents")
|
| 444 |
+
|
| 445 |
+
# Afficher les messages
|
| 446 |
+
for message in st.session_state.messages:
|
| 447 |
+
if message["role"] == "user":
|
| 448 |
+
st.chat_message("user").write(message["content"])
|
| 449 |
+
else:
|
| 450 |
+
with st.chat_message("assistant"):
|
| 451 |
+
st.write(message["content"])
|
| 452 |
+
|
| 453 |
+
# Afficher les sources
|
| 454 |
+
if "sources" in message and message["sources"]:
|
| 455 |
+
with st.expander(f"Sources ({len(message['sources'])})"):
|
| 456 |
+
for i, (chunk, score, source_file) in enumerate(message["sources"], 1):
|
| 457 |
+
st.markdown(f"""
|
| 458 |
+
**Source {i}** - {source_file} (Page {chunk.page_number})
|
| 459 |
+
Score: {score:.3f} • {chunk.word_count} mots
|
| 460 |
+
|
| 461 |
+
{chunk.text[:300]}{'...' if len(chunk.text) > 300 else ''}
|
| 462 |
+
""")
|
| 463 |
+
if i < len(message['sources']):
|
| 464 |
+
st.divider()
|
| 465 |
+
|
| 466 |
+
# Input utilisateur
|
| 467 |
+
if prompt := st.chat_input("Posez votre question sur les documents..."):
|
| 468 |
+
|
| 469 |
+
st.session_state.messages.append({"role": "user", "content": prompt})
|
| 470 |
+
st.chat_message("user").write(prompt)
|
| 471 |
+
|
| 472 |
+
with st.chat_message("assistant"):
|
| 473 |
+
with st.spinner("Recherche en cours..."):
|
| 474 |
+
|
| 475 |
+
try:
|
| 476 |
+
search_results = st.session_state.chatbot.search_with_sources(prompt, top_k)
|
| 477 |
+
|
| 478 |
+
if isinstance(search_results, dict) and "error" in search_results:
|
| 479 |
+
error_msg = f"Erreur lors de la recherche: {search_results['error']}"
|
| 480 |
+
st.error(error_msg)
|
| 481 |
+
st.session_state.messages.append({
|
| 482 |
+
"role": "assistant",
|
| 483 |
+
"content": error_msg
|
| 484 |
+
})
|
| 485 |
+
|
| 486 |
+
elif search_results and len(search_results) > 0:
|
| 487 |
+
|
| 488 |
+
use_openai = (response_mode.startswith('OpenAI') and
|
| 489 |
+
st.session_state.openai_configured)
|
| 490 |
+
|
| 491 |
+
if use_openai:
|
| 492 |
+
with st.spinner("Génération de la réponse..."):
|
| 493 |
+
openai_response = st.session_state.chatbot.generate_openai_response(
|
| 494 |
+
prompt,
|
| 495 |
+
search_results,
|
| 496 |
+
model_choice
|
| 497 |
+
)
|
| 498 |
+
|
| 499 |
+
st.markdown(openai_response)
|
| 500 |
+
response = openai_response
|
| 501 |
+
|
| 502 |
+
else:
|
| 503 |
+
sources_text = []
|
| 504 |
+
for i, (chunk, score, source_file) in enumerate(search_results, 1):
|
| 505 |
+
sources_text.append(f"""
|
| 506 |
+
**Extrait {i}** (Fichier: {source_file}, Page {chunk.page_number}, Score: {score:.3f}):
|
| 507 |
+
|
| 508 |
+
{chunk.text}
|
| 509 |
+
""".strip())
|
| 510 |
+
|
| 511 |
+
context = "\n\n---\n\n".join(sources_text)
|
| 512 |
+
|
| 513 |
+
response = f"""Voici les informations pertinentes trouvées dans vos documents :
|
| 514 |
+
|
| 515 |
+
{context}
|
| 516 |
+
|
| 517 |
+
---
|
| 518 |
+
|
| 519 |
+
**Résumé:** {len(search_results)} extraits pertinents trouvés pour votre question, provenant de {len(set(source for _, _, source in search_results))} fichier(s) différent(s)."""
|
| 520 |
+
|
| 521 |
+
st.markdown(response)
|
| 522 |
+
|
| 523 |
+
st.session_state.messages.append({
|
| 524 |
+
"role": "assistant",
|
| 525 |
+
"content": response,
|
| 526 |
+
"sources": search_results
|
| 527 |
+
})
|
| 528 |
+
|
| 529 |
+
else:
|
| 530 |
+
no_result_msg = f"Aucune information pertinente trouvée dans vos documents pour la question: '{prompt}'. Essayez de reformuler votre question."
|
| 531 |
+
st.write(no_result_msg)
|
| 532 |
+
st.session_state.messages.append({
|
| 533 |
+
"role": "assistant",
|
| 534 |
+
"content": no_result_msg
|
| 535 |
+
})
|
| 536 |
+
|
| 537 |
+
except Exception as e:
|
| 538 |
+
error_msg = f"Erreur lors de la recherche: {str(e)}"
|
| 539 |
+
st.error(error_msg)
|
| 540 |
+
with st.expander("Détails de l'erreur"):
|
| 541 |
+
st.code(traceback.format_exc())
|
| 542 |
+
st.session_state.messages.append({
|
| 543 |
+
"role": "assistant",
|
| 544 |
+
"content": error_msg
|
| 545 |
+
})
|
| 546 |
+
|
| 547 |
+
else:
|
| 548 |
+
# Page d'accueil épurée
|
| 549 |
+
col1, col2, col3 = st.columns(3)
|
| 550 |
+
|
| 551 |
+
with col1:
|
| 552 |
+
st.markdown("""
|
| 553 |
+
<div class="stat-card">
|
| 554 |
+
<div style="font-size: 2rem;">🔍</div>
|
| 555 |
+
<div class="stat-label">Recherche</div>
|
| 556 |
+
<div style="margin-top: 8px; color: #6B7280; font-size: 0.875rem;">
|
| 557 |
+
FAISS locale haute performance
|
| 558 |
+
</div>
|
| 559 |
+
</div>
|
| 560 |
+
""", unsafe_allow_html=True)
|
| 561 |
+
|
| 562 |
+
with col2:
|
| 563 |
+
st.markdown("""
|
| 564 |
+
<div class="stat-card">
|
| 565 |
+
<div style="font-size: 2rem;">🤖</div>
|
| 566 |
+
<div class="stat-label">Intelligence</div>
|
| 567 |
+
<div style="margin-top: 8px; color: #6B7280; font-size: 0.875rem;">
|
| 568 |
+
Réponses OpenAI GPT
|
| 569 |
+
</div>
|
| 570 |
+
</div>
|
| 571 |
+
""", unsafe_allow_html=True)
|
| 572 |
+
|
| 573 |
+
with col3:
|
| 574 |
+
st.markdown("""
|
| 575 |
+
<div class="stat-card">
|
| 576 |
+
<div style="font-size: 2rem;">📄</div>
|
| 577 |
+
<div class="stat-label">OCR</div>
|
| 578 |
+
<div style="margin-top: 8px; color: #6B7280; font-size: 0.875rem;">
|
| 579 |
+
PDFs scannés supportés
|
| 580 |
+
</div>
|
| 581 |
+
</div>
|
| 582 |
+
""", unsafe_allow_html=True)
|
| 583 |
+
|
| 584 |
+
st.markdown("<br>", unsafe_allow_html=True)
|
| 585 |
+
|
| 586 |
+
st.markdown("""
|
| 587 |
+
### Pour commencer
|
| 588 |
+
|
| 589 |
+
1. Configurez OpenAI avec votre clé API (variable d'environnement OPENAI_API_KEY)
|
| 590 |
+
2. Uploadez vos PDFs dans la sidebar (normaux ou scannés), vous pouvez choisir le nombre de page que vous voulez selectionner
|
| 591 |
+
3. Cliquez sur "Traiter les documents"
|
| 592 |
+
4. Posez vos questions - OpenAI générera des réponses intelligentes
|
| 593 |
+
|
| 594 |
+
|
| 595 |
+
|
| 596 |
+
|
| 597 |
+
""")
|
| 598 |
+
|
| 599 |
+
if __name__ == "__main__":
|
| 600 |
+
create_multi_pdf_interface()
|
faiss_index/faiss_index.bin
ADDED
|
Binary file (18.5 kB). View file
|
|
|
faiss_index/metadata.pkl
ADDED
|
Binary file (9.05 kB). View file
|
|
|
faiss_index/statistics.pkl
ADDED
|
Binary file (223 Bytes). View file
|
|
|
main.py
ADDED
|
@@ -0,0 +1,565 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Pipeline PDF vers FAISS - Version Corrigée
|
| 3 |
+
Traite un PDF pharmaceutique et crée un index de recherche sémantique
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import os
|
| 7 |
+
import sys
|
| 8 |
+
import re
|
| 9 |
+
import numpy as np
|
| 10 |
+
import faiss
|
| 11 |
+
import pickle
|
| 12 |
+
import time
|
| 13 |
+
from typing import List, Tuple, Dict, Optional
|
| 14 |
+
from pathlib import Path
|
| 15 |
+
from dataclasses import dataclass
|
| 16 |
+
import logging
|
| 17 |
+
|
| 18 |
+
# Configuration du logging
|
| 19 |
+
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
| 20 |
+
logger = logging.getLogger(__name__)
|
| 21 |
+
|
| 22 |
+
@dataclass
|
| 23 |
+
class DocumentChunk:
|
| 24 |
+
"""Représente un chunk de document avec ses métadonnées"""
|
| 25 |
+
text: str
|
| 26 |
+
page_number: int
|
| 27 |
+
chunk_index: int
|
| 28 |
+
start_char: int
|
| 29 |
+
end_char: int
|
| 30 |
+
word_count: int = 0
|
| 31 |
+
source_file: str = "" # Ajout pour multi-fichiers
|
| 32 |
+
|
| 33 |
+
def __post_init__(self):
|
| 34 |
+
self.word_count = len(self.text.split())
|
| 35 |
+
|
| 36 |
+
class OptimalPDFVectorizer:
|
| 37 |
+
"""
|
| 38 |
+
Vectorizer PDF optimisé avec gestion d'erreurs robuste
|
| 39 |
+
"""
|
| 40 |
+
|
| 41 |
+
def __init__(self,
|
| 42 |
+
model_name: str = "sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2",
|
| 43 |
+
chunk_size: int = 1000,
|
| 44 |
+
chunk_overlap: int = 200,
|
| 45 |
+
min_chunk_length: int = 50):
|
| 46 |
+
"""
|
| 47 |
+
Initialise le vectorizer avec un modèle multilingue optimisé
|
| 48 |
+
"""
|
| 49 |
+
self.model_name = model_name
|
| 50 |
+
self.chunk_size = chunk_size
|
| 51 |
+
self.chunk_overlap = chunk_overlap
|
| 52 |
+
self.min_chunk_length = min_chunk_length
|
| 53 |
+
|
| 54 |
+
# Initialisation différée des composants
|
| 55 |
+
self.embedding_model = None
|
| 56 |
+
self.embedding_dim = None
|
| 57 |
+
self.index = None
|
| 58 |
+
self.chunks = []
|
| 59 |
+
|
| 60 |
+
self._setup_directories()
|
| 61 |
+
|
| 62 |
+
def _setup_directories(self):
|
| 63 |
+
"""Crée les dossiers nécessaires"""
|
| 64 |
+
self.output_dir = Path("./faiss_index")
|
| 65 |
+
self.output_dir.mkdir(exist_ok=True)
|
| 66 |
+
|
| 67 |
+
def _initialize_model(self):
|
| 68 |
+
"""Initialise le modèle de manière différée avec gestion d'erreurs"""
|
| 69 |
+
if self.embedding_model is None:
|
| 70 |
+
try:
|
| 71 |
+
logger.info(f"🤖 Chargement du modèle {self.model_name}...")
|
| 72 |
+
|
| 73 |
+
# Vérifier si sentence-transformers est installé
|
| 74 |
+
try:
|
| 75 |
+
from sentence_transformers import SentenceTransformer
|
| 76 |
+
except ImportError:
|
| 77 |
+
raise ImportError(
|
| 78 |
+
"sentence-transformers n'est pas installé. "
|
| 79 |
+
"Installez-le avec: pip install sentence-transformers"
|
| 80 |
+
)
|
| 81 |
+
|
| 82 |
+
self.embedding_model = SentenceTransformer(self.model_name)
|
| 83 |
+
self.embedding_dim = self.embedding_model.get_sentence_embedding_dimension()
|
| 84 |
+
|
| 85 |
+
logger.info(f"✅ Modèle chargé - Dimension: {self.embedding_dim}")
|
| 86 |
+
|
| 87 |
+
except Exception as e:
|
| 88 |
+
logger.error(f"❌ Erreur chargement modèle: {e}")
|
| 89 |
+
logger.error("💡 Vérifiez votre connexion internet et les dépendances")
|
| 90 |
+
raise
|
| 91 |
+
|
| 92 |
+
def extract_text_from_pdf(self, pdf_path: str) -> List[Tuple[str, int]]:
|
| 93 |
+
"""
|
| 94 |
+
Extraction robuste du texte PDF avec plusieurs méthodes de fallback
|
| 95 |
+
"""
|
| 96 |
+
pdf_path = Path(pdf_path)
|
| 97 |
+
|
| 98 |
+
if not pdf_path.exists():
|
| 99 |
+
raise FileNotFoundError(f"PDF non trouvé: {pdf_path}")
|
| 100 |
+
|
| 101 |
+
logger.info(f"📄 Extraction du PDF: {pdf_path.name}")
|
| 102 |
+
pages_text = []
|
| 103 |
+
|
| 104 |
+
# Vérifier si pdfplumber est installé
|
| 105 |
+
try:
|
| 106 |
+
import pdfplumber
|
| 107 |
+
except ImportError:
|
| 108 |
+
raise ImportError(
|
| 109 |
+
"pdfplumber n'est pas installé. "
|
| 110 |
+
"Installez-le avec: pip install pdfplumber"
|
| 111 |
+
)
|
| 112 |
+
|
| 113 |
+
# Méthode principale : pdfplumber
|
| 114 |
+
try:
|
| 115 |
+
with pdfplumber.open(pdf_path) as pdf:
|
| 116 |
+
total_pages = len(pdf.pages)
|
| 117 |
+
logger.info(f"📖 {total_pages} pages détectées")
|
| 118 |
+
|
| 119 |
+
for page_num, page in enumerate(pdf.pages, 1):
|
| 120 |
+
try:
|
| 121 |
+
# Extraction du texte
|
| 122 |
+
text = page.extract_text()
|
| 123 |
+
|
| 124 |
+
if text and text.strip():
|
| 125 |
+
# Nettoyage et validation
|
| 126 |
+
cleaned_text = self._clean_text(text)
|
| 127 |
+
|
| 128 |
+
if len(cleaned_text) > self.min_chunk_length:
|
| 129 |
+
pages_text.append((cleaned_text, page_num))
|
| 130 |
+
logger.debug(f"Page {page_num}: {len(cleaned_text)} caractères")
|
| 131 |
+
|
| 132 |
+
except Exception as e:
|
| 133 |
+
logger.warning(f"⚠️ Erreur page {page_num}: {e}")
|
| 134 |
+
continue
|
| 135 |
+
|
| 136 |
+
except Exception as e:
|
| 137 |
+
logger.error(f"❌ Erreur extraction PDF: {e}")
|
| 138 |
+
raise
|
| 139 |
+
|
| 140 |
+
if not pages_text:
|
| 141 |
+
raise ValueError("Aucun texte extrait du PDF")
|
| 142 |
+
|
| 143 |
+
logger.info(f"✅ {len(pages_text)} pages extraites avec succès")
|
| 144 |
+
return pages_text
|
| 145 |
+
|
| 146 |
+
def _clean_text(self, text: str) -> str:
|
| 147 |
+
"""
|
| 148 |
+
Nettoyage intelligent du texte
|
| 149 |
+
"""
|
| 150 |
+
if not text:
|
| 151 |
+
return ""
|
| 152 |
+
|
| 153 |
+
# Suppression des caractères de contrôle
|
| 154 |
+
text = re.sub(r'[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x84\x86-\x9f]', '', text)
|
| 155 |
+
|
| 156 |
+
# Normalisation des espaces et sauts de ligne
|
| 157 |
+
text = re.sub(r'\n\s*\n\s*\n+', '\n\n', text) # Max 2 sauts de ligne consécutifs
|
| 158 |
+
text = re.sub(r'[ \t]+', ' ', text) # Espaces multiples
|
| 159 |
+
text = re.sub(r' ?\n ?', '\n', text) # Espaces autour des sauts de ligne
|
| 160 |
+
|
| 161 |
+
# Suppression des tirets de fin de ligne (césure)
|
| 162 |
+
text = re.sub(r'-\n([a-z])', r'\1', text)
|
| 163 |
+
|
| 164 |
+
return text.strip()
|
| 165 |
+
|
| 166 |
+
def create_chunks(self, pages_text: List[Tuple[str, int]], source_file: str = "") -> List[DocumentChunk]:
|
| 167 |
+
"""
|
| 168 |
+
Création intelligente de chunks avec optimisation sémantique
|
| 169 |
+
"""
|
| 170 |
+
logger.info("🔧 Création des chunks...")
|
| 171 |
+
chunks = []
|
| 172 |
+
chunk_index = 0
|
| 173 |
+
|
| 174 |
+
for page_text, page_num in pages_text:
|
| 175 |
+
text_length = len(page_text)
|
| 176 |
+
|
| 177 |
+
if text_length <= self.chunk_size:
|
| 178 |
+
# Page entière si assez petite
|
| 179 |
+
if text_length >= self.min_chunk_length:
|
| 180 |
+
chunk = DocumentChunk(
|
| 181 |
+
text=page_text,
|
| 182 |
+
page_number=page_num,
|
| 183 |
+
chunk_index=chunk_index,
|
| 184 |
+
start_char=0,
|
| 185 |
+
end_char=text_length,
|
| 186 |
+
source_file=source_file
|
| 187 |
+
)
|
| 188 |
+
chunks.append(chunk)
|
| 189 |
+
chunk_index += 1
|
| 190 |
+
continue
|
| 191 |
+
|
| 192 |
+
# Découpage intelligent pour pages longues
|
| 193 |
+
start = 0
|
| 194 |
+
|
| 195 |
+
while start < text_length:
|
| 196 |
+
end = min(start + self.chunk_size, text_length)
|
| 197 |
+
|
| 198 |
+
if end < text_length:
|
| 199 |
+
# Recherche du meilleur point de coupure
|
| 200 |
+
best_cut = self._find_best_cut_point(page_text, start, end)
|
| 201 |
+
if best_cut > start:
|
| 202 |
+
end = best_cut
|
| 203 |
+
|
| 204 |
+
chunk_text = page_text[start:end].strip()
|
| 205 |
+
|
| 206 |
+
# Validation du chunk
|
| 207 |
+
if len(chunk_text) >= self.min_chunk_length:
|
| 208 |
+
chunk = DocumentChunk(
|
| 209 |
+
text=chunk_text,
|
| 210 |
+
page_number=page_num,
|
| 211 |
+
chunk_index=chunk_index,
|
| 212 |
+
start_char=start,
|
| 213 |
+
end_char=end,
|
| 214 |
+
source_file=source_file
|
| 215 |
+
)
|
| 216 |
+
chunks.append(chunk)
|
| 217 |
+
chunk_index += 1
|
| 218 |
+
|
| 219 |
+
# Calcul du prochain début avec chevauchement intelligent
|
| 220 |
+
next_start = end - self.chunk_overlap
|
| 221 |
+
|
| 222 |
+
# Éviter les chevauchements trop courts
|
| 223 |
+
if next_start <= start + 50:
|
| 224 |
+
next_start = end
|
| 225 |
+
|
| 226 |
+
start = next_start
|
| 227 |
+
|
| 228 |
+
logger.info(f"✅ {len(chunks)} chunks créés")
|
| 229 |
+
|
| 230 |
+
# Statistiques
|
| 231 |
+
if chunks:
|
| 232 |
+
total_words = sum(chunk.word_count for chunk in chunks)
|
| 233 |
+
avg_words = total_words / len(chunks)
|
| 234 |
+
logger.info(f"📊 Moyenne: {avg_words:.1f} mots/chunk, Total: {total_words} mots")
|
| 235 |
+
|
| 236 |
+
return chunks
|
| 237 |
+
|
| 238 |
+
def _find_best_cut_point(self, text: str, start: int, end: int) -> int:
|
| 239 |
+
"""
|
| 240 |
+
Trouve le meilleur point de coupure pour préserver le sens
|
| 241 |
+
"""
|
| 242 |
+
search_window = 100 # Fenêtre de recherche autour du point de coupure
|
| 243 |
+
search_start = max(start, end - search_window)
|
| 244 |
+
search_end = min(len(text), end + search_window // 2)
|
| 245 |
+
search_text = text[search_start:search_end]
|
| 246 |
+
|
| 247 |
+
# Priorités de coupure (par ordre de préférence)
|
| 248 |
+
cut_patterns = [
|
| 249 |
+
r'\n\n', # Double saut de ligne
|
| 250 |
+
r'\. [A-ZÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ]', # Fin de phrase + majuscule
|
| 251 |
+
r'\?\s+[A-ZÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ]', # Point d'interrogation + majuscule
|
| 252 |
+
r'!\s+[A-ZÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ]', # Point d'exclamation + majuscule
|
| 253 |
+
r'\n', # Simple saut de ligne
|
| 254 |
+
r'[;:]\s+', # Ponctuation forte
|
| 255 |
+
r',\s+', # Virgule
|
| 256 |
+
r'\s+' # Espace
|
| 257 |
+
]
|
| 258 |
+
|
| 259 |
+
best_pos = end
|
| 260 |
+
|
| 261 |
+
for pattern in cut_patterns:
|
| 262 |
+
matches = list(re.finditer(pattern, search_text))
|
| 263 |
+
if matches:
|
| 264 |
+
# Prendre la correspondance la plus proche du point de coupure original
|
| 265 |
+
target_pos = end - search_start
|
| 266 |
+
closest_match = min(matches, key=lambda m: abs(m.start() - target_pos))
|
| 267 |
+
candidate_pos = search_start + closest_match.end()
|
| 268 |
+
|
| 269 |
+
# Vérifier que c'est dans une plage acceptable
|
| 270 |
+
if start + 200 <= candidate_pos <= end + 50:
|
| 271 |
+
best_pos = candidate_pos
|
| 272 |
+
break
|
| 273 |
+
|
| 274 |
+
return min(best_pos, len(text))
|
| 275 |
+
|
| 276 |
+
def create_embeddings(self, chunks: List[DocumentChunk]) -> np.ndarray:
|
| 277 |
+
"""
|
| 278 |
+
Création optimisée des embeddings avec gestion de batch
|
| 279 |
+
"""
|
| 280 |
+
self._initialize_model()
|
| 281 |
+
|
| 282 |
+
logger.info(f"🧠 Création des embeddings pour {len(chunks)} chunks...")
|
| 283 |
+
|
| 284 |
+
if not chunks:
|
| 285 |
+
raise ValueError("Aucun chunk à traiter")
|
| 286 |
+
|
| 287 |
+
texts = [chunk.text for chunk in chunks]
|
| 288 |
+
|
| 289 |
+
try:
|
| 290 |
+
# Traitement par batch pour optimiser la mémoire
|
| 291 |
+
batch_size = 32
|
| 292 |
+
all_embeddings = []
|
| 293 |
+
|
| 294 |
+
for i in range(0, len(texts), batch_size):
|
| 295 |
+
batch = texts[i:i + batch_size]
|
| 296 |
+
logger.debug(f"Traitement batch {i//batch_size + 1}/{(len(texts)-1)//batch_size + 1}")
|
| 297 |
+
|
| 298 |
+
batch_embeddings = self.embedding_model.encode(
|
| 299 |
+
batch,
|
| 300 |
+
convert_to_numpy=True,
|
| 301 |
+
show_progress_bar=False,
|
| 302 |
+
normalize_embeddings=True # Normalisation directe
|
| 303 |
+
)
|
| 304 |
+
all_embeddings.append(batch_embeddings)
|
| 305 |
+
|
| 306 |
+
# Concaténation des résultats
|
| 307 |
+
embeddings = np.vstack(all_embeddings)
|
| 308 |
+
|
| 309 |
+
logger.info(f"✅ Embeddings créés: {embeddings.shape}")
|
| 310 |
+
return embeddings
|
| 311 |
+
|
| 312 |
+
except Exception as e:
|
| 313 |
+
logger.error(f"❌ Erreur création embeddings: {e}")
|
| 314 |
+
raise
|
| 315 |
+
|
| 316 |
+
def build_faiss_index(self, embeddings: np.ndarray) -> faiss.Index:
|
| 317 |
+
"""
|
| 318 |
+
Construction d'un index FAISS optimisé
|
| 319 |
+
"""
|
| 320 |
+
logger.info("🔍 Construction de l'index FAISS...")
|
| 321 |
+
|
| 322 |
+
# Choix de l'index selon la taille des données
|
| 323 |
+
n_vectors, dim = embeddings.shape
|
| 324 |
+
|
| 325 |
+
if n_vectors < 1000:
|
| 326 |
+
# Index exact pour petites collections
|
| 327 |
+
index = faiss.IndexFlatIP(dim)
|
| 328 |
+
logger.info("📋 Index exact (IndexFlatIP)")
|
| 329 |
+
else:
|
| 330 |
+
# Index approximatif pour collections plus importantes
|
| 331 |
+
nlist = min(100, n_vectors // 10) # Nombre de clusters
|
| 332 |
+
quantizer = faiss.IndexFlatIP(dim)
|
| 333 |
+
index = faiss.IndexIVFFlat(quantizer, dim, nlist)
|
| 334 |
+
|
| 335 |
+
# Entraînement de l'index
|
| 336 |
+
logger.info(f"🏋️ Entraînement de l'index avec {nlist} clusters...")
|
| 337 |
+
index.train(embeddings)
|
| 338 |
+
logger.info("📋 Index approximatif (IndexIVFFlat)")
|
| 339 |
+
|
| 340 |
+
# Ajout des vecteurs
|
| 341 |
+
index.add(embeddings)
|
| 342 |
+
|
| 343 |
+
logger.info(f"✅ Index construit avec {index.ntotal} vecteurs")
|
| 344 |
+
return index
|
| 345 |
+
|
| 346 |
+
def process_pdf(self, pdf_path: str, save_automatically: bool = True) -> Dict:
|
| 347 |
+
"""
|
| 348 |
+
Pipeline complète avec rapport détaillé
|
| 349 |
+
"""
|
| 350 |
+
start_time = time.time()
|
| 351 |
+
logger.info(f"🚀 Début du traitement: {Path(pdf_path).name}")
|
| 352 |
+
|
| 353 |
+
try:
|
| 354 |
+
# 1. Extraction
|
| 355 |
+
pages_text = self.extract_text_from_pdf(pdf_path)
|
| 356 |
+
|
| 357 |
+
# 2. Création des chunks
|
| 358 |
+
source_file = Path(pdf_path).name
|
| 359 |
+
self.chunks = self.create_chunks(pages_text, source_file)
|
| 360 |
+
|
| 361 |
+
# 3. Création des embeddings
|
| 362 |
+
embeddings = self.create_embeddings(self.chunks)
|
| 363 |
+
|
| 364 |
+
# 4. Construction de l'index
|
| 365 |
+
self.index = self.build_faiss_index(embeddings)
|
| 366 |
+
|
| 367 |
+
# 5. Sauvegarde automatique
|
| 368 |
+
if save_automatically:
|
| 369 |
+
self.save_index()
|
| 370 |
+
|
| 371 |
+
# Rapport final
|
| 372 |
+
processing_time = time.time() - start_time
|
| 373 |
+
|
| 374 |
+
report = {
|
| 375 |
+
'success': True,
|
| 376 |
+
'pdf_path': str(pdf_path),
|
| 377 |
+
'pages_processed': len(pages_text),
|
| 378 |
+
'chunks_created': len(self.chunks),
|
| 379 |
+
'embedding_dimension': self.embedding_dim,
|
| 380 |
+
'processing_time': processing_time,
|
| 381 |
+
'avg_chunk_words': np.mean([chunk.word_count for chunk in self.chunks]) if self.chunks else 0,
|
| 382 |
+
'total_words': sum(chunk.word_count for chunk in self.chunks)
|
| 383 |
+
}
|
| 384 |
+
|
| 385 |
+
logger.info(f"🎉 Traitement terminé en {processing_time:.1f}s")
|
| 386 |
+
logger.info(f"📊 {report['pages_processed']} pages → {report['chunks_created']} chunks → {report['total_words']} mots")
|
| 387 |
+
|
| 388 |
+
return report
|
| 389 |
+
|
| 390 |
+
except Exception as e:
|
| 391 |
+
logger.error(f"❌ Erreur traitement: {e}")
|
| 392 |
+
raise
|
| 393 |
+
|
| 394 |
+
def search(self,
|
| 395 |
+
query: str,
|
| 396 |
+
top_k: int = 5,
|
| 397 |
+
score_threshold: float = 0.1) -> List[Tuple[DocumentChunk, float]]:
|
| 398 |
+
"""
|
| 399 |
+
Recherche sémantique avancée
|
| 400 |
+
"""
|
| 401 |
+
if self.index is None:
|
| 402 |
+
raise ValueError("Index non initialisé - lancez process_pdf() d'abord")
|
| 403 |
+
|
| 404 |
+
if not query.strip():
|
| 405 |
+
return []
|
| 406 |
+
|
| 407 |
+
self._initialize_model()
|
| 408 |
+
|
| 409 |
+
logger.debug(f"🔍 Recherche: '{query[:50]}...'")
|
| 410 |
+
|
| 411 |
+
try:
|
| 412 |
+
# Embedding de la requête
|
| 413 |
+
query_embedding = self.embedding_model.encode(
|
| 414 |
+
[query],
|
| 415 |
+
convert_to_numpy=True,
|
| 416 |
+
normalize_embeddings=True
|
| 417 |
+
)
|
| 418 |
+
|
| 419 |
+
# Recherche dans l'index
|
| 420 |
+
search_k = min(top_k * 2, len(self.chunks), self.index.ntotal)
|
| 421 |
+
scores, indices = self.index.search(query_embedding, search_k)
|
| 422 |
+
|
| 423 |
+
# Filtrage et classement des résultats
|
| 424 |
+
results = []
|
| 425 |
+
for score, idx in zip(scores[0], indices[0]):
|
| 426 |
+
if idx >= 0 and idx < len(self.chunks) and score >= score_threshold:
|
| 427 |
+
results.append((self.chunks[idx], float(score)))
|
| 428 |
+
|
| 429 |
+
# Limitation au top_k final
|
| 430 |
+
results = results[:top_k]
|
| 431 |
+
|
| 432 |
+
logger.debug(f"✅ {len(results)} résultats trouvés")
|
| 433 |
+
return results
|
| 434 |
+
|
| 435 |
+
except Exception as e:
|
| 436 |
+
logger.error(f"❌ Erreur recherche: {e}")
|
| 437 |
+
return []
|
| 438 |
+
|
| 439 |
+
def save_index(self, save_dir: Optional[str] = None) -> Path:
|
| 440 |
+
"""
|
| 441 |
+
Sauvegarde complète avec métadonnées enrichies
|
| 442 |
+
"""
|
| 443 |
+
if self.index is None:
|
| 444 |
+
raise ValueError("Aucun index à sauvegarder")
|
| 445 |
+
|
| 446 |
+
save_path = Path(save_dir) if save_dir else self.output_dir
|
| 447 |
+
save_path.mkdir(exist_ok=True)
|
| 448 |
+
|
| 449 |
+
logger.info(f"💾 Sauvegarde dans: {save_path}")
|
| 450 |
+
|
| 451 |
+
# Sauvegarde de l'index FAISS
|
| 452 |
+
index_file = save_path / "faiss_index.bin"
|
| 453 |
+
faiss.write_index(self.index, str(index_file))
|
| 454 |
+
|
| 455 |
+
# Métadonnées complètes
|
| 456 |
+
metadata = {
|
| 457 |
+
'chunks': self.chunks,
|
| 458 |
+
'model_name': self.model_name,
|
| 459 |
+
'embedding_dim': self.embedding_dim,
|
| 460 |
+
'chunk_size': self.chunk_size,
|
| 461 |
+
'chunk_overlap': self.chunk_overlap,
|
| 462 |
+
'min_chunk_length': self.min_chunk_length,
|
| 463 |
+
'total_chunks': len(self.chunks),
|
| 464 |
+
'creation_time': time.time(),
|
| 465 |
+
'version': '1.0'
|
| 466 |
+
}
|
| 467 |
+
|
| 468 |
+
metadata_file = save_path / "metadata.pkl"
|
| 469 |
+
with open(metadata_file, 'wb') as f:
|
| 470 |
+
pickle.dump(metadata, f)
|
| 471 |
+
|
| 472 |
+
# Sauvegarde des statistiques
|
| 473 |
+
if self.chunks:
|
| 474 |
+
stats = {
|
| 475 |
+
'pages': len(set(chunk.page_number for chunk in self.chunks)),
|
| 476 |
+
'total_words': sum(chunk.word_count for chunk in self.chunks),
|
| 477 |
+
'avg_words_per_chunk': np.mean([chunk.word_count for chunk in self.chunks]),
|
| 478 |
+
'chunk_lengths': [len(chunk.text) for chunk in self.chunks]
|
| 479 |
+
}
|
| 480 |
+
else:
|
| 481 |
+
stats = {'pages': 0, 'total_words': 0, 'avg_words_per_chunk': 0, 'chunk_lengths': []}
|
| 482 |
+
|
| 483 |
+
stats_file = save_path / "statistics.pkl"
|
| 484 |
+
with open(stats_file, 'wb') as f:
|
| 485 |
+
pickle.dump(stats, f)
|
| 486 |
+
|
| 487 |
+
logger.info(f"✅ Sauvegarde terminée: {len(list(save_path.glob('*')))} fichiers")
|
| 488 |
+
return save_path
|
| 489 |
+
|
| 490 |
+
def load_index(self, save_dir: str) -> Dict:
|
| 491 |
+
"""
|
| 492 |
+
Chargement avec validation
|
| 493 |
+
"""
|
| 494 |
+
save_path = Path(save_dir)
|
| 495 |
+
|
| 496 |
+
if not save_path.exists():
|
| 497 |
+
raise FileNotFoundError(f"Dossier introuvable: {save_path}")
|
| 498 |
+
|
| 499 |
+
logger.info(f"📂 Chargement depuis: {save_path}")
|
| 500 |
+
|
| 501 |
+
# Chargement de l'index
|
| 502 |
+
index_file = save_path / "faiss_index.bin"
|
| 503 |
+
if not index_file.exists():
|
| 504 |
+
raise FileNotFoundError(f"Index FAISS manquant: {index_file}")
|
| 505 |
+
|
| 506 |
+
self.index = faiss.read_index(str(index_file))
|
| 507 |
+
|
| 508 |
+
# Chargement des métadonnées
|
| 509 |
+
metadata_file = save_path / "metadata.pkl"
|
| 510 |
+
if not metadata_file.exists():
|
| 511 |
+
raise FileNotFoundError(f"Métadonnées manquantes: {metadata_file}")
|
| 512 |
+
|
| 513 |
+
with open(metadata_file, 'rb') as f:
|
| 514 |
+
metadata = pickle.load(f)
|
| 515 |
+
|
| 516 |
+
# Restauration des attributs
|
| 517 |
+
self.chunks = metadata['chunks']
|
| 518 |
+
self.model_name = metadata['model_name']
|
| 519 |
+
self.embedding_dim = metadata['embedding_dim']
|
| 520 |
+
self.chunk_size = metadata['chunk_size']
|
| 521 |
+
self.chunk_overlap = metadata['chunk_overlap']
|
| 522 |
+
self.min_chunk_length = metadata.get('min_chunk_length', 50)
|
| 523 |
+
|
| 524 |
+
logger.info(f"✅ Index chargé: {len(self.chunks)} chunks, dim={self.embedding_dim}")
|
| 525 |
+
|
| 526 |
+
return {
|
| 527 |
+
'chunks_loaded': len(self.chunks),
|
| 528 |
+
'model_name': self.model_name,
|
| 529 |
+
'embedding_dim': self.embedding_dim,
|
| 530 |
+
'creation_time': metadata.get('creation_time', 'Unknown')
|
| 531 |
+
}
|
| 532 |
+
|
| 533 |
+
|
| 534 |
+
def test_vectorizer():
|
| 535 |
+
"""
|
| 536 |
+
Test simple pour vérifier que tout fonctionne
|
| 537 |
+
"""
|
| 538 |
+
print("🚀 === TEST VECTORIZER ===\n")
|
| 539 |
+
|
| 540 |
+
try:
|
| 541 |
+
# Initialisation
|
| 542 |
+
vectorizer = OptimalPDFVectorizer(
|
| 543 |
+
chunk_size=500,
|
| 544 |
+
chunk_overlap=100,
|
| 545 |
+
min_chunk_length=50
|
| 546 |
+
)
|
| 547 |
+
|
| 548 |
+
print("✅ Vectorizer initialisé")
|
| 549 |
+
print("✅ Test réussi - Le code fonctionne correctement")
|
| 550 |
+
|
| 551 |
+
return True
|
| 552 |
+
|
| 553 |
+
except Exception as e:
|
| 554 |
+
print(f"❌ Erreur test: {e}")
|
| 555 |
+
return False
|
| 556 |
+
|
| 557 |
+
|
| 558 |
+
if __name__ == "__main__":
|
| 559 |
+
# Exécuter le test simple
|
| 560 |
+
success = test_vectorizer()
|
| 561 |
+
|
| 562 |
+
if success:
|
| 563 |
+
print("\n💡 Pour utiliser avec des PDFs, appelez process_pdf() avec le chemin de votre fichier")
|
| 564 |
+
|
| 565 |
+
sys.exit(0 if success else 1)
|
packages.txt
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
tesseract-ocr
|
| 2 |
+
poppler-utils
|
requirements.txt
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
streamlit>=1.28.0
|
| 2 |
+
sentence-transformers>=2.2.0
|
| 3 |
+
faiss-cpu>=1.7.4
|
| 4 |
+
pdfplumber>=0.9.0
|
| 5 |
+
numpy>=1.24.0
|
| 6 |
+
openai>=1.0.0
|
| 7 |
+
pytesseract>=0.3.10
|
| 8 |
+
pdf2image>=1.16.3
|
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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Pipeline PDF vers FAISS - Version OCR AMÉLIORÉE
|
| 3 |
+
Meilleure gestion des PDFs scannés + diagnostic automatique
|
| 4 |
+
MODÈLE CROSS-LINGUAL pour recherche FR→EN
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import os
|
| 8 |
+
import sys
|
| 9 |
+
import re
|
| 10 |
+
import numpy as np
|
| 11 |
+
import faiss
|
| 12 |
+
import pickle
|
| 13 |
+
import time
|
| 14 |
+
from typing import List, Tuple, Dict, Optional
|
| 15 |
+
from pathlib import Path
|
| 16 |
+
from dataclasses import dataclass
|
| 17 |
+
import logging
|
| 18 |
+
|
| 19 |
+
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
| 20 |
+
logger = logging.getLogger(__name__)
|
| 21 |
+
|
| 22 |
+
@dataclass
|
| 23 |
+
class DocumentChunk:
|
| 24 |
+
text: str
|
| 25 |
+
page_number: int
|
| 26 |
+
chunk_index: int
|
| 27 |
+
start_char: int
|
| 28 |
+
end_char: int
|
| 29 |
+
word_count: int = 0
|
| 30 |
+
source_file: str = ""
|
| 31 |
+
|
| 32 |
+
def __post_init__(self):
|
| 33 |
+
self.word_count = len(self.text.split())
|
| 34 |
+
|
| 35 |
+
class OptimalPDFVectorizer:
|
| 36 |
+
"""Vectorizer PDF avec OCR robuste pour PDFs scannés"""
|
| 37 |
+
|
| 38 |
+
def __init__(self,
|
| 39 |
+
model_name: str = "intfloat/multilingual-e5-base", # ✅ MODÈLE CROSS-LINGUAL
|
| 40 |
+
chunk_size: int = 1000,
|
| 41 |
+
chunk_overlap: int = 200,
|
| 42 |
+
min_chunk_length: int = 50,
|
| 43 |
+
use_ocr: bool = True,
|
| 44 |
+
ocr_language: str = 'fra',
|
| 45 |
+
ocr_dpi: int = 300,
|
| 46 |
+
ocr_preprocessing: bool = True,
|
| 47 |
+
auto_detect_scanned: bool = True):
|
| 48 |
+
"""
|
| 49 |
+
Args:
|
| 50 |
+
model_name: Modèle d'embeddings (multilingual-e5-base recommandé pour cross-lingual)
|
| 51 |
+
use_ocr: Active l'OCR pour les PDFs scannés
|
| 52 |
+
ocr_language: 'fra' pour français, 'eng' pour anglais, 'fra+eng' pour les deux
|
| 53 |
+
ocr_dpi: Résolution pour conversion PDF en image (200-400 recommandé)
|
| 54 |
+
ocr_preprocessing: Active le prétraitement des images pour améliorer l'OCR
|
| 55 |
+
auto_detect_scanned: Détection automatique des PDFs scannés (mettre False pour forcer extraction normale)
|
| 56 |
+
"""
|
| 57 |
+
self.model_name = model_name
|
| 58 |
+
self.chunk_size = chunk_size
|
| 59 |
+
self.chunk_overlap = chunk_overlap
|
| 60 |
+
self.min_chunk_length = min_chunk_length
|
| 61 |
+
self.use_ocr = use_ocr
|
| 62 |
+
self.ocr_language = ocr_language
|
| 63 |
+
self.ocr_dpi = ocr_dpi
|
| 64 |
+
self.ocr_preprocessing = ocr_preprocessing
|
| 65 |
+
self.auto_detect_scanned = auto_detect_scanned
|
| 66 |
+
|
| 67 |
+
self.ocr_available = False
|
| 68 |
+
|
| 69 |
+
self.embedding_model = None
|
| 70 |
+
self.embedding_dim = None
|
| 71 |
+
self.index = None
|
| 72 |
+
self.chunks = []
|
| 73 |
+
|
| 74 |
+
# Éviter le warning tokenizers avec fork
|
| 75 |
+
os.environ.setdefault("TOKENIZERS_PARALLELISM", "false")
|
| 76 |
+
|
| 77 |
+
self._setup_directories()
|
| 78 |
+
self._check_ocr_availability()
|
| 79 |
+
|
| 80 |
+
def _setup_directories(self):
|
| 81 |
+
import tempfile
|
| 82 |
+
self.output_dir = Path(tempfile.gettempdir()) / "faiss_index"
|
| 83 |
+
self.output_dir.mkdir(exist_ok=True, parents=True)
|
| 84 |
+
|
| 85 |
+
def _check_ocr_availability(self):
|
| 86 |
+
"""Vérifie si OCR est disponible et diagnostique les problèmes"""
|
| 87 |
+
self.ocr_available = False
|
| 88 |
+
|
| 89 |
+
if not self.use_ocr:
|
| 90 |
+
logger.info("OCR désactivé (use_ocr=False)")
|
| 91 |
+
return
|
| 92 |
+
|
| 93 |
+
try:
|
| 94 |
+
missing = []
|
| 95 |
+
|
| 96 |
+
try:
|
| 97 |
+
import pytesseract
|
| 98 |
+
except ImportError:
|
| 99 |
+
missing.append("pytesseract (pip install pytesseract)")
|
| 100 |
+
|
| 101 |
+
try:
|
| 102 |
+
from pdf2image import convert_from_path
|
| 103 |
+
except ImportError:
|
| 104 |
+
missing.append("pdf2image (pip install pdf2image)")
|
| 105 |
+
|
| 106 |
+
try:
|
| 107 |
+
from PIL import Image, ImageEnhance, ImageFilter
|
| 108 |
+
except ImportError:
|
| 109 |
+
missing.append("Pillow (pip install Pillow)")
|
| 110 |
+
|
| 111 |
+
if missing:
|
| 112 |
+
logger.error(f"❌ Dépendances OCR manquantes: {', '.join(missing)}")
|
| 113 |
+
return
|
| 114 |
+
|
| 115 |
+
try:
|
| 116 |
+
import subprocess
|
| 117 |
+
result = subprocess.run(['tesseract', '--version'],
|
| 118 |
+
capture_output=True, text=True, timeout=5)
|
| 119 |
+
if result.returncode != 0:
|
| 120 |
+
logger.error("❌ Tesseract installé mais ne fonctionne pas correctement")
|
| 121 |
+
return
|
| 122 |
+
|
| 123 |
+
langs_result = subprocess.run(['tesseract', '--list-langs'],
|
| 124 |
+
capture_output=True, text=True, timeout=5)
|
| 125 |
+
available_langs = langs_result.stdout.lower()
|
| 126 |
+
|
| 127 |
+
required_langs = self.ocr_language.lower().split('+')
|
| 128 |
+
missing_langs = [lang for lang in required_langs if lang not in available_langs]
|
| 129 |
+
|
| 130 |
+
if missing_langs:
|
| 131 |
+
logger.warning(f"⚠️ Langues OCR manquantes: {missing_langs}")
|
| 132 |
+
logger.warning("Installation: brew install tesseract-lang (Mac) ou sudo apt install tesseract-ocr-fra (Linux)")
|
| 133 |
+
|
| 134 |
+
self.ocr_available = True
|
| 135 |
+
logger.info(f"✅ OCR Tesseract disponible (langue: {self.ocr_language})")
|
| 136 |
+
|
| 137 |
+
except FileNotFoundError:
|
| 138 |
+
logger.error("❌ Tesseract NON installé")
|
| 139 |
+
logger.error("Installation:")
|
| 140 |
+
logger.error(" - Mac: brew install tesseract tesseract-lang poppler")
|
| 141 |
+
logger.error(" - Linux: sudo apt install tesseract-ocr tesseract-ocr-fra poppler-utils")
|
| 142 |
+
except subprocess.TimeoutExpired:
|
| 143 |
+
logger.error("❌ Timeout lors de la vérification de Tesseract")
|
| 144 |
+
except Exception as e:
|
| 145 |
+
logger.error(f"❌ Erreur vérification Tesseract: {e}")
|
| 146 |
+
|
| 147 |
+
except Exception as e:
|
| 148 |
+
logger.error(f"❌ Erreur inattendue lors de la vérification OCR: {e}")
|
| 149 |
+
self.ocr_available = False
|
| 150 |
+
|
| 151 |
+
def _initialize_model(self):
|
| 152 |
+
if self.embedding_model is None:
|
| 153 |
+
try:
|
| 154 |
+
logger.info(f"Chargement du modèle {self.model_name}...")
|
| 155 |
+
from sentence_transformers import SentenceTransformer
|
| 156 |
+
self.embedding_model = SentenceTransformer(self.model_name)
|
| 157 |
+
self.embedding_dim = self.embedding_model.get_sentence_embedding_dimension()
|
| 158 |
+
logger.info(f"✅ Modèle chargé - Dimension: {self.embedding_dim}")
|
| 159 |
+
logger.info(f"✅ Recherche cross-linguale activée (FR↔EN supporté)")
|
| 160 |
+
except Exception as e:
|
| 161 |
+
logger.error(f"Erreur chargement modèle: {e}")
|
| 162 |
+
raise
|
| 163 |
+
|
| 164 |
+
def _is_scanned_pdf(self, pages_text: List[Tuple[str, int]], total_pages: int) -> bool:
|
| 165 |
+
"""Détection améliorée des PDFs scannés avec critères plus intelligents"""
|
| 166 |
+
if not pages_text:
|
| 167 |
+
logger.info("📊 Diagnostic: Aucune page extraite → PDF scanné")
|
| 168 |
+
return True
|
| 169 |
+
|
| 170 |
+
pages_with_content = 0
|
| 171 |
+
total_chars = 0
|
| 172 |
+
total_words = 0
|
| 173 |
+
chars_on_content_pages = 0
|
| 174 |
+
|
| 175 |
+
for text, _ in pages_text:
|
| 176 |
+
text_clean = text.strip()
|
| 177 |
+
if len(text_clean) > 100:
|
| 178 |
+
pages_with_content += 1
|
| 179 |
+
chars_this_page = len(text_clean)
|
| 180 |
+
total_chars += chars_this_page
|
| 181 |
+
chars_on_content_pages += chars_this_page
|
| 182 |
+
total_words += len(text_clean.split())
|
| 183 |
+
|
| 184 |
+
# Calculs
|
| 185 |
+
extraction_rate = (pages_with_content / total_pages) * 100 if total_pages > 0 else 0
|
| 186 |
+
avg_chars_per_page = total_chars / total_pages if total_pages > 0 else 0
|
| 187 |
+
avg_words_per_page = total_words / total_pages if total_pages > 0 else 0
|
| 188 |
+
|
| 189 |
+
# Nouveau : caractères moyens sur les pages qui ONT du contenu
|
| 190 |
+
avg_chars_per_content_page = chars_on_content_pages / pages_with_content if pages_with_content > 0 else 0
|
| 191 |
+
|
| 192 |
+
# Logging détaillé
|
| 193 |
+
logger.info("📊 Diagnostic PDF:")
|
| 194 |
+
logger.info(f" - Pages avec contenu: {pages_with_content}/{total_pages} ({extraction_rate:.1f}%)")
|
| 195 |
+
logger.info(f" - Caractères moyens/page (toutes): {avg_chars_per_page:.0f}")
|
| 196 |
+
logger.info(f" - Caractères moyens/page (avec contenu): {avg_chars_per_content_page:.0f}")
|
| 197 |
+
logger.info(f" - Mots moyens/page: {avg_words_per_page:.0f}")
|
| 198 |
+
|
| 199 |
+
# Critères améliorés pour détecter un PDF scanné
|
| 200 |
+
# Un PDF est considéré comme scanné SI :
|
| 201 |
+
# 1. Moins de 20% des pages ont du contenu (vraiment très peu)
|
| 202 |
+
# OU
|
| 203 |
+
# 2. Moins de 50% des pages ont du contenu ET les pages avec contenu ont <800 caractères en moyenne
|
| 204 |
+
# OU
|
| 205 |
+
# 3. Toutes les pages ont du contenu mais <300 caractères en moyenne (OCR raté)
|
| 206 |
+
|
| 207 |
+
very_low_extraction = extraction_rate < 20
|
| 208 |
+
low_extraction_and_poor_content = (extraction_rate < 50 and avg_chars_per_content_page < 800)
|
| 209 |
+
all_pages_but_poor = (extraction_rate > 90 and avg_chars_per_page < 300)
|
| 210 |
+
|
| 211 |
+
is_scanned = very_low_extraction or low_extraction_and_poor_content or all_pages_but_poor
|
| 212 |
+
|
| 213 |
+
if is_scanned:
|
| 214 |
+
logger.warning(f"🔍 DÉTECTION: PDF scanné")
|
| 215 |
+
if very_low_extraction:
|
| 216 |
+
logger.warning(f" → Raison: Très peu de pages avec contenu ({extraction_rate:.1f}%)")
|
| 217 |
+
elif low_extraction_and_poor_content:
|
| 218 |
+
logger.warning(f" → Raison: Peu de pages ({extraction_rate:.1f}%) ET peu de contenu par page ({avg_chars_per_content_page:.0f} chars)")
|
| 219 |
+
elif all_pages_but_poor:
|
| 220 |
+
logger.warning(f" → Raison: Toutes les pages mais contenu très pauvre ({avg_chars_per_page:.0f} chars/page)")
|
| 221 |
+
else:
|
| 222 |
+
logger.info(f"✅ DÉTECTION: PDF normal")
|
| 223 |
+
if extraction_rate < 60:
|
| 224 |
+
logger.info(f" → Extraction partielle OK: les pages avec contenu sont riches ({avg_chars_per_content_page:.0f} chars/page)")
|
| 225 |
+
|
| 226 |
+
return is_scanned
|
| 227 |
+
|
| 228 |
+
def _preprocess_image_for_ocr(self, image):
|
| 229 |
+
"""Prétraitement avancé de l'image pour améliorer l'OCR"""
|
| 230 |
+
from PIL import Image, ImageEnhance, ImageFilter
|
| 231 |
+
|
| 232 |
+
if not self.ocr_preprocessing:
|
| 233 |
+
return image
|
| 234 |
+
|
| 235 |
+
try:
|
| 236 |
+
if image.mode != 'L':
|
| 237 |
+
image = image.convert('L')
|
| 238 |
+
|
| 239 |
+
image = image.filter(ImageFilter.SHARPEN)
|
| 240 |
+
|
| 241 |
+
enhancer = ImageEnhance.Contrast(image)
|
| 242 |
+
image = enhancer.enhance(2.0)
|
| 243 |
+
|
| 244 |
+
enhancer = ImageEnhance.Brightness(image)
|
| 245 |
+
image = enhancer.enhance(1.2)
|
| 246 |
+
|
| 247 |
+
threshold = 128
|
| 248 |
+
image = image.point(lambda x: 0 if x < threshold else 255, '1')
|
| 249 |
+
image = image.convert('L')
|
| 250 |
+
|
| 251 |
+
return image
|
| 252 |
+
|
| 253 |
+
except Exception as e:
|
| 254 |
+
logger.warning(f"Erreur prétraitement image: {e}")
|
| 255 |
+
return image
|
| 256 |
+
|
| 257 |
+
def _extract_with_ocr(self, pdf_path: str, max_pages: Optional[int] = None) -> List[Tuple[str, int]]:
|
| 258 |
+
"""Extraction OCR améliorée avec prétraitement d'image
|
| 259 |
+
|
| 260 |
+
Args:
|
| 261 |
+
pdf_path: Chemin vers le PDF
|
| 262 |
+
max_pages: Nombre maximum de pages à traiter (None = toutes les pages)
|
| 263 |
+
"""
|
| 264 |
+
if not self.ocr_available:
|
| 265 |
+
raise RuntimeError("OCR non disponible - vérifiez l'installation de Tesseract")
|
| 266 |
+
|
| 267 |
+
try:
|
| 268 |
+
import pytesseract
|
| 269 |
+
from pdf2image import convert_from_path
|
| 270 |
+
from PIL import Image
|
| 271 |
+
except ImportError as e:
|
| 272 |
+
raise ImportError(f"Installez les dépendances OCR: pip install pytesseract pdf2image Pillow")
|
| 273 |
+
|
| 274 |
+
logger.info(f"🔍 Démarrage OCR Tesseract (DPI: {self.ocr_dpi}, Langue: {self.ocr_language})")
|
| 275 |
+
|
| 276 |
+
try:
|
| 277 |
+
logger.info("📸 Conversion PDF en images...")
|
| 278 |
+
|
| 279 |
+
# Convertir seulement le nombre de pages demandé
|
| 280 |
+
images = convert_from_path(
|
| 281 |
+
pdf_path,
|
| 282 |
+
dpi=self.ocr_dpi,
|
| 283 |
+
thread_count=4,
|
| 284 |
+
fmt='png',
|
| 285 |
+
last_page=max_pages if max_pages else None # Limite à max_pages
|
| 286 |
+
)
|
| 287 |
+
|
| 288 |
+
total_pages = len(images)
|
| 289 |
+
logger.info(f"📄 {total_pages} pages à traiter par OCR")
|
| 290 |
+
|
| 291 |
+
pages_text = []
|
| 292 |
+
successful_pages = 0
|
| 293 |
+
|
| 294 |
+
for page_num, image in enumerate(images, 1):
|
| 295 |
+
try:
|
| 296 |
+
processed_image = self._preprocess_image_for_ocr(image)
|
| 297 |
+
|
| 298 |
+
custom_config = r'--oem 3 --psm 6'
|
| 299 |
+
|
| 300 |
+
text = pytesseract.image_to_string(
|
| 301 |
+
processed_image,
|
| 302 |
+
lang=self.ocr_language,
|
| 303 |
+
config=custom_config
|
| 304 |
+
)
|
| 305 |
+
|
| 306 |
+
if text and text.strip():
|
| 307 |
+
cleaned_text = self._clean_text(text)
|
| 308 |
+
|
| 309 |
+
if len(cleaned_text) > self.min_chunk_length:
|
| 310 |
+
pages_text.append((cleaned_text, page_num))
|
| 311 |
+
successful_pages += 1
|
| 312 |
+
logger.info(f"✅ Page {page_num}/{total_pages} OK ({len(cleaned_text)} chars)")
|
| 313 |
+
else:
|
| 314 |
+
logger.warning(f"⚠️ Page {page_num}/{total_pages} - Texte trop court ({len(cleaned_text)} chars)")
|
| 315 |
+
else:
|
| 316 |
+
logger.warning(f"⚠️ Page {page_num}/{total_pages} - Aucun texte détecté")
|
| 317 |
+
|
| 318 |
+
except Exception as e:
|
| 319 |
+
logger.error(f"❌ Erreur page {page_num}: {e}")
|
| 320 |
+
continue
|
| 321 |
+
|
| 322 |
+
if not pages_text:
|
| 323 |
+
raise ValueError(f"❌ Aucun texte extrait par OCR sur {total_pages} pages")
|
| 324 |
+
|
| 325 |
+
success_rate = (successful_pages / total_pages) * 100
|
| 326 |
+
logger.info(f"✅ OCR terminé: {successful_pages}/{total_pages} pages extraites ({success_rate:.1f}%)")
|
| 327 |
+
|
| 328 |
+
if success_rate < 50:
|
| 329 |
+
logger.warning("⚠️ Taux de réussite OCR faible (<50%). Vérifiez la qualité du PDF scanné.")
|
| 330 |
+
|
| 331 |
+
return pages_text
|
| 332 |
+
|
| 333 |
+
except Exception as e:
|
| 334 |
+
logger.error(f"❌ Erreur OCR: {e}")
|
| 335 |
+
raise
|
| 336 |
+
|
| 337 |
+
def get_pdf_page_count(self, pdf_path: str) -> int:
|
| 338 |
+
"""Compte rapidement le nombre de pages d'un PDF sans l'extraire"""
|
| 339 |
+
try:
|
| 340 |
+
import pdfplumber
|
| 341 |
+
with pdfplumber.open(pdf_path) as pdf:
|
| 342 |
+
return len(pdf.pages)
|
| 343 |
+
except Exception as e:
|
| 344 |
+
logger.error(f"Erreur comptage pages: {e}")
|
| 345 |
+
return 0
|
| 346 |
+
|
| 347 |
+
def estimate_processing_time(self, pdf_path: str, max_pages: Optional[int] = None) -> Dict:
|
| 348 |
+
"""Estime le temps de traitement d'un PDF
|
| 349 |
+
|
| 350 |
+
Returns:
|
| 351 |
+
Dict avec 'total_pages', 'pages_to_process', 'estimated_time_seconds', 'estimated_time_formatted'
|
| 352 |
+
"""
|
| 353 |
+
total_pages = self.get_pdf_page_count(pdf_path)
|
| 354 |
+
|
| 355 |
+
if total_pages == 0:
|
| 356 |
+
return {
|
| 357 |
+
'total_pages': 0,
|
| 358 |
+
'pages_to_process': 0,
|
| 359 |
+
'estimated_time_seconds': 0,
|
| 360 |
+
'estimated_time_formatted': "Impossible d'estimer"
|
| 361 |
+
}
|
| 362 |
+
|
| 363 |
+
pages_to_process = min(max_pages, total_pages) if max_pages else total_pages
|
| 364 |
+
|
| 365 |
+
# Temps estimés (en secondes par page)
|
| 366 |
+
# Ces valeurs sont approximatives et peuvent varier selon la machine
|
| 367 |
+
time_per_page_normal = 0.7 # Extraction pdfplumber
|
| 368 |
+
time_per_page_ocr = 3.5 # OCR Tesseract
|
| 369 |
+
time_per_chunk_embedding = 0.02 # Création des embeddings
|
| 370 |
+
|
| 371 |
+
# Estimation du nombre de chunks (approximatif: ~2-3 chunks par page)
|
| 372 |
+
estimated_chunks = pages_to_process * 2.5
|
| 373 |
+
|
| 374 |
+
# On ne sait pas encore si c'est un PDF scanné, donc on estime pour le cas normal
|
| 375 |
+
# et on indique que ça peut être plus long si OCR
|
| 376 |
+
extraction_time = pages_to_process * time_per_page_normal
|
| 377 |
+
embedding_time = estimated_chunks * time_per_chunk_embedding
|
| 378 |
+
index_time = 2 # Temps de construction de l'index FAISS
|
| 379 |
+
|
| 380 |
+
total_time_normal = extraction_time + embedding_time + index_time
|
| 381 |
+
total_time_ocr = (pages_to_process * time_per_page_ocr) + embedding_time + index_time
|
| 382 |
+
|
| 383 |
+
# Formater le temps
|
| 384 |
+
def format_time(seconds):
|
| 385 |
+
if seconds < 60:
|
| 386 |
+
return f"{int(seconds)}s"
|
| 387 |
+
elif seconds < 3600:
|
| 388 |
+
minutes = int(seconds // 60)
|
| 389 |
+
secs = int(seconds % 60)
|
| 390 |
+
return f"{minutes}min {secs}s"
|
| 391 |
+
else:
|
| 392 |
+
hours = int(seconds // 3600)
|
| 393 |
+
minutes = int((seconds % 3600) // 60)
|
| 394 |
+
return f"{hours}h {minutes}min"
|
| 395 |
+
|
| 396 |
+
return {
|
| 397 |
+
'total_pages': total_pages,
|
| 398 |
+
'pages_to_process': pages_to_process,
|
| 399 |
+
'estimated_time_normal': total_time_normal,
|
| 400 |
+
'estimated_time_ocr': total_time_ocr,
|
| 401 |
+
'estimated_time_formatted_normal': format_time(total_time_normal),
|
| 402 |
+
'estimated_time_formatted_ocr': format_time(total_time_ocr),
|
| 403 |
+
'estimated_chunks': int(estimated_chunks)
|
| 404 |
+
}
|
| 405 |
+
|
| 406 |
+
def extract_text_from_pdf(self, pdf_path: str, force_ocr: bool = False, max_pages: Optional[int] = None) -> List[Tuple[str, int]]:
|
| 407 |
+
"""Extraction avec fallback OCR automatique + diagnostics
|
| 408 |
+
|
| 409 |
+
Args:
|
| 410 |
+
pdf_path: Chemin vers le PDF
|
| 411 |
+
force_ocr: Force l'utilisation de l'OCR
|
| 412 |
+
max_pages: Nombre maximum de pages à traiter (None = toutes les pages)
|
| 413 |
+
"""
|
| 414 |
+
pdf_path = Path(pdf_path)
|
| 415 |
+
|
| 416 |
+
if not pdf_path.exists():
|
| 417 |
+
raise FileNotFoundError(f"PDF non trouvé: {pdf_path}")
|
| 418 |
+
|
| 419 |
+
logger.info(f"📖 Extraction du PDF: {pdf_path.name}")
|
| 420 |
+
if max_pages:
|
| 421 |
+
logger.info(f"⚠️ Limitation: {max_pages} premières pages seulement")
|
| 422 |
+
|
| 423 |
+
# Si OCR forcé
|
| 424 |
+
if force_ocr:
|
| 425 |
+
logger.info("🔧 Mode OCR forcé activé")
|
| 426 |
+
if self.ocr_available:
|
| 427 |
+
return self._extract_with_ocr(str(pdf_path), max_pages)
|
| 428 |
+
else:
|
| 429 |
+
raise RuntimeError("OCR forcé mais non disponible")
|
| 430 |
+
|
| 431 |
+
try:
|
| 432 |
+
import pdfplumber
|
| 433 |
+
except ImportError:
|
| 434 |
+
raise ImportError("pip install pdfplumber")
|
| 435 |
+
|
| 436 |
+
pages_text = []
|
| 437 |
+
total_pages = 0
|
| 438 |
+
|
| 439 |
+
# Tentative d'extraction normale
|
| 440 |
+
try:
|
| 441 |
+
logger.info("🔄 Extraction normale avec pdfplumber...")
|
| 442 |
+
with pdfplumber.open(pdf_path) as pdf:
|
| 443 |
+
total_pages = len(pdf.pages)
|
| 444 |
+
|
| 445 |
+
# Limiter le nombre de pages si max_pages est défini
|
| 446 |
+
pages_to_process = min(max_pages, total_pages) if max_pages else total_pages
|
| 447 |
+
|
| 448 |
+
logger.info(f"📄 {total_pages} pages détectées - Traitement de {pages_to_process} pages")
|
| 449 |
+
|
| 450 |
+
for page_num, page in enumerate(pdf.pages[:pages_to_process], 1):
|
| 451 |
+
try:
|
| 452 |
+
text = page.extract_text()
|
| 453 |
+
|
| 454 |
+
if text and text.strip():
|
| 455 |
+
cleaned_text = self._clean_text(text)
|
| 456 |
+
|
| 457 |
+
if len(cleaned_text) > self.min_chunk_length:
|
| 458 |
+
pages_text.append((cleaned_text, page_num))
|
| 459 |
+
|
| 460 |
+
except Exception as e:
|
| 461 |
+
logger.warning(f"⚠️ Erreur page {page_num}: {e}")
|
| 462 |
+
continue
|
| 463 |
+
|
| 464 |
+
except Exception as e:
|
| 465 |
+
logger.error(f"❌ Erreur extraction PDF: {e}")
|
| 466 |
+
raise
|
| 467 |
+
|
| 468 |
+
# Diagnostic automatique si activé
|
| 469 |
+
if self.auto_detect_scanned:
|
| 470 |
+
is_scanned = self._is_scanned_pdf(pages_text, total_pages)
|
| 471 |
+
|
| 472 |
+
if is_scanned:
|
| 473 |
+
logger.warning(f"🔍 PDF scanné détecté")
|
| 474 |
+
|
| 475 |
+
if self.use_ocr and self.ocr_available:
|
| 476 |
+
logger.info("🚀 Basculement vers OCR Tesseract...")
|
| 477 |
+
try:
|
| 478 |
+
pages_text = self._extract_with_ocr(str(pdf_path), max_pages)
|
| 479 |
+
except Exception as e:
|
| 480 |
+
logger.error(f"❌ Échec OCR: {e}")
|
| 481 |
+
if not pages_text:
|
| 482 |
+
raise ValueError("Impossible d'extraire le texte du PDF scanné")
|
| 483 |
+
else:
|
| 484 |
+
if not self.ocr_available:
|
| 485 |
+
logger.error("❌ PDF scanné mais OCR non disponible")
|
| 486 |
+
if not pages_text:
|
| 487 |
+
raise ValueError("PDF scanné détecté mais OCR non disponible")
|
| 488 |
+
elif not self.use_ocr:
|
| 489 |
+
logger.error("❌ PDF scanné mais OCR désactivé")
|
| 490 |
+
if not pages_text:
|
| 491 |
+
raise ValueError("PDF scanné détecté - activez use_ocr=True")
|
| 492 |
+
else:
|
| 493 |
+
logger.info(f"✅ PDF normal - Extraction réussie ({len(pages_text)}/{total_pages} pages)")
|
| 494 |
+
else:
|
| 495 |
+
logger.info(f"✅ Extraction terminée ({len(pages_text)}/{total_pages} pages) - Détection auto désactivée")
|
| 496 |
+
|
| 497 |
+
if not pages_text:
|
| 498 |
+
raise ValueError("Aucun texte extrait du PDF")
|
| 499 |
+
|
| 500 |
+
return pages_text
|
| 501 |
+
|
| 502 |
+
def _clean_text(self, text: str) -> str:
|
| 503 |
+
"""Nettoyage du texte"""
|
| 504 |
+
if not text:
|
| 505 |
+
return ""
|
| 506 |
+
|
| 507 |
+
text = re.sub(r'[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x84\x86-\x9f]', '', text)
|
| 508 |
+
text = re.sub(r'\n\s*\n\s*\n+', '\n\n', text)
|
| 509 |
+
text = re.sub(r'[ \t]+', ' ', text)
|
| 510 |
+
text = re.sub(r' ?\n ?', '\n', text)
|
| 511 |
+
text = re.sub(r'-\n([a-zàâäéèêëïîôùûü])', r'\1', text, flags=re.IGNORECASE)
|
| 512 |
+
text = re.sub(r'\s+([.,;:!?])', r'\1', text)
|
| 513 |
+
|
| 514 |
+
return text.strip()
|
| 515 |
+
|
| 516 |
+
def create_chunks(self, pages_text: List[Tuple[str, int]], source_file: str = "") -> List[DocumentChunk]:
|
| 517 |
+
logger.info("📝 Création des chunks...")
|
| 518 |
+
chunks = []
|
| 519 |
+
chunk_index = 0
|
| 520 |
+
|
| 521 |
+
for page_text, page_num in pages_text:
|
| 522 |
+
text_length = len(page_text)
|
| 523 |
+
|
| 524 |
+
if text_length <= self.chunk_size:
|
| 525 |
+
if text_length >= self.min_chunk_length:
|
| 526 |
+
chunk = DocumentChunk(
|
| 527 |
+
text=page_text,
|
| 528 |
+
page_number=page_num,
|
| 529 |
+
chunk_index=chunk_index,
|
| 530 |
+
start_char=0,
|
| 531 |
+
end_char=text_length,
|
| 532 |
+
source_file=source_file
|
| 533 |
+
)
|
| 534 |
+
chunks.append(chunk)
|
| 535 |
+
chunk_index += 1
|
| 536 |
+
continue
|
| 537 |
+
|
| 538 |
+
start = 0
|
| 539 |
+
while start < text_length:
|
| 540 |
+
end = min(start + self.chunk_size, text_length)
|
| 541 |
+
|
| 542 |
+
if end < text_length:
|
| 543 |
+
best_cut = self._find_best_cut_point(page_text, start, end)
|
| 544 |
+
if best_cut > start:
|
| 545 |
+
end = best_cut
|
| 546 |
+
|
| 547 |
+
chunk_text = page_text[start:end].strip()
|
| 548 |
+
|
| 549 |
+
if len(chunk_text) >= self.min_chunk_length:
|
| 550 |
+
chunk = DocumentChunk(
|
| 551 |
+
text=chunk_text,
|
| 552 |
+
page_number=page_num,
|
| 553 |
+
chunk_index=chunk_index,
|
| 554 |
+
start_char=start,
|
| 555 |
+
end_char=end,
|
| 556 |
+
source_file=source_file
|
| 557 |
+
)
|
| 558 |
+
chunks.append(chunk)
|
| 559 |
+
chunk_index += 1
|
| 560 |
+
|
| 561 |
+
next_start = end - self.chunk_overlap
|
| 562 |
+
if next_start <= start + 50:
|
| 563 |
+
next_start = end
|
| 564 |
+
start = next_start
|
| 565 |
+
|
| 566 |
+
logger.info(f"✅ {len(chunks)} chunks créés")
|
| 567 |
+
|
| 568 |
+
if chunks:
|
| 569 |
+
total_words = sum(chunk.word_count for chunk in chunks)
|
| 570 |
+
avg_words = total_words / len(chunks)
|
| 571 |
+
logger.info(f"📊 Moyenne: {avg_words:.1f} mots/chunk, Total: {total_words} mots")
|
| 572 |
+
|
| 573 |
+
return chunks
|
| 574 |
+
|
| 575 |
+
def _find_best_cut_point(self, text: str, start: int, end: int) -> int:
|
| 576 |
+
search_window = 100
|
| 577 |
+
search_start = max(start, end - search_window)
|
| 578 |
+
search_end = min(len(text), end + search_window // 2)
|
| 579 |
+
search_text = text[search_start:search_end]
|
| 580 |
+
|
| 581 |
+
cut_patterns = [
|
| 582 |
+
r'\n\n',
|
| 583 |
+
r'\. [A-ZÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ]',
|
| 584 |
+
r'\?\s+[A-ZÀÁÂÃÄÅÆÇÈÉÊËÌ��ÎÏÐÑÒÓÔÕÖ]',
|
| 585 |
+
r'!\s+[A-ZÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ]',
|
| 586 |
+
r'\n',
|
| 587 |
+
r'[;:]\s+',
|
| 588 |
+
r',\s+',
|
| 589 |
+
r'\s+'
|
| 590 |
+
]
|
| 591 |
+
|
| 592 |
+
best_pos = end
|
| 593 |
+
for pattern in cut_patterns:
|
| 594 |
+
matches = list(re.finditer(pattern, search_text))
|
| 595 |
+
if matches:
|
| 596 |
+
target_pos = end - search_start
|
| 597 |
+
closest_match = min(matches, key=lambda m: abs(m.start() - target_pos))
|
| 598 |
+
candidate_pos = search_start + closest_match.end()
|
| 599 |
+
if start + 200 <= candidate_pos <= end + 50:
|
| 600 |
+
best_pos = candidate_pos
|
| 601 |
+
break
|
| 602 |
+
|
| 603 |
+
return min(best_pos, len(text))
|
| 604 |
+
|
| 605 |
+
def create_embeddings(self, chunks: List[DocumentChunk]) -> np.ndarray:
|
| 606 |
+
self._initialize_model()
|
| 607 |
+
logger.info(f"🧮 Création des embeddings pour {len(chunks)} chunks...")
|
| 608 |
+
|
| 609 |
+
if not chunks:
|
| 610 |
+
raise ValueError("Aucun chunk à traiter")
|
| 611 |
+
|
| 612 |
+
texts = [chunk.text for chunk in chunks]
|
| 613 |
+
|
| 614 |
+
# PRÉFIXE POUR MODÈLE E5 (requis pour performances optimales)
|
| 615 |
+
if "e5" in self.model_name.lower():
|
| 616 |
+
texts = [f"passage: {text}" for text in texts]
|
| 617 |
+
logger.info("✅ Préfixe E5 ajouté aux textes (passage:)")
|
| 618 |
+
|
| 619 |
+
try:
|
| 620 |
+
batch_size = 32
|
| 621 |
+
all_embeddings = []
|
| 622 |
+
|
| 623 |
+
for i in range(0, len(texts), batch_size):
|
| 624 |
+
batch = texts[i:i + batch_size]
|
| 625 |
+
|
| 626 |
+
batch_embeddings = self.embedding_model.encode(
|
| 627 |
+
batch,
|
| 628 |
+
convert_to_numpy=True,
|
| 629 |
+
show_progress_bar=False,
|
| 630 |
+
normalize_embeddings=True
|
| 631 |
+
)
|
| 632 |
+
all_embeddings.append(batch_embeddings)
|
| 633 |
+
|
| 634 |
+
embeddings = np.vstack(all_embeddings)
|
| 635 |
+
logger.info(f"✅ Embeddings créés: {embeddings.shape}")
|
| 636 |
+
return embeddings
|
| 637 |
+
|
| 638 |
+
except Exception as e:
|
| 639 |
+
logger.error(f"❌ Erreur création embeddings: {e}")
|
| 640 |
+
raise
|
| 641 |
+
|
| 642 |
+
def build_faiss_index(self, embeddings: np.ndarray) -> faiss.Index:
|
| 643 |
+
logger.info("🔨 Construction de l'index FAISS...")
|
| 644 |
+
n_vectors, dim = embeddings.shape
|
| 645 |
+
|
| 646 |
+
if n_vectors < 1000:
|
| 647 |
+
index = faiss.IndexFlatIP(dim)
|
| 648 |
+
else:
|
| 649 |
+
nlist = min(100, n_vectors // 10)
|
| 650 |
+
quantizer = faiss.IndexFlatIP(dim)
|
| 651 |
+
index = faiss.IndexIVFFlat(quantizer, dim, nlist)
|
| 652 |
+
index.train(embeddings)
|
| 653 |
+
|
| 654 |
+
index.add(embeddings)
|
| 655 |
+
logger.info(f"✅ Index construit avec {index.ntotal} vecteurs")
|
| 656 |
+
return index
|
| 657 |
+
|
| 658 |
+
def process_pdf(self, pdf_path: str, save_automatically: bool = True) -> Dict:
|
| 659 |
+
start_time = time.time()
|
| 660 |
+
logger.info(f"🚀 Début du traitement: {Path(pdf_path).name}")
|
| 661 |
+
|
| 662 |
+
try:
|
| 663 |
+
pages_text = self.extract_text_from_pdf(pdf_path)
|
| 664 |
+
source_file = Path(pdf_path).name
|
| 665 |
+
self.chunks = self.create_chunks(pages_text, source_file)
|
| 666 |
+
embeddings = self.create_embeddings(self.chunks)
|
| 667 |
+
self.index = self.build_faiss_index(embeddings)
|
| 668 |
+
|
| 669 |
+
if save_automatically:
|
| 670 |
+
self.save_index()
|
| 671 |
+
|
| 672 |
+
processing_time = time.time() - start_time
|
| 673 |
+
|
| 674 |
+
report = {
|
| 675 |
+
'success': True,
|
| 676 |
+
'pdf_path': str(pdf_path),
|
| 677 |
+
'pages_processed': len(pages_text),
|
| 678 |
+
'chunks_created': len(self.chunks),
|
| 679 |
+
'embedding_dimension': self.embedding_dim,
|
| 680 |
+
'processing_time': processing_time,
|
| 681 |
+
'avg_chunk_words': np.mean([chunk.word_count for chunk in self.chunks]) if self.chunks else 0,
|
| 682 |
+
'total_words': sum(chunk.word_count for chunk in self.chunks)
|
| 683 |
+
}
|
| 684 |
+
|
| 685 |
+
logger.info(f"✅ Traitement terminé en {processing_time:.1f}s")
|
| 686 |
+
logger.info(f"📊 {report['pages_processed']} pages → {report['chunks_created']} chunks")
|
| 687 |
+
|
| 688 |
+
return report
|
| 689 |
+
|
| 690 |
+
except Exception as e:
|
| 691 |
+
logger.error(f"❌ Erreur traitement: {e}")
|
| 692 |
+
raise
|
| 693 |
+
|
| 694 |
+
def search(self, query: str, top_k: int = 5, score_threshold: float = 0.1) -> List[Tuple[DocumentChunk, float]]:
|
| 695 |
+
if self.index is None:
|
| 696 |
+
raise ValueError("Index non initialisé")
|
| 697 |
+
if not query.strip():
|
| 698 |
+
return []
|
| 699 |
+
|
| 700 |
+
self._initialize_model()
|
| 701 |
+
|
| 702 |
+
try:
|
| 703 |
+
# PRÉFIXE POUR MODÈLE E5 (requis pour queries)
|
| 704 |
+
search_query = query
|
| 705 |
+
if "e5" in self.model_name.lower():
|
| 706 |
+
search_query = f"query: {query}"
|
| 707 |
+
logger.info(f"🔍 Recherche avec préfixe E5: query: {query}")
|
| 708 |
+
|
| 709 |
+
query_embedding = self.embedding_model.encode(
|
| 710 |
+
[search_query],
|
| 711 |
+
convert_to_numpy=True,
|
| 712 |
+
normalize_embeddings=True
|
| 713 |
+
)
|
| 714 |
+
|
| 715 |
+
search_k = min(top_k * 2, len(self.chunks), self.index.ntotal)
|
| 716 |
+
scores, indices = self.index.search(query_embedding, search_k)
|
| 717 |
+
|
| 718 |
+
results = []
|
| 719 |
+
for score, idx in zip(scores[0], indices[0]):
|
| 720 |
+
if idx >= 0 and idx < len(self.chunks) and score >= score_threshold:
|
| 721 |
+
results.append((self.chunks[idx], float(score)))
|
| 722 |
+
|
| 723 |
+
return results[:top_k]
|
| 724 |
+
|
| 725 |
+
except Exception as e:
|
| 726 |
+
logger.error(f"❌ Erreur recherche: {e}")
|
| 727 |
+
return []
|
| 728 |
+
|
| 729 |
+
def save_index(self, save_dir: Optional[str] = None) -> Path:
|
| 730 |
+
if self.index is None:
|
| 731 |
+
raise ValueError("Aucun index à sauvegarder")
|
| 732 |
+
|
| 733 |
+
save_path = Path(save_dir) if save_dir else self.output_dir
|
| 734 |
+
save_path.mkdir(exist_ok=True)
|
| 735 |
+
|
| 736 |
+
index_file = save_path / "faiss_index.bin"
|
| 737 |
+
faiss.write_index(self.index, str(index_file))
|
| 738 |
+
|
| 739 |
+
metadata = {
|
| 740 |
+
'chunks': self.chunks,
|
| 741 |
+
'model_name': self.model_name,
|
| 742 |
+
'embedding_dim': self.embedding_dim,
|
| 743 |
+
'chunk_size': self.chunk_size,
|
| 744 |
+
'chunk_overlap': self.chunk_overlap,
|
| 745 |
+
'min_chunk_length': self.min_chunk_length,
|
| 746 |
+
'total_chunks': len(self.chunks),
|
| 747 |
+
'creation_time': time.time(),
|
| 748 |
+
'version': '2.2'
|
| 749 |
+
}
|
| 750 |
+
|
| 751 |
+
metadata_file = save_path / "metadata.pkl"
|
| 752 |
+
with open(metadata_file, 'wb') as f:
|
| 753 |
+
pickle.dump(metadata, f)
|
| 754 |
+
|
| 755 |
+
logger.info(f"💾 Sauvegarde terminée: {save_path}")
|
| 756 |
+
return save_path
|
| 757 |
+
|
| 758 |
+
def load_index(self, save_dir: str) -> Dict:
|
| 759 |
+
save_path = Path(save_dir)
|
| 760 |
+
|
| 761 |
+
if not save_path.exists():
|
| 762 |
+
raise FileNotFoundError(f"Dossier introuvable: {save_path}")
|
| 763 |
+
|
| 764 |
+
self.index = faiss.read_index(str(save_path / "faiss_index.bin"))
|
| 765 |
+
|
| 766 |
+
with open(save_path / "metadata.pkl", 'rb') as f:
|
| 767 |
+
metadata = pickle.load(f)
|
| 768 |
+
|
| 769 |
+
self.chunks = metadata['chunks']
|
| 770 |
+
self.model_name = metadata['model_name']
|
| 771 |
+
self.embedding_dim = metadata['embedding_dim']
|
| 772 |
+
self.chunk_size = metadata['chunk_size']
|
| 773 |
+
self.chunk_overlap = metadata['chunk_overlap']
|
| 774 |
+
self.min_chunk_length = metadata.get('min_chunk_length', 50)
|
| 775 |
+
|
| 776 |
+
logger.info(f"📂 Index chargé: {len(self.chunks)} chunks")
|
| 777 |
+
|
| 778 |
+
return {
|
| 779 |
+
'chunks_loaded': len(self.chunks),
|
| 780 |
+
'model_name': self.model_name,
|
| 781 |
+
'embedding_dim': self.embedding_dim
|
| 782 |
+
}
|
| 783 |
+
|
| 784 |
+
|
| 785 |
+
if __name__ == "__main__":
|
| 786 |
+
print("=" * 60)
|
| 787 |
+
print("Test Vectorizer avec OCR + Modèle Cross-Lingual")
|
| 788 |
+
print("=" * 60)
|
| 789 |
+
|
| 790 |
+
try:
|
| 791 |
+
vectorizer = OptimalPDFVectorizer(
|
| 792 |
+
use_ocr=True,
|
| 793 |
+
ocr_language='fra',
|
| 794 |
+
ocr_dpi=300,
|
| 795 |
+
ocr_preprocessing=True
|
| 796 |
+
)
|
| 797 |
+
print(f"\nVectorizer initialisé")
|
| 798 |
+
print(f" - Modèle: {vectorizer.model_name}")
|
| 799 |
+
print(f" - OCR disponible: {vectorizer.ocr_available}")
|
| 800 |
+
print(f" - Langue: {vectorizer.ocr_language}")
|
| 801 |
+
print(f" - DPI: {vectorizer.ocr_dpi}")
|
| 802 |
+
print(f" - Prétraitement: {vectorizer.ocr_preprocessing}")
|
| 803 |
+
print("\n✅ Test réussi - Recherche cross-linguale FR↔EN activée!")
|
| 804 |
+
|
| 805 |
+
except Exception as e:
|
| 806 |
+
print(f"\nErreur: {e}")
|
| 807 |
+
import traceback
|
| 808 |
+
traceback.print_exc()
|