Spaces:
Runtime error
refactor: retirer 165 Mo de dependances mortes et dix scripts a usage unique
Browse filesDEPENDANCES
scikit-learn et joblib : ZERO occurrence dans tout le depot depuis la
suppression du classifieur ML. Avec scipy qu'ils entrainent, ils pesaient
165 Mo dans l'image pour rien. Le classement de domaine est fait par des
regles depuis legal_domain_classifier.py.
SCRIPTS
Sept scripts a usage unique, sans argparse, avec `law_id = 1` code en dur et
aucun garde `__main__` — donc executables au simple import. Quatre d'entre eux
etaient DESTRUCTIFS sans confirmation : force_clean_extract, reextract_
constitution, reextract_pdfplumber effacaient les articles de la loi 1.
reprocess_law.py portait en plus un file_id code en dur ; il figurait dans un
plan de suppression precedent et n'avait pas ete supprime.
Trois scripts de maintenance des categories (add_category_icons,
update_category_icons, cleanup_categories) sont perimes par la migration 007,
qui possede desormais les 14 domaines avec leurs icones et le verifie par
assertion. Les executer se battrait contre elle.
reset_database.py gardait un mot de passe en clair et pointait sur un port
(5432) et une base (jurix_db) qui n'existent pas — il ne pouvait de toute facon
plus se connecter. Il passe par Settings.
CODE MORT
- app/api/dependencies/ : paquet entier que rien n'importe. Toutes les routes
prennent get_db depuis app.core.database.
- init_db() et drop_db() : appelaient create_all/drop_all, aucun appelant. Le
schema appartient a Alembic ; deux sources de verite pour une meme structure
finissent toujours par diverger.
- split_text_into_pages, SearchService.invalidate_cache (jumelle exacte de
invalidate_search_cache au message de journal pres), et les quatre
clear_*_cache : aucun appelant, ni en production ni dans les tests.
- 65 imports inutilises. Le seul conserve est `import pytesseract` dans
ocr_service : il echoue tout de suite si la dependance manque, avant une
conversion de PDF qui coute plusieurs secondes par page.
CE QU'ON GARDE, ET POURQUOI : le sous-systeme OCR — l'ingestion passe par
LlamaParse, mais un fonds juridique contient des PDF scannes et le Dockerfile
installe deja tesseract ; scripts/eval/ — l'outil qui mesure la qualite du RAG ;
et les personas, sur decision explicite.
Verification : 747 tests, ruff sans reproche.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
- app/api/dependencies/__init__.py +0 -5
- app/api/routes/admin.py +1 -2
- app/api/routes/analytics.py +1 -1
- app/api/routes/batch_upload.py +2 -3
- app/api/routes/language.py +1 -1
- app/api/routes/laws.py +3 -8
- app/api/routes/ocr.py +0 -2
- app/api/routes/personas.py +2 -5
- app/api/routes/rag.py +1 -1
- app/api/routes/search.py +0 -1
- app/api/routes/upload.py +0 -1
- app/core/config.py +0 -1
- app/core/database.py +4 -34
- app/core/dependencies.py +4 -34
- app/models/conversation.py +1 -1
- app/models/law.py +0 -3
- app/models/user.py +0 -1
- app/schemas/persona.py +1 -2
- app/schemas/search.py +1 -1
- app/services/category_service.py +0 -1
- app/services/file_upload_service.py +0 -1
- app/services/gemini_service.py +0 -6
- app/services/llama_parse_service.py +0 -3
- app/services/ocr_service.py +7 -4
- app/services/persona_service.py +2 -4
- app/services/rag_service.py +0 -1
- app/services/search_service.py +3 -23
- app/tasks/process_law.py +1 -3
- app/utils/ocr_utils.py +1 -28
- requirements.txt +5 -4
- scripts/debug_extraction.py +0 -49
- scripts/force_clean_extract.py +0 -66
- scripts/maintenance/add_category_icons.py +0 -69
- scripts/maintenance/cleanup_categories.py +0 -40
- scripts/maintenance/update_category_icons.py +0 -57
- scripts/reextract_constitution.py +0 -115
- scripts/reextract_pdfplumber.py +0 -101
- scripts/reprocess_law.py +0 -20
- scripts/reset_database.py +15 -2
- scripts/show_articles.py +0 -29
- scripts/test_extraction.py +0 -89
|
@@ -1,5 +0,0 @@
|
|
| 1 |
-
"""API dependencies."""
|
| 2 |
-
|
| 3 |
-
from app.core.database import get_db
|
| 4 |
-
|
| 5 |
-
__all__ = ["get_db"]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@@ -15,10 +15,9 @@ Date: 2026-01-11
|
|
| 15 |
import logging
|
| 16 |
import platform
|
| 17 |
from datetime import datetime
|
| 18 |
-
from typing import
|
| 19 |
|
| 20 |
from fastapi import APIRouter, Depends, HTTPException, status
|
| 21 |
-
from pydantic import BaseModel, EmailStr, Field
|
| 22 |
from sqlalchemy import or_, select
|
| 23 |
from sqlalchemy.ext.asyncio import AsyncSession
|
| 24 |
|
|
|
|
| 15 |
import logging
|
| 16 |
import platform
|
| 17 |
from datetime import datetime
|
| 18 |
+
from typing import Dict, List
|
| 19 |
|
| 20 |
from fastapi import APIRouter, Depends, HTTPException, status
|
|
|
|
| 21 |
from sqlalchemy import or_, select
|
| 22 |
from sqlalchemy.ext.asyncio import AsyncSession
|
| 23 |
|
|
@@ -13,7 +13,7 @@ Date: 2026-01-11
|
|
| 13 |
|
| 14 |
import logging
|
| 15 |
from datetime import datetime, timedelta
|
| 16 |
-
from typing import Dict
|
| 17 |
|
| 18 |
from fastapi import APIRouter, Depends, Query
|
| 19 |
from sqlalchemy import func, select, text
|
|
|
|
| 13 |
|
| 14 |
import logging
|
| 15 |
from datetime import datetime, timedelta
|
| 16 |
+
from typing import Dict
|
| 17 |
|
| 18 |
from fastapi import APIRouter, Depends, Query
|
| 19 |
from sqlalchemy import func, select, text
|
|
@@ -9,10 +9,9 @@ Handles:
|
|
| 9 |
|
| 10 |
from fastapi import APIRouter, UploadFile, File, WebSocket, WebSocketDisconnect, HTTPException, Depends
|
| 11 |
from sqlalchemy.ext.asyncio import AsyncSession
|
| 12 |
-
from sqlalchemy import select
|
| 13 |
-
from typing import List
|
| 14 |
import asyncio
|
| 15 |
-
import json
|
| 16 |
import uuid
|
| 17 |
import logging
|
| 18 |
from datetime import datetime, timezone
|
|
|
|
| 9 |
|
| 10 |
from fastapi import APIRouter, UploadFile, File, WebSocket, WebSocketDisconnect, HTTPException, Depends
|
| 11 |
from sqlalchemy.ext.asyncio import AsyncSession
|
| 12 |
+
from sqlalchemy import select
|
| 13 |
+
from typing import List
|
| 14 |
import asyncio
|
|
|
|
| 15 |
import uuid
|
| 16 |
import logging
|
| 17 |
from datetime import datetime, timezone
|
|
@@ -11,7 +11,7 @@ Usage:
|
|
| 11 |
-d '{"text": "Article 1. La présente loi..."}'
|
| 12 |
"""
|
| 13 |
|
| 14 |
-
from typing import Dict
|
| 15 |
import logging
|
| 16 |
|
| 17 |
from fastapi import APIRouter, Depends, HTTPException, status
|
|
|
|
| 11 |
-d '{"text": "Article 1. La présente loi..."}'
|
| 12 |
"""
|
| 13 |
|
| 14 |
+
from typing import Dict
|
| 15 |
import logging
|
| 16 |
|
| 17 |
from fastapi import APIRouter, Depends, HTTPException, status
|
|
@@ -18,8 +18,8 @@ import time
|
|
| 18 |
from pathlib import Path
|
| 19 |
from typing import List, Optional, cast
|
| 20 |
|
| 21 |
-
from fastapi import APIRouter,
|
| 22 |
-
from fastapi.responses import FileResponse
|
| 23 |
from pydantic import BaseModel
|
| 24 |
from sqlalchemy import select
|
| 25 |
from sqlalchemy.ext.asyncio import AsyncSession
|
|
@@ -28,14 +28,13 @@ from sqlalchemy.orm import selectinload
|
|
| 28 |
from app.core.auth import get_current_admin_user
|
| 29 |
from app.models.user import User
|
| 30 |
from app.core.database import get_db, AsyncSessionLocal
|
| 31 |
-
from app.models.law import
|
| 32 |
from app.schemas.law import (
|
| 33 |
LawDetailResponse,
|
| 34 |
LawCreate,
|
| 35 |
LawResponse,
|
| 36 |
LawUpdate,
|
| 37 |
)
|
| 38 |
-
from app.services.file_upload_service import get_upload_service
|
| 39 |
from app.utils.file_utils import resolve_upload_path
|
| 40 |
from app.services.search_service import invalidate_search_cache
|
| 41 |
from app.tasks.process_law import delete_from_search_index
|
|
@@ -307,7 +306,6 @@ async def get_law_pdf_data(
|
|
| 307 |
if not law.file_id:
|
| 308 |
raise HTTPException(status_code=404, detail="No source file found for this law")
|
| 309 |
|
| 310 |
-
from app.services.file_upload_service import get_upload_service
|
| 311 |
file_path = _law_file_path(law)
|
| 312 |
|
| 313 |
# Read file and encode to Base64
|
|
@@ -349,7 +347,6 @@ async def get_law_pdf_stream(
|
|
| 349 |
if not law.file_id:
|
| 350 |
raise HTTPException(status_code=404, detail="No source file found for this law")
|
| 351 |
|
| 352 |
-
from app.services.file_upload_service import get_upload_service
|
| 353 |
file_path = _law_file_path(law)
|
| 354 |
|
| 355 |
# Read file content
|
|
@@ -391,7 +388,6 @@ async def get_law_pdf_info(
|
|
| 391 |
if not law.file_id:
|
| 392 |
raise HTTPException(status_code=404, detail="No source file found for this law")
|
| 393 |
|
| 394 |
-
from app.services.file_upload_service import get_upload_service
|
| 395 |
file_path = _law_file_path(law)
|
| 396 |
|
| 397 |
# Get page count
|
|
@@ -442,7 +438,6 @@ async def get_law_pdf_page_image(
|
|
| 442 |
if not law.file_id:
|
| 443 |
raise HTTPException(status_code=404, detail="No source file found for this law")
|
| 444 |
|
| 445 |
-
from app.services.file_upload_service import get_upload_service
|
| 446 |
file_path = _law_file_path(law)
|
| 447 |
|
| 448 |
# Convert page to image using Poppler
|
|
|
|
| 18 |
from pathlib import Path
|
| 19 |
from typing import List, Optional, cast
|
| 20 |
|
| 21 |
+
from fastapi import APIRouter, Depends, HTTPException, Query, status
|
| 22 |
+
from fastapi.responses import FileResponse
|
| 23 |
from pydantic import BaseModel
|
| 24 |
from sqlalchemy import select
|
| 25 |
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
| 28 |
from app.core.auth import get_current_admin_user
|
| 29 |
from app.models.user import User
|
| 30 |
from app.core.database import get_db, AsyncSessionLocal
|
| 31 |
+
from app.models.law import Law
|
| 32 |
from app.schemas.law import (
|
| 33 |
LawDetailResponse,
|
| 34 |
LawCreate,
|
| 35 |
LawResponse,
|
| 36 |
LawUpdate,
|
| 37 |
)
|
|
|
|
| 38 |
from app.utils.file_utils import resolve_upload_path
|
| 39 |
from app.services.search_service import invalidate_search_cache
|
| 40 |
from app.tasks.process_law import delete_from_search_index
|
|
|
|
| 306 |
if not law.file_id:
|
| 307 |
raise HTTPException(status_code=404, detail="No source file found for this law")
|
| 308 |
|
|
|
|
| 309 |
file_path = _law_file_path(law)
|
| 310 |
|
| 311 |
# Read file and encode to Base64
|
|
|
|
| 347 |
if not law.file_id:
|
| 348 |
raise HTTPException(status_code=404, detail="No source file found for this law")
|
| 349 |
|
|
|
|
| 350 |
file_path = _law_file_path(law)
|
| 351 |
|
| 352 |
# Read file content
|
|
|
|
| 388 |
if not law.file_id:
|
| 389 |
raise HTTPException(status_code=404, detail="No source file found for this law")
|
| 390 |
|
|
|
|
| 391 |
file_path = _law_file_path(law)
|
| 392 |
|
| 393 |
# Get page count
|
|
|
|
| 438 |
if not law.file_id:
|
| 439 |
raise HTTPException(status_code=404, detail="No source file found for this law")
|
| 440 |
|
|
|
|
| 441 |
file_path = _law_file_path(law)
|
| 442 |
|
| 443 |
# Convert page to image using Poppler
|
|
@@ -11,10 +11,8 @@ Date: 2026-01-11
|
|
| 11 |
"""
|
| 12 |
|
| 13 |
import logging
|
| 14 |
-
from pathlib import Path
|
| 15 |
|
| 16 |
from fastapi import APIRouter, Depends, HTTPException, status
|
| 17 |
-
from fastapi.responses import JSONResponse
|
| 18 |
|
| 19 |
from app.schemas.ocr import (
|
| 20 |
OCRRequest,
|
|
|
|
| 11 |
"""
|
| 12 |
|
| 13 |
import logging
|
|
|
|
| 14 |
|
| 15 |
from fastapi import APIRouter, Depends, HTTPException, status
|
|
|
|
| 16 |
|
| 17 |
from app.schemas.ocr import (
|
| 18 |
OCRRequest,
|
|
@@ -21,7 +21,7 @@ Version: 2.1.0
|
|
| 21 |
"""
|
| 22 |
|
| 23 |
import logging
|
| 24 |
-
from typing import List,
|
| 25 |
from datetime import date
|
| 26 |
from fastapi import APIRouter, Depends, HTTPException, status, Query, Path
|
| 27 |
from sqlalchemy.ext.asyncio import AsyncSession
|
|
@@ -31,8 +31,7 @@ from app.services.persona_service import (
|
|
| 31 |
PersonaService,
|
| 32 |
InvalidPersonaError,
|
| 33 |
MessageNotFoundError,
|
| 34 |
-
FeedbackAlreadyExistsError
|
| 35 |
-
PersonaServiceError
|
| 36 |
)
|
| 37 |
from app.schemas.persona import (
|
| 38 |
PersonaInfo,
|
|
@@ -42,10 +41,8 @@ from app.schemas.persona import (
|
|
| 42 |
FeedbackStats,
|
| 43 |
EngagementMetricsResponse,
|
| 44 |
PopularQuestionsResponse,
|
| 45 |
-
PopularQuestion,
|
| 46 |
PersonaComparisonResponse,
|
| 47 |
TrendsResponse,
|
| 48 |
-
TrendPoint,
|
| 49 |
UsageBreakdownResponse,
|
| 50 |
HealthCheckResponse,
|
| 51 |
ErrorResponse
|
|
|
|
| 21 |
"""
|
| 22 |
|
| 23 |
import logging
|
| 24 |
+
from typing import List, Optional
|
| 25 |
from datetime import date
|
| 26 |
from fastapi import APIRouter, Depends, HTTPException, status, Query, Path
|
| 27 |
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
| 31 |
PersonaService,
|
| 32 |
InvalidPersonaError,
|
| 33 |
MessageNotFoundError,
|
| 34 |
+
FeedbackAlreadyExistsError
|
|
|
|
| 35 |
)
|
| 36 |
from app.schemas.persona import (
|
| 37 |
PersonaInfo,
|
|
|
|
| 41 |
FeedbackStats,
|
| 42 |
EngagementMetricsResponse,
|
| 43 |
PopularQuestionsResponse,
|
|
|
|
| 44 |
PersonaComparisonResponse,
|
| 45 |
TrendsResponse,
|
|
|
|
| 46 |
UsageBreakdownResponse,
|
| 47 |
HealthCheckResponse,
|
| 48 |
ErrorResponse
|
|
@@ -13,7 +13,7 @@ import logging
|
|
| 13 |
|
| 14 |
from fastapi import APIRouter, Depends, HTTPException, status
|
| 15 |
from fastapi.responses import StreamingResponse
|
| 16 |
-
from sqlalchemy import
|
| 17 |
from sqlalchemy.ext.asyncio import AsyncSession
|
| 18 |
from sqlalchemy.orm import joinedload
|
| 19 |
|
|
|
|
| 13 |
|
| 14 |
from fastapi import APIRouter, Depends, HTTPException, status
|
| 15 |
from fastapi.responses import StreamingResponse
|
| 16 |
+
from sqlalchemy import select
|
| 17 |
from sqlalchemy.ext.asyncio import AsyncSession
|
| 18 |
from sqlalchemy.orm import joinedload
|
| 19 |
|
|
@@ -12,7 +12,6 @@ Version: 1.0.0
|
|
| 12 |
|
| 13 |
import logging
|
| 14 |
import time
|
| 15 |
-
from typing import Optional
|
| 16 |
|
| 17 |
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException, status
|
| 18 |
from sqlalchemy import text
|
|
|
|
| 12 |
|
| 13 |
import logging
|
| 14 |
import time
|
|
|
|
| 15 |
|
| 16 |
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException, status
|
| 17 |
from sqlalchemy import text
|
|
@@ -16,7 +16,6 @@ from pathlib import Path
|
|
| 16 |
from typing import Dict
|
| 17 |
|
| 18 |
from fastapi import Depends, APIRouter, File, HTTPException, UploadFile, status
|
| 19 |
-
from fastapi.responses import JSONResponse
|
| 20 |
|
| 21 |
from app.schemas.file_upload import FileUploadResult, UploadServiceHealth
|
| 22 |
from app.services.file_upload_service import FileUploadError, FileUploadService
|
|
|
|
| 16 |
from typing import Dict
|
| 17 |
|
| 18 |
from fastapi import Depends, APIRouter, File, HTTPException, UploadFile, status
|
|
|
|
| 19 |
|
| 20 |
from app.schemas.file_upload import FileUploadResult, UploadServiceHealth
|
| 21 |
from app.services.file_upload_service import FileUploadError, FileUploadService
|
|
@@ -1,7 +1,6 @@
|
|
| 1 |
"""Configuration application - Toutes les variables d'environnement."""
|
| 2 |
|
| 3 |
from pydantic_settings import BaseSettings
|
| 4 |
-
from typing import Optional
|
| 5 |
|
| 6 |
|
| 7 |
class Settings(BaseSettings):
|
|
|
|
| 1 |
"""Configuration application - Toutes les variables d'environnement."""
|
| 2 |
|
| 3 |
from pydantic_settings import BaseSettings
|
|
|
|
| 4 |
|
| 5 |
|
| 6 |
class Settings(BaseSettings):
|
|
@@ -125,42 +125,12 @@ async def get_db() -> AsyncGenerator[AsyncSession, None]:
|
|
| 125 |
logger.debug("🗑️ Session DB fermée")
|
| 126 |
|
| 127 |
|
| 128 |
-
async def init_db() -> None:
|
| 129 |
-
"""
|
| 130 |
-
Initialise les tables de la base de données.
|
| 131 |
-
|
| 132 |
-
Crée toutes les tables définies dans les modèles SQLAlchemy
|
| 133 |
-
si elles n'existent pas déjà.
|
| 134 |
-
|
| 135 |
-
Note:
|
| 136 |
-
En production, utiliser Alembic pour les migrations.
|
| 137 |
-
Cette fonction est principalement pour les tests.
|
| 138 |
-
|
| 139 |
-
Example:
|
| 140 |
-
>>> # Dans les tests
|
| 141 |
-
>>> await init_db()
|
| 142 |
-
"""
|
| 143 |
-
async with engine.begin() as conn:
|
| 144 |
-
logger.info("🚀 Initialisation des tables de la base de données...")
|
| 145 |
-
await conn.run_sync(Base.metadata.create_all)
|
| 146 |
-
logger.info("✅ Tables créées avec succès")
|
| 147 |
|
| 148 |
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
⚠️ ATTENTION: Cette fonction est destructive!
|
| 154 |
-
Utilisée uniquement pour les tests.
|
| 155 |
-
|
| 156 |
-
Example:
|
| 157 |
-
>>> # Nettoyage après tests
|
| 158 |
-
>>> await drop_db()
|
| 159 |
-
"""
|
| 160 |
-
async with engine.begin() as conn:
|
| 161 |
-
logger.warning("⚠️ Suppression de toutes les tables...")
|
| 162 |
-
await conn.run_sync(Base.metadata.drop_all)
|
| 163 |
-
logger.info("✅ Tables supprimées")
|
| 164 |
|
| 165 |
|
| 166 |
async def close_db() -> None:
|
|
|
|
| 125 |
logger.debug("🗑️ Session DB fermée")
|
| 126 |
|
| 127 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 128 |
|
| 129 |
|
| 130 |
+
# init_db() et drop_db() ont ete retirees : elles appelaient
|
| 131 |
+
# Base.metadata.create_all/drop_all, et n'etaient appelees par personne. Le
|
| 132 |
+
# schema appartient a Alembic — deux sources de verite pour une meme structure
|
| 133 |
+
# finissent toujours par diverger.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 134 |
|
| 135 |
|
| 136 |
async def close_db() -> None:
|
|
@@ -15,9 +15,8 @@ Usage dans routes:
|
|
| 15 |
import logging
|
| 16 |
from functools import lru_cache
|
| 17 |
|
| 18 |
-
from app.services.embedding_service import
|
| 19 |
from app.services.language_detector import LanguageDetector
|
| 20 |
-
from app.services.search_service import SearchService
|
| 21 |
|
| 22 |
logger = logging.getLogger(__name__)
|
| 23 |
|
|
@@ -45,44 +44,15 @@ def get_language_detector() -> LanguageDetector:
|
|
| 45 |
return LanguageDetector()
|
| 46 |
|
| 47 |
|
| 48 |
-
def clear_detector_cache():
|
| 49 |
-
"""
|
| 50 |
-
Efface le cache du detector (force rechargement).
|
| 51 |
-
|
| 52 |
-
Utile pour:
|
| 53 |
-
- Tests (isolation entre tests)
|
| 54 |
-
- Mise à jour des modèles
|
| 55 |
-
- Debugging
|
| 56 |
-
|
| 57 |
-
Example:
|
| 58 |
-
>>> clear_detector_cache()
|
| 59 |
-
>>> detector = get_language_detector() # Nouvelle instance
|
| 60 |
-
"""
|
| 61 |
-
get_language_detector.cache_clear()
|
| 62 |
-
logger.info("🗑️ Cache LanguageDetector effacé")
|
| 63 |
|
| 64 |
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
Utile pour:
|
| 70 |
-
- Tests (isolation entre tests)
|
| 71 |
-
- Mise à jour des modèles
|
| 72 |
-
- Debugging
|
| 73 |
-
|
| 74 |
-
Example:
|
| 75 |
-
>>> clear_embedding_service_cache()
|
| 76 |
-
>>> service = get_embedding_service() # Nouvelle instance
|
| 77 |
-
"""
|
| 78 |
-
get_embedding_service.cache_clear()
|
| 79 |
-
logger.info("🗑️ Cache EmbeddingService effacé")
|
| 80 |
|
| 81 |
|
| 82 |
# Exports for dependency injection
|
| 83 |
__all__ = [
|
| 84 |
"get_language_detector",
|
| 85 |
"get_embedding_service",
|
| 86 |
-
"clear_detector_cache",
|
| 87 |
-
"clear_embedding_service_cache",
|
| 88 |
]
|
|
|
|
| 15 |
import logging
|
| 16 |
from functools import lru_cache
|
| 17 |
|
| 18 |
+
from app.services.embedding_service import get_embedding_service
|
| 19 |
from app.services.language_detector import LanguageDetector
|
|
|
|
| 20 |
|
| 21 |
logger = logging.getLogger(__name__)
|
| 22 |
|
|
|
|
| 44 |
return LanguageDetector()
|
| 45 |
|
| 46 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 47 |
|
| 48 |
|
| 49 |
+
# clear_detector_cache() et clear_embedding_service_cache() ont ete retirees :
|
| 50 |
+
# aucun appelant, ni en production ni dans les tests. Les caches @lru_cache
|
| 51 |
+
# qu'elles vidaient vivent le temps du processus.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
|
| 53 |
|
| 54 |
# Exports for dependency injection
|
| 55 |
__all__ = [
|
| 56 |
"get_language_detector",
|
| 57 |
"get_embedding_service",
|
|
|
|
|
|
|
| 58 |
]
|
|
@@ -4,7 +4,7 @@ Database models for RAG conversation tracking.
|
|
| 4 |
Stores conversation sessions and individual messages with sources and metadata.
|
| 5 |
"""
|
| 6 |
|
| 7 |
-
from datetime import
|
| 8 |
|
| 9 |
from sqlalchemy import (
|
| 10 |
JSON,
|
|
|
|
| 4 |
Stores conversation sessions and individual messages with sources and metadata.
|
| 5 |
"""
|
| 6 |
|
| 7 |
+
from datetime import datetime
|
| 8 |
|
| 9 |
from sqlalchemy import (
|
| 10 |
JSON,
|
|
@@ -14,8 +14,6 @@ Features v2.1:
|
|
| 14 |
Author: JuriX Team
|
| 15 |
"""
|
| 16 |
|
| 17 |
-
from datetime import datetime, date
|
| 18 |
-
from typing import List, Optional
|
| 19 |
|
| 20 |
from sqlalchemy import (
|
| 21 |
text,
|
|
@@ -29,7 +27,6 @@ from sqlalchemy import (
|
|
| 29 |
DateTime,
|
| 30 |
ForeignKey,
|
| 31 |
Index,
|
| 32 |
-
JSON,
|
| 33 |
)
|
| 34 |
from sqlalchemy.dialects.postgresql import ARRAY
|
| 35 |
from sqlalchemy.orm import relationship
|
|
|
|
| 14 |
Author: JuriX Team
|
| 15 |
"""
|
| 16 |
|
|
|
|
|
|
|
| 17 |
|
| 18 |
from sqlalchemy import (
|
| 19 |
text,
|
|
|
|
| 27 |
DateTime,
|
| 28 |
ForeignKey,
|
| 29 |
Index,
|
|
|
|
| 30 |
)
|
| 31 |
from sqlalchemy.dialects.postgresql import ARRAY
|
| 32 |
from sqlalchemy.orm import relationship
|
|
@@ -8,7 +8,6 @@ Date: 2026-01-12
|
|
| 8 |
"""
|
| 9 |
|
| 10 |
from datetime import datetime
|
| 11 |
-
from typing import Optional
|
| 12 |
|
| 13 |
from sqlalchemy import Boolean, Column, DateTime, Integer, String
|
| 14 |
from sqlalchemy.orm import relationship
|
|
|
|
| 8 |
"""
|
| 9 |
|
| 10 |
from datetime import datetime
|
|
|
|
| 11 |
|
| 12 |
from sqlalchemy import Boolean, Column, DateTime, Integer, String
|
| 13 |
from sqlalchemy.orm import relationship
|
|
@@ -4,9 +4,8 @@ Pydantic schemas for PersonaService API.
|
|
| 4 |
Request/response models for persona management and analytics endpoints.
|
| 5 |
"""
|
| 6 |
|
| 7 |
-
from datetime import date, datetime
|
| 8 |
from typing import Dict, List, Optional, Any
|
| 9 |
-
from pydantic import BaseModel, Field
|
| 10 |
|
| 11 |
|
| 12 |
# ============================================================================
|
|
|
|
| 4 |
Request/response models for persona management and analytics endpoints.
|
| 5 |
"""
|
| 6 |
|
|
|
|
| 7 |
from typing import Dict, List, Optional, Any
|
| 8 |
+
from pydantic import BaseModel, Field
|
| 9 |
|
| 10 |
|
| 11 |
# ============================================================================
|
|
@@ -15,7 +15,7 @@ Date: 2026-01-10
|
|
| 15 |
"""
|
| 16 |
|
| 17 |
from datetime import date
|
| 18 |
-
from typing import Literal,
|
| 19 |
|
| 20 |
from pydantic import BaseModel, Field, field_validator
|
| 21 |
|
|
|
|
| 15 |
"""
|
| 16 |
|
| 17 |
from datetime import date
|
| 18 |
+
from typing import Literal, Dict, List, Optional
|
| 19 |
|
| 20 |
from pydantic import BaseModel, Field, field_validator
|
| 21 |
|
|
@@ -18,7 +18,6 @@ from datetime import datetime
|
|
| 18 |
from sqlalchemy import select, func, and_
|
| 19 |
from sqlalchemy.ext.asyncio import AsyncSession
|
| 20 |
from sqlalchemy.exc import IntegrityError
|
| 21 |
-
from sqlalchemy.orm import joinedload
|
| 22 |
|
| 23 |
from app.models.law import Category, Law
|
| 24 |
from app.schemas.law import CategoryCreate, CategoryUpdate, CategoryResponse, CategoryStats
|
|
|
|
| 18 |
from sqlalchemy import select, func, and_
|
| 19 |
from sqlalchemy.ext.asyncio import AsyncSession
|
| 20 |
from sqlalchemy.exc import IntegrityError
|
|
|
|
| 21 |
|
| 22 |
from app.models.law import Category, Law
|
| 23 |
from app.schemas.law import CategoryCreate, CategoryUpdate, CategoryResponse, CategoryStats
|
|
@@ -34,7 +34,6 @@ from app.utils.file_utils import (
|
|
| 34 |
ensure_storage_directory,
|
| 35 |
generate_unique_filename,
|
| 36 |
get_file_hash,
|
| 37 |
-
get_file_size_mb,
|
| 38 |
get_mime_type,
|
| 39 |
is_file_size_valid,
|
| 40 |
is_valid_docx,
|
|
|
|
| 34 |
ensure_storage_directory,
|
| 35 |
generate_unique_filename,
|
| 36 |
get_file_hash,
|
|
|
|
| 37 |
get_mime_type,
|
| 38 |
is_file_size_valid,
|
| 39 |
is_valid_docx,
|
|
@@ -442,9 +442,3 @@ def get_gemini_service() -> GeminiService:
|
|
| 442 |
return _gemini_service
|
| 443 |
|
| 444 |
|
| 445 |
-
def clear_gemini_service_cache():
|
| 446 |
-
"""Clear the singleton instance (for testing)."""
|
| 447 |
-
global _gemini_service
|
| 448 |
-
_gemini_service = None
|
| 449 |
-
get_gemini_service.cache_clear()
|
| 450 |
-
logger.info("🗑️ GeminiService cache cleared")
|
|
|
|
| 442 |
return _gemini_service
|
| 443 |
|
| 444 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@@ -592,6 +592,3 @@ def get_llama_parse_service() -> LlamaParseService:
|
|
| 592 |
return LlamaParseService()
|
| 593 |
|
| 594 |
|
| 595 |
-
def clear_llama_parse_service_cache() -> None:
|
| 596 |
-
"""Force la recreation du singleton (tests, rotation de cle)."""
|
| 597 |
-
get_llama_parse_service.cache_clear()
|
|
|
|
| 592 |
return LlamaParseService()
|
| 593 |
|
| 594 |
|
|
|
|
|
|
|
|
|
|
@@ -19,7 +19,7 @@ import logging
|
|
| 19 |
import time
|
| 20 |
from concurrent.futures import ThreadPoolExecutor, TimeoutError as FuturesTimeoutError
|
| 21 |
from pathlib import Path
|
| 22 |
-
from typing import Any, Dict,
|
| 23 |
|
| 24 |
from app.core.config import settings
|
| 25 |
from app.schemas.ocr import (
|
|
@@ -31,7 +31,6 @@ from app.utils.ocr_utils import (
|
|
| 31 |
assess_text_quality,
|
| 32 |
clean_ocr_text,
|
| 33 |
convert_pdf_to_images,
|
| 34 |
-
estimate_ocr_time,
|
| 35 |
has_embedded_text,
|
| 36 |
has_images,
|
| 37 |
merge_text_blocks,
|
|
@@ -330,7 +329,12 @@ class OCRService:
|
|
| 330 |
logger.info(f"🔍 OCR en cours: {pdf_path.name} ({language}, {dpi} DPI)")
|
| 331 |
|
| 332 |
try:
|
| 333 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 334 |
|
| 335 |
# 1. Convertir PDF en images
|
| 336 |
images = convert_pdf_to_images(pdf_path, dpi=dpi)
|
|
@@ -453,7 +457,6 @@ class OCRService:
|
|
| 453 |
|
| 454 |
# Vérifier Poppler (pdf2image)
|
| 455 |
try:
|
| 456 |
-
from pdf2image import pdfinfo_from_path
|
| 457 |
|
| 458 |
# Test simple
|
| 459 |
status["poppler"] = {"available": True}
|
|
|
|
| 19 |
import time
|
| 20 |
from concurrent.futures import ThreadPoolExecutor, TimeoutError as FuturesTimeoutError
|
| 21 |
from pathlib import Path
|
| 22 |
+
from typing import Any, Dict, Optional
|
| 23 |
|
| 24 |
from app.core.config import settings
|
| 25 |
from app.schemas.ocr import (
|
|
|
|
| 31 |
assess_text_quality,
|
| 32 |
clean_ocr_text,
|
| 33 |
convert_pdf_to_images,
|
|
|
|
| 34 |
has_embedded_text,
|
| 35 |
has_images,
|
| 36 |
merge_text_blocks,
|
|
|
|
| 329 |
logger.info(f"🔍 OCR en cours: {pdf_path.name} ({language}, {dpi} DPI)")
|
| 330 |
|
| 331 |
try:
|
| 332 |
+
# Import volontaire, jamais utilise directement : il echoue tout de
|
| 333 |
+
# suite si pytesseract manque, AVANT la conversion du PDF en images
|
| 334 |
+
# qui coute plusieurs secondes par page. Sans lui, l'absence de la
|
| 335 |
+
# dependance se manifesterait beaucoup plus loin et beaucoup plus
|
| 336 |
+
# cher.
|
| 337 |
+
import pytesseract # noqa: F401
|
| 338 |
|
| 339 |
# 1. Convertir PDF en images
|
| 340 |
images = convert_pdf_to_images(pdf_path, dpi=dpi)
|
|
|
|
| 457 |
|
| 458 |
# Vérifier Poppler (pdf2image)
|
| 459 |
try:
|
|
|
|
| 460 |
|
| 461 |
# Test simple
|
| 462 |
status["poppler"] = {"available": True}
|
|
@@ -14,18 +14,16 @@ Version: 2.1.0
|
|
| 14 |
"""
|
| 15 |
|
| 16 |
import logging
|
| 17 |
-
from typing import Dict, List, Optional, Any
|
| 18 |
from datetime import datetime, date, timedelta
|
| 19 |
|
| 20 |
-
from sqlalchemy import select, func, and_,
|
| 21 |
from sqlalchemy.ext.asyncio import AsyncSession
|
| 22 |
-
from sqlalchemy.exc import IntegrityError
|
| 23 |
from sqlalchemy.orm import selectinload
|
| 24 |
|
| 25 |
from app.models.conversation import (
|
| 26 |
Conversation, Message, PersonaStat, MessageFeedback, PersonaInteraction
|
| 27 |
)
|
| 28 |
-
from app.services.prompts import SYSTEM_PROMPTS
|
| 29 |
|
| 30 |
# Configure logger
|
| 31 |
logger = logging.getLogger(__name__)
|
|
|
|
| 14 |
"""
|
| 15 |
|
| 16 |
import logging
|
| 17 |
+
from typing import Dict, List, Optional, Any
|
| 18 |
from datetime import datetime, date, timedelta
|
| 19 |
|
| 20 |
+
from sqlalchemy import select, func, and_, desc
|
| 21 |
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
| 22 |
from sqlalchemy.orm import selectinload
|
| 23 |
|
| 24 |
from app.models.conversation import (
|
| 25 |
Conversation, Message, PersonaStat, MessageFeedback, PersonaInteraction
|
| 26 |
)
|
|
|
|
| 27 |
|
| 28 |
# Configure logger
|
| 29 |
logger = logging.getLogger(__name__)
|
|
@@ -39,7 +39,6 @@ from app.services.gemini_service import (
|
|
| 39 |
from app.services.prompts import (
|
| 40 |
CONTEXT_TEMPLATE,
|
| 41 |
NO_RESULTS_MESSAGE,
|
| 42 |
-
SYSTEM_PROMPTS,
|
| 43 |
build_context_string,
|
| 44 |
format_conversation_history,
|
| 45 |
get_system_prompt,
|
|
|
|
| 39 |
from app.services.prompts import (
|
| 40 |
CONTEXT_TEMPLATE,
|
| 41 |
NO_RESULTS_MESSAGE,
|
|
|
|
| 42 |
build_context_string,
|
| 43 |
format_conversation_history,
|
| 44 |
get_system_prompt,
|
|
@@ -16,17 +16,12 @@ Author: JuriX Team
|
|
| 16 |
Version: 3.0.0 (PostgreSQL natif)
|
| 17 |
"""
|
| 18 |
|
| 19 |
-
import asyncio
|
| 20 |
-
import hashlib
|
| 21 |
-
import json
|
| 22 |
import logging
|
| 23 |
import time
|
| 24 |
from typing import Any, Dict, List, Optional
|
| 25 |
|
| 26 |
-
import numpy as np
|
| 27 |
from sqlalchemy import func, select, text
|
| 28 |
from sqlalchemy.ext.asyncio import AsyncSession
|
| 29 |
-
from sqlalchemy.orm import joinedload
|
| 30 |
|
| 31 |
from app.core.config import settings
|
| 32 |
from app.models.law import Article, Category, Law
|
|
@@ -38,7 +33,6 @@ from app.schemas.search import (
|
|
| 38 |
SearchRequest,
|
| 39 |
SearchResponse,
|
| 40 |
SearchResult,
|
| 41 |
-
SearchStats,
|
| 42 |
)
|
| 43 |
from app.services.embedding_service import EmbeddingService, get_embedding_service
|
| 44 |
from app.services.reranker import rerank_chunks
|
|
@@ -56,7 +50,6 @@ from app.services.postgres_search_service import (
|
|
| 56 |
search_titles_trgm_pg,
|
| 57 |
update_law_search_vector,
|
| 58 |
remove_law_search_index,
|
| 59 |
-
cleanup_expired_cache,
|
| 60 |
_make_cache_key,
|
| 61 |
)
|
| 62 |
|
|
@@ -923,22 +916,9 @@ class SearchService:
|
|
| 923 |
logger.error(f"❌ Reindexing failed: {e}")
|
| 924 |
raise IndexingError(f"Échec réindexation: {e}") from e
|
| 925 |
|
| 926 |
-
|
| 927 |
-
|
| 928 |
-
|
| 929 |
-
|
| 930 |
-
Returns:
|
| 931 |
-
Nombre d'entrées supprimées
|
| 932 |
-
"""
|
| 933 |
-
try:
|
| 934 |
-
result = await self.db.execute(text("DELETE FROM query_cache"))
|
| 935 |
-
deleted = getattr(result, "rowcount", 0)
|
| 936 |
-
await self.db.commit()
|
| 937 |
-
logger.info(f"🗑️ PG cache invalidated: {deleted} entries deleted")
|
| 938 |
-
return deleted
|
| 939 |
-
except Exception as e:
|
| 940 |
-
logger.warning(f"⚠️ Cache invalidation error: {e}")
|
| 941 |
-
return 0
|
| 942 |
|
| 943 |
# ==================== PRIVATE HELPERS ====================
|
| 944 |
|
|
|
|
| 16 |
Version: 3.0.0 (PostgreSQL natif)
|
| 17 |
"""
|
| 18 |
|
|
|
|
|
|
|
|
|
|
| 19 |
import logging
|
| 20 |
import time
|
| 21 |
from typing import Any, Dict, List, Optional
|
| 22 |
|
|
|
|
| 23 |
from sqlalchemy import func, select, text
|
| 24 |
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
| 25 |
|
| 26 |
from app.core.config import settings
|
| 27 |
from app.models.law import Article, Category, Law
|
|
|
|
| 33 |
SearchRequest,
|
| 34 |
SearchResponse,
|
| 35 |
SearchResult,
|
|
|
|
| 36 |
)
|
| 37 |
from app.services.embedding_service import EmbeddingService, get_embedding_service
|
| 38 |
from app.services.reranker import rerank_chunks
|
|
|
|
| 50 |
search_titles_trgm_pg,
|
| 51 |
update_law_search_vector,
|
| 52 |
remove_law_search_index,
|
|
|
|
| 53 |
_make_cache_key,
|
| 54 |
)
|
| 55 |
|
|
|
|
| 916 |
logger.error(f"❌ Reindexing failed: {e}")
|
| 917 |
raise IndexingError(f"Échec réindexation: {e}") from e
|
| 918 |
|
| 919 |
+
# SearchService.invalidate_cache() a ete retiree : aucun appelant, et son
|
| 920 |
+
# corps etait le jumeau exact de `invalidate_search_cache` plus bas dans ce
|
| 921 |
+
# meme fichier, au message de journal pres.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 922 |
|
| 923 |
# ==================== PRIVATE HELPERS ====================
|
| 924 |
|
|
@@ -21,10 +21,9 @@ Version: 3.0.0 (PostgreSQL natif)
|
|
| 21 |
import asyncio
|
| 22 |
import logging
|
| 23 |
import time
|
| 24 |
-
from pathlib import Path
|
| 25 |
from typing import Any, Dict
|
| 26 |
|
| 27 |
-
from sqlalchemy import
|
| 28 |
from sqlalchemy.exc import DataError
|
| 29 |
from sqlalchemy.ext.asyncio import AsyncSession
|
| 30 |
|
|
@@ -313,7 +312,6 @@ def _extract_pdf_text(file_path) -> tuple:
|
|
| 313 |
Raises:
|
| 314 |
LlamaParseError: extraction impossible
|
| 315 |
"""
|
| 316 |
-
import asyncio
|
| 317 |
|
| 318 |
from app.services.llama_parse_service import (
|
| 319 |
LlamaParseError,
|
|
|
|
| 21 |
import asyncio
|
| 22 |
import logging
|
| 23 |
import time
|
|
|
|
| 24 |
from typing import Any, Dict
|
| 25 |
|
| 26 |
+
from sqlalchemy import text
|
| 27 |
from sqlalchemy.exc import DataError
|
| 28 |
from sqlalchemy.ext.asyncio import AsyncSession
|
| 29 |
|
|
|
|
| 312 |
Raises:
|
| 313 |
LlamaParseError: extraction impossible
|
| 314 |
"""
|
|
|
|
| 315 |
|
| 316 |
from app.services.llama_parse_service import (
|
| 317 |
LlamaParseError,
|
|
@@ -424,31 +424,4 @@ def estimate_ocr_time(page_count: int, dpi: int = 300) -> int:
|
|
| 424 |
return max(estimated_seconds, 1)
|
| 425 |
|
| 426 |
|
| 427 |
-
|
| 428 |
-
"""
|
| 429 |
-
Split OCR text back into pages if markers present.
|
| 430 |
-
|
| 431 |
-
Args:
|
| 432 |
-
text: Full OCR text
|
| 433 |
-
page_markers: List of page marker patterns
|
| 434 |
-
|
| 435 |
-
Returns:
|
| 436 |
-
List of text per page
|
| 437 |
-
|
| 438 |
-
Example:
|
| 439 |
-
>>> text = "Page 1 text\\n--- PAGE BREAK ---\\nPage 2 text"
|
| 440 |
-
>>> split_text_into_pages(text, ["--- PAGE BREAK ---"])
|
| 441 |
-
['Page 1 text', 'Page 2 text']
|
| 442 |
-
"""
|
| 443 |
-
if not page_markers:
|
| 444 |
-
# Default markers
|
| 445 |
-
page_markers = ["\f", "--- PAGE BREAK ---", "\n\n\n"]
|
| 446 |
-
|
| 447 |
-
pages = [text]
|
| 448 |
-
|
| 449 |
-
for marker in page_markers:
|
| 450 |
-
if marker in text:
|
| 451 |
-
pages = text.split(marker)
|
| 452 |
-
break
|
| 453 |
-
|
| 454 |
-
return [page.strip() for page in pages if page.strip()]
|
|
|
|
| 424 |
return max(estimated_seconds, 1)
|
| 425 |
|
| 426 |
|
| 427 |
+
# split_text_into_pages() a ete retiree : definie, documentee, jamais appelee.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@@ -36,10 +36,11 @@ pdf2image>=1.16.3,<2.0.0
|
|
| 36 |
numpy>=1.26.0,<2.0.0
|
| 37 |
langdetect>=1.0.9,<2.0.0
|
| 38 |
fasttext-wheel>=0.9.2
|
| 39 |
-
|
| 40 |
-
#
|
| 41 |
-
|
| 42 |
-
|
|
|
|
| 43 |
|
| 44 |
# ── LLM — Gemini API ─────────────────────────────────────────────────────────
|
| 45 |
# SDK google-genai (nouveau). L'ancien google-generativeai n'est plus utilisé :
|
|
|
|
| 36 |
numpy>=1.26.0,<2.0.0
|
| 37 |
langdetect>=1.0.9,<2.0.0
|
| 38 |
fasttext-wheel>=0.9.2
|
| 39 |
+
# scikit-learn et joblib ont ete retires : zero occurrence dans tout le
|
| 40 |
+
# depot depuis la suppression du classifieur ML (app/services/document_classifier.py
|
| 41 |
+
# et scripts/train_classifier.py). Avec scipy qu'ils entrainent, ils pesaient
|
| 42 |
+
# 165 Mo dans l'image pour rien. Le classement de domaine est desormais
|
| 43 |
+
# fait par des regles, dans app/services/legal_domain_classifier.py.
|
| 44 |
|
| 45 |
# ── LLM — Gemini API ─────────────────────────────────────────────────────────
|
| 46 |
# SDK google-genai (nouveau). L'ancien google-generativeai n'est plus utilisé :
|
|
@@ -1,49 +0,0 @@
|
|
| 1 |
-
"""
|
| 2 |
-
Debug script to analyze raw text and article splitting - output to file.
|
| 3 |
-
"""
|
| 4 |
-
import sys
|
| 5 |
-
import os
|
| 6 |
-
sys.path.insert(0, '.')
|
| 7 |
-
os.environ.setdefault('PYTHONPATH', '.')
|
| 8 |
-
|
| 9 |
-
from sqlalchemy import create_engine, text
|
| 10 |
-
from app.core.config import settings
|
| 11 |
-
|
| 12 |
-
# Get raw text from DB
|
| 13 |
-
sync_url = settings.DATABASE_URL.replace('+asyncpg', '')
|
| 14 |
-
engine = create_engine(sync_url)
|
| 15 |
-
|
| 16 |
-
with engine.connect() as conn:
|
| 17 |
-
result = conn.execute(text("SELECT content FROM laws WHERE id = 1"))
|
| 18 |
-
row = result.fetchone()
|
| 19 |
-
raw_text = row[0] if row else ""
|
| 20 |
-
|
| 21 |
-
# Write analysis to file
|
| 22 |
-
with open('debug_output.txt', 'w', encoding='utf-8') as f:
|
| 23 |
-
f.write(f"Total raw text length: {len(raw_text)} chars\n\n")
|
| 24 |
-
|
| 25 |
-
import re
|
| 26 |
-
|
| 27 |
-
# Find ALL article positions
|
| 28 |
-
article_pattern = re.compile(r'Article\s+(\d+)\s*[.:]', re.IGNORECASE)
|
| 29 |
-
matches = list(article_pattern.finditer(raw_text))
|
| 30 |
-
|
| 31 |
-
f.write(f"Found {len(matches)} articles in raw text\n\n")
|
| 32 |
-
|
| 33 |
-
for i, match in enumerate(matches[:20]): # First 20 articles
|
| 34 |
-
art_num = match.group(1)
|
| 35 |
-
start = match.start()
|
| 36 |
-
# End is start of next article or +2000 chars
|
| 37 |
-
if i + 1 < len(matches):
|
| 38 |
-
end = matches[i + 1].start()
|
| 39 |
-
else:
|
| 40 |
-
end = start + 2000
|
| 41 |
-
|
| 42 |
-
content = raw_text[start:end]
|
| 43 |
-
|
| 44 |
-
f.write("=" * 70 + "\n")
|
| 45 |
-
f.write(f"ARTICLE {art_num} (pos {start} to {end}, len={end-start})\n")
|
| 46 |
-
f.write("=" * 70 + "\n")
|
| 47 |
-
f.write(content[:1500] + "\n\n")
|
| 48 |
-
|
| 49 |
-
print("Output written to debug_output.txt")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@@ -1,66 +0,0 @@
|
|
| 1 |
-
"""
|
| 2 |
-
Force clean re-extraction with verification.
|
| 3 |
-
"""
|
| 4 |
-
import sys
|
| 5 |
-
sys.path.insert(0, '.')
|
| 6 |
-
|
| 7 |
-
from sqlalchemy import create_engine, text
|
| 8 |
-
from sqlalchemy.orm import sessionmaker
|
| 9 |
-
from app.core.config import settings
|
| 10 |
-
from app.models.law import Article
|
| 11 |
-
from app.utils.text_chunker import extract_articles
|
| 12 |
-
|
| 13 |
-
sync_url = settings.DATABASE_URL.replace('+asyncpg', '')
|
| 14 |
-
engine = create_engine(sync_url)
|
| 15 |
-
Session = sessionmaker(bind=engine)
|
| 16 |
-
|
| 17 |
-
# Get law content
|
| 18 |
-
with engine.connect() as conn:
|
| 19 |
-
row = conn.execute(text("SELECT content FROM laws WHERE id = 1")).fetchone()
|
| 20 |
-
raw_text = row[0]
|
| 21 |
-
|
| 22 |
-
print(f"Raw text length: {len(raw_text)} chars")
|
| 23 |
-
|
| 24 |
-
# Extract articles
|
| 25 |
-
articles = extract_articles(raw_text)
|
| 26 |
-
print(f"Extracted {len(articles)} articles")
|
| 27 |
-
|
| 28 |
-
# Verify Article 9 content is clean
|
| 29 |
-
art9 = [a for a in articles if a['number'] == '9'][0]
|
| 30 |
-
print(f"\nArticle 9 content has <<PAGE? {'<<PAGE' in art9['content']}")
|
| 31 |
-
print(f"Article 9 content length: {len(art9['content'])}")
|
| 32 |
-
|
| 33 |
-
# Delete and re-insert articles
|
| 34 |
-
with Session() as session:
|
| 35 |
-
session.execute(text("DELETE FROM articles WHERE law_id = 1"))
|
| 36 |
-
session.commit()
|
| 37 |
-
print("Deleted old articles")
|
| 38 |
-
|
| 39 |
-
with Session() as session:
|
| 40 |
-
for article_data in articles:
|
| 41 |
-
content = article_data.get('content', '')
|
| 42 |
-
# Double-check cleaning
|
| 43 |
-
import re
|
| 44 |
-
content = re.sub(r'<<PAGE:\s*\d+>>', '', content)
|
| 45 |
-
content = re.sub(r'\n\s*\d+\s*\n', '\n', content) # Remove orphan page numbers
|
| 46 |
-
content = content.strip()
|
| 47 |
-
|
| 48 |
-
article = Article(
|
| 49 |
-
law_id=1,
|
| 50 |
-
number=str(article_data.get('number', '')),
|
| 51 |
-
title=article_data.get('title'),
|
| 52 |
-
section=article_data.get('section'),
|
| 53 |
-
content=content,
|
| 54 |
-
order=article_data.get('position', 0),
|
| 55 |
-
page_number=article_data.get('page_number'),
|
| 56 |
-
)
|
| 57 |
-
session.add(article)
|
| 58 |
-
|
| 59 |
-
session.commit()
|
| 60 |
-
print(f"Saved {len(articles)} articles with cleaned content")
|
| 61 |
-
|
| 62 |
-
# Verify
|
| 63 |
-
with engine.connect() as conn:
|
| 64 |
-
row = conn.execute(text("SELECT content FROM articles WHERE law_id = 1 AND number = '9'")).fetchone()
|
| 65 |
-
print(f"\nVerification - Article 9 in DB has <<PAGE? {'<<PAGE' in row[0] if row else 'N/A'}")
|
| 66 |
-
print(f"Content:\n{row[0][:400] if row else 'N/A'}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@@ -1,69 +0,0 @@
|
|
| 1 |
-
"""
|
| 2 |
-
Script pour ajouter des icônes à toutes les catégories et supprimer "Droit de la Famille"
|
| 3 |
-
"""
|
| 4 |
-
import asyncio
|
| 5 |
-
from sqlalchemy import select, delete
|
| 6 |
-
from app.core.database import AsyncSessionLocal
|
| 7 |
-
from app.models.law import Category
|
| 8 |
-
|
| 9 |
-
# Mapping des catégories avec leurs icônes appropriées
|
| 10 |
-
CATEGORY_ICONS = {
|
| 11 |
-
"Droit Constitutionnel": "⚖️",
|
| 12 |
-
"Droit Civil": "👥",
|
| 13 |
-
"Droit Pénal": "🔒",
|
| 14 |
-
"Droit Commercial": "🏪",
|
| 15 |
-
"Droit du Travail": "👔",
|
| 16 |
-
"Droit Fiscal": "💰",
|
| 17 |
-
"Droit Administratif": "🏛️",
|
| 18 |
-
"Droit OHADA": "🌍",
|
| 19 |
-
"Droit des Affaires": "💼",
|
| 20 |
-
"Procédure Civile": "📋",
|
| 21 |
-
"Procédure Pénale": "⚖️",
|
| 22 |
-
}
|
| 23 |
-
|
| 24 |
-
async def update_category_icons():
|
| 25 |
-
async with AsyncSessionLocal() as db:
|
| 26 |
-
# 1. Supprimer "Droit de la Famille"
|
| 27 |
-
result = await db.execute(
|
| 28 |
-
delete(Category).where(Category.name == "Droit de la Famille")
|
| 29 |
-
)
|
| 30 |
-
if result.rowcount > 0:
|
| 31 |
-
print("✅ 'Droit de la Famille' supprimé")
|
| 32 |
-
|
| 33 |
-
# 2. Récupérer toutes les catégories
|
| 34 |
-
result = await db.execute(select(Category))
|
| 35 |
-
categories = result.scalars().all()
|
| 36 |
-
|
| 37 |
-
# 3. Ajouter les icônes
|
| 38 |
-
updated_count = 0
|
| 39 |
-
for category in categories:
|
| 40 |
-
if category.name in CATEGORY_ICONS:
|
| 41 |
-
icon = CATEGORY_ICONS[category.name]
|
| 42 |
-
|
| 43 |
-
# Mettre à jour la description avec l'icône
|
| 44 |
-
if category.description:
|
| 45 |
-
# Si la description existe déjà, ajouter l'icône au début
|
| 46 |
-
if not category.description.startswith(icon):
|
| 47 |
-
category.description = f"{icon} {category.description}"
|
| 48 |
-
else:
|
| 49 |
-
# Créer une description avec l'icône
|
| 50 |
-
category.description = f"{icon} Lois relatives au {category.name.lower()}"
|
| 51 |
-
|
| 52 |
-
updated_count += 1
|
| 53 |
-
print(f" {icon} {category.name}")
|
| 54 |
-
|
| 55 |
-
await db.commit()
|
| 56 |
-
print(f"\n✅ {updated_count} catégories mises à jour avec des icônes")
|
| 57 |
-
|
| 58 |
-
# 4. Afficher le résultat final
|
| 59 |
-
result = await db.execute(select(Category).order_by(Category.id))
|
| 60 |
-
categories = result.scalars().all()
|
| 61 |
-
|
| 62 |
-
print(f"\n📋 {len(categories)} catégories finales:")
|
| 63 |
-
for cat in categories:
|
| 64 |
-
desc_preview = cat.description[:50] if cat.description else "Pas de description"
|
| 65 |
-
print(f" ID={cat.id}: {cat.name}")
|
| 66 |
-
print(f" {desc_preview}")
|
| 67 |
-
|
| 68 |
-
if __name__ == "__main__":
|
| 69 |
-
asyncio.run(update_category_icons())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@@ -1,40 +0,0 @@
|
|
| 1 |
-
"""
|
| 2 |
-
Script final pour nettoyer toutes les catégories de test
|
| 3 |
-
"""
|
| 4 |
-
import asyncio
|
| 5 |
-
from sqlalchemy import select, delete
|
| 6 |
-
from app.core.database import AsyncSessionLocal
|
| 7 |
-
from app.models.law import Category
|
| 8 |
-
|
| 9 |
-
async def final_cleanup():
|
| 10 |
-
async with AsyncSessionLocal() as db:
|
| 11 |
-
# Liste des catégories de test à supprimer
|
| 12 |
-
test_categories = [
|
| 13 |
-
"Category 1",
|
| 14 |
-
"Category 2",
|
| 15 |
-
"Duplicate Test",
|
| 16 |
-
"Get Test Category",
|
| 17 |
-
"Updated Name",
|
| 18 |
-
"Extra Fields Test"
|
| 19 |
-
]
|
| 20 |
-
|
| 21 |
-
# Supprimer toutes les catégories de test
|
| 22 |
-
result = await db.execute(
|
| 23 |
-
delete(Category).where(Category.name.in_(test_categories))
|
| 24 |
-
)
|
| 25 |
-
deleted_count = result.rowcount
|
| 26 |
-
await db.commit()
|
| 27 |
-
|
| 28 |
-
print(f"✅ {deleted_count} catégories de test supprimées")
|
| 29 |
-
|
| 30 |
-
# Afficher les catégories restantes
|
| 31 |
-
result = await db.execute(select(Category).order_by(Category.id))
|
| 32 |
-
categories = result.scalars().all()
|
| 33 |
-
|
| 34 |
-
print(f"\n📋 {len(categories)} catégories restantes:")
|
| 35 |
-
for cat in categories:
|
| 36 |
-
icon = "⚖️" if cat.name == "Droit Constitutionnel" else "📁"
|
| 37 |
-
print(f" {icon} ID={cat.id}: {cat.name}")
|
| 38 |
-
|
| 39 |
-
if __name__ == "__main__":
|
| 40 |
-
asyncio.run(final_cleanup())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@@ -1,57 +0,0 @@
|
|
| 1 |
-
"""
|
| 2 |
-
Script pour mettre à jour les icônes des catégories dans le nouveau champ 'icon'
|
| 3 |
-
"""
|
| 4 |
-
import asyncio
|
| 5 |
-
from sqlalchemy import select
|
| 6 |
-
from app.core.database import AsyncSessionLocal
|
| 7 |
-
from app.models.law import Category
|
| 8 |
-
|
| 9 |
-
# Mapping des catégories avec leurs icônes
|
| 10 |
-
CATEGORY_ICONS = {
|
| 11 |
-
"Droit Constitutionnel": "⚖️",
|
| 12 |
-
"Droit Civil": "👥",
|
| 13 |
-
"Droit Pénal": "🔒",
|
| 14 |
-
"Droit Commercial": "🏪",
|
| 15 |
-
"Droit du Travail": "👔",
|
| 16 |
-
"Droit Fiscal": "💰",
|
| 17 |
-
"Droit Administratif": "🏛️",
|
| 18 |
-
"Droit OHADA": "🌍",
|
| 19 |
-
"Droit des Affaires": "💼",
|
| 20 |
-
"Procédure Civile": "📋",
|
| 21 |
-
"Procédure Pénale": "⚖️",
|
| 22 |
-
}
|
| 23 |
-
|
| 24 |
-
async def update_icons():
|
| 25 |
-
async with AsyncSessionLocal() as db:
|
| 26 |
-
# Récupérer toutes les catégories
|
| 27 |
-
result = await db.execute(select(Category))
|
| 28 |
-
categories = result.scalars().all()
|
| 29 |
-
|
| 30 |
-
updated_count = 0
|
| 31 |
-
for category in categories:
|
| 32 |
-
if category.name in CATEGORY_ICONS:
|
| 33 |
-
# Mettre à jour le champ icon
|
| 34 |
-
category.icon = CATEGORY_ICONS[category.name]
|
| 35 |
-
|
| 36 |
-
# Nettoyer la description (enlever les icônes si présentes)
|
| 37 |
-
if category.description and category.description.startswith(category.icon):
|
| 38 |
-
# Enlever l'icône du début de la description
|
| 39 |
-
category.description = category.description[len(category.icon):].strip()
|
| 40 |
-
|
| 41 |
-
updated_count += 1
|
| 42 |
-
print(f"✅ {category.icon} {category.name}")
|
| 43 |
-
|
| 44 |
-
await db.commit()
|
| 45 |
-
print(f"\n✅ {updated_count} catégories mises à jour avec des icônes")
|
| 46 |
-
|
| 47 |
-
# Afficher le résultat
|
| 48 |
-
result = await db.execute(select(Category).order_by(Category.id))
|
| 49 |
-
categories = result.scalars().all()
|
| 50 |
-
|
| 51 |
-
print(f"\n📋 Catégories finales:")
|
| 52 |
-
for cat in categories:
|
| 53 |
-
icon_display = cat.icon if cat.icon else "📜"
|
| 54 |
-
print(f" {icon_display} {cat.name}")
|
| 55 |
-
|
| 56 |
-
if __name__ == "__main__":
|
| 57 |
-
asyncio.run(update_icons())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@@ -1,115 +0,0 @@
|
|
| 1 |
-
"""
|
| 2 |
-
Re-extract text from Constitution PDF with improved extraction.
|
| 3 |
-
"""
|
| 4 |
-
import sys
|
| 5 |
-
import os
|
| 6 |
-
sys.path.insert(0, '.')
|
| 7 |
-
os.environ.setdefault('PYTHONPATH', '.')
|
| 8 |
-
|
| 9 |
-
from pathlib import Path
|
| 10 |
-
from sqlalchemy import create_engine, text
|
| 11 |
-
from sqlalchemy.orm import sessionmaker
|
| 12 |
-
from app.core.config import settings
|
| 13 |
-
from app.models.law import Law, Article
|
| 14 |
-
from app.utils.text_chunker import extract_articles
|
| 15 |
-
|
| 16 |
-
# File ID for Constitution
|
| 17 |
-
file_id = "e824bec8-f852-4a9c-aa27-5bf03f9b857f"
|
| 18 |
-
file_path = Path(f"data/uploads/{file_id}.pdf")
|
| 19 |
-
|
| 20 |
-
print(f"📄 Re-extracting text from: {file_path}")
|
| 21 |
-
|
| 22 |
-
if not file_path.exists():
|
| 23 |
-
print(f"❌ File not found: {file_path}")
|
| 24 |
-
exit(1)
|
| 25 |
-
|
| 26 |
-
# Extract text with improved method
|
| 27 |
-
from pypdf import PdfReader
|
| 28 |
-
|
| 29 |
-
reader = PdfReader(file_path)
|
| 30 |
-
total_pages = len(reader.pages)
|
| 31 |
-
print(f"📄 PDF has {total_pages} pages")
|
| 32 |
-
|
| 33 |
-
pages_text = []
|
| 34 |
-
for i, page in enumerate(reader.pages):
|
| 35 |
-
try:
|
| 36 |
-
# Try layout mode for better structure
|
| 37 |
-
page_text = page.extract_text(extraction_mode="layout")
|
| 38 |
-
except TypeError:
|
| 39 |
-
page_text = page.extract_text()
|
| 40 |
-
|
| 41 |
-
# Add page marker
|
| 42 |
-
pages_text.append(f"<<PAGE: {i + 1}>>\n{page_text}")
|
| 43 |
-
|
| 44 |
-
extracted_text = "\n\n".join(pages_text)
|
| 45 |
-
print(f"✅ Extracted {len(extracted_text)} characters")
|
| 46 |
-
|
| 47 |
-
# Show Article 4 area
|
| 48 |
-
import re
|
| 49 |
-
art4_match = re.search(r'Article\s+4\s*[.:]\s*', extracted_text, re.IGNORECASE)
|
| 50 |
-
if art4_match:
|
| 51 |
-
start = art4_match.start()
|
| 52 |
-
print("\n" + "=" * 60)
|
| 53 |
-
print("ARTICLE 4 in NEW extraction:")
|
| 54 |
-
print("=" * 60)
|
| 55 |
-
print(extracted_text[start:start+600])
|
| 56 |
-
|
| 57 |
-
art9_match = re.search(r'Article\s+9\s*[.:]\s*', extracted_text, re.IGNORECASE)
|
| 58 |
-
if art9_match:
|
| 59 |
-
start = art9_match.start()
|
| 60 |
-
print("\n" + "=" * 60)
|
| 61 |
-
print("ARTICLE 9 in NEW extraction:")
|
| 62 |
-
print("=" * 60)
|
| 63 |
-
print(extracted_text[start:start+800])
|
| 64 |
-
|
| 65 |
-
# Now save to database
|
| 66 |
-
print("\n📥 Updating law content in database...")
|
| 67 |
-
|
| 68 |
-
sync_url = settings.DATABASE_URL.replace('+asyncpg', '')
|
| 69 |
-
engine = create_engine(sync_url)
|
| 70 |
-
Session = sessionmaker(bind=engine)
|
| 71 |
-
|
| 72 |
-
with Session() as session:
|
| 73 |
-
# Update law content
|
| 74 |
-
session.execute(
|
| 75 |
-
text("UPDATE laws SET content = :content WHERE id = 1"),
|
| 76 |
-
{"content": extracted_text}
|
| 77 |
-
)
|
| 78 |
-
|
| 79 |
-
# Delete old articles
|
| 80 |
-
session.execute(text("DELETE FROM articles WHERE law_id = 1"))
|
| 81 |
-
|
| 82 |
-
session.commit()
|
| 83 |
-
print("✅ Law content updated")
|
| 84 |
-
|
| 85 |
-
# Now run article extraction
|
| 86 |
-
print("\n📊 Extracting articles with improved parser...")
|
| 87 |
-
articles = extract_articles(extracted_text)
|
| 88 |
-
|
| 89 |
-
print(f"📊 Extracted {len(articles)} articles")
|
| 90 |
-
|
| 91 |
-
# Save articles to database
|
| 92 |
-
with Session() as session:
|
| 93 |
-
for article_data in articles:
|
| 94 |
-
article = Article(
|
| 95 |
-
law_id=1,
|
| 96 |
-
number=str(article_data.get('number', '')),
|
| 97 |
-
title=article_data.get('title'),
|
| 98 |
-
section=article_data.get('section'),
|
| 99 |
-
content=article_data.get('content', ''),
|
| 100 |
-
order=article_data.get('position', 0),
|
| 101 |
-
page_number=article_data.get('page_number'),
|
| 102 |
-
)
|
| 103 |
-
session.add(article)
|
| 104 |
-
|
| 105 |
-
session.commit()
|
| 106 |
-
print(f"✅ Saved {len(articles)} articles")
|
| 107 |
-
|
| 108 |
-
# Show results for Article 4 and 9
|
| 109 |
-
for art in articles:
|
| 110 |
-
if art['number'] in ['4', '9']:
|
| 111 |
-
print(f"\n--- Article {art['number']} ---")
|
| 112 |
-
print(f"Section: {art.get('section', 'None')}")
|
| 113 |
-
print(f"Content ({len(art['content'])} chars):")
|
| 114 |
-
print(art['content'][:300])
|
| 115 |
-
print("...")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@@ -1,101 +0,0 @@
|
|
| 1 |
-
"""
|
| 2 |
-
Re-extract Constitution with pdfplumber and save to database.
|
| 3 |
-
"""
|
| 4 |
-
import sys
|
| 5 |
-
import re
|
| 6 |
-
sys.path.insert(0, '.')
|
| 7 |
-
|
| 8 |
-
from pathlib import Path
|
| 9 |
-
from sqlalchemy import create_engine, text
|
| 10 |
-
from sqlalchemy.orm import sessionmaker
|
| 11 |
-
from app.core.config import settings
|
| 12 |
-
from app.models.law import Article
|
| 13 |
-
from app.utils.text_chunker import extract_articles
|
| 14 |
-
|
| 15 |
-
# File ID for Constitution
|
| 16 |
-
file_id = "e824bec8-f852-4a9c-aa27-5bf03f9b857f"
|
| 17 |
-
file_path = Path(f"data/uploads/{file_id}.pdf")
|
| 18 |
-
|
| 19 |
-
print(f"📄 Re-extracting with pdfplumber from: {file_path}")
|
| 20 |
-
|
| 21 |
-
if not file_path.exists():
|
| 22 |
-
print(f"❌ File not found: {file_path}")
|
| 23 |
-
exit(1)
|
| 24 |
-
|
| 25 |
-
# Extract with pdfplumber
|
| 26 |
-
import pdfplumber
|
| 27 |
-
|
| 28 |
-
pages_text = []
|
| 29 |
-
with pdfplumber.open(file_path) as pdf:
|
| 30 |
-
total_pages = len(pdf.pages)
|
| 31 |
-
print(f"📄 PDF has {total_pages} pages")
|
| 32 |
-
|
| 33 |
-
for i, page in enumerate(pdf.pages):
|
| 34 |
-
page_text = page.extract_text(x_tolerance=3, y_tolerance=3) or ""
|
| 35 |
-
pages_text.append(f"<<PAGE: {i + 1}>>\n{page_text}")
|
| 36 |
-
|
| 37 |
-
extracted_text = "\n\n".join(pages_text)
|
| 38 |
-
print(f"✅ Extracted {len(extracted_text)} characters")
|
| 39 |
-
|
| 40 |
-
# Save to database
|
| 41 |
-
print("\n📥 Updating law content in database...")
|
| 42 |
-
|
| 43 |
-
sync_url = settings.DATABASE_URL.replace('+asyncpg', '')
|
| 44 |
-
engine = create_engine(sync_url)
|
| 45 |
-
Session = sessionmaker(bind=engine)
|
| 46 |
-
|
| 47 |
-
with Session() as session:
|
| 48 |
-
session.execute(
|
| 49 |
-
text("UPDATE laws SET content = :content WHERE id = 1"),
|
| 50 |
-
{"content": extracted_text}
|
| 51 |
-
)
|
| 52 |
-
session.execute(text("DELETE FROM articles WHERE law_id = 1"))
|
| 53 |
-
session.commit()
|
| 54 |
-
print("✅ Law content updated")
|
| 55 |
-
|
| 56 |
-
# Extract articles
|
| 57 |
-
print("\n📊 Extracting articles...")
|
| 58 |
-
articles = extract_articles(extracted_text)
|
| 59 |
-
print(f"📊 Extracted {len(articles)} articles")
|
| 60 |
-
|
| 61 |
-
# Save articles with clean content
|
| 62 |
-
with Session() as session:
|
| 63 |
-
for article_data in articles:
|
| 64 |
-
content = article_data.get('content', '')
|
| 65 |
-
# Additional cleaning
|
| 66 |
-
content = re.sub(r'<<PAGE:\s*\d+>>', '', content)
|
| 67 |
-
content = re.sub(r'\n\s*\d{1,2}\s*\n', '\n', content) # Orphan page numbers
|
| 68 |
-
content = content.strip()
|
| 69 |
-
|
| 70 |
-
article = Article(
|
| 71 |
-
law_id=1,
|
| 72 |
-
number=str(article_data.get('number', '')),
|
| 73 |
-
title=article_data.get('title'),
|
| 74 |
-
section=article_data.get('section'),
|
| 75 |
-
content=content,
|
| 76 |
-
order=article_data.get('position', 0),
|
| 77 |
-
page_number=article_data.get('page_number'),
|
| 78 |
-
)
|
| 79 |
-
session.add(article)
|
| 80 |
-
|
| 81 |
-
session.commit()
|
| 82 |
-
print(f"✅ Saved {len(articles)} articles")
|
| 83 |
-
|
| 84 |
-
# Verify results
|
| 85 |
-
print("\n📋 VERIFICATION:")
|
| 86 |
-
print("-" * 60)
|
| 87 |
-
|
| 88 |
-
for art_num in ['4', '9', '10']:
|
| 89 |
-
art = [a for a in articles if str(a['number']) == art_num]
|
| 90 |
-
if art:
|
| 91 |
-
a = art[0]
|
| 92 |
-
content = a['content']
|
| 93 |
-
content = re.sub(r'<<PAGE:\s*\d+>>', '', content)
|
| 94 |
-
content = re.sub(r'\n\s*\d{1,2}\s*\n', '\n', content)
|
| 95 |
-
|
| 96 |
-
print(f"\nArticle {art_num}:")
|
| 97 |
-
print(f" Section: {a.get('section', 'N/A')}")
|
| 98 |
-
print(f" Content ({len(content)} chars):")
|
| 99 |
-
print(f" {content[:250]}...")
|
| 100 |
-
|
| 101 |
-
print("\n✅ DONE")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@@ -1,20 +0,0 @@
|
|
| 1 |
-
"""
|
| 2 |
-
Script to reprocess a law with the improved article parser.
|
| 3 |
-
"""
|
| 4 |
-
import sys
|
| 5 |
-
sys.path.insert(0, '.')
|
| 6 |
-
|
| 7 |
-
from app.tasks.process_law import process_law_sync
|
| 8 |
-
|
| 9 |
-
# Reprocess law ID 1 (La Constitution)
|
| 10 |
-
law_id = 1
|
| 11 |
-
file_id = "e824bec8-f852-4a9c-aa27-5bf03f9b857f"
|
| 12 |
-
|
| 13 |
-
print(f"🔄 Reprocessing law {law_id} with file {file_id}...")
|
| 14 |
-
try:
|
| 15 |
-
result = process_law_sync(law_id, file_id)
|
| 16 |
-
print(f"✅ Success! Result: {result}")
|
| 17 |
-
except Exception as e:
|
| 18 |
-
print(f"❌ Error: {e}")
|
| 19 |
-
import traceback
|
| 20 |
-
traceback.print_exc()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@@ -6,8 +6,21 @@ Utilise la méthode la plus directe avec gestion d'erreurs complète.
|
|
| 6 |
import psycopg2
|
| 7 |
from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT
|
| 8 |
|
| 9 |
-
#
|
| 10 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
|
| 12 |
def reset_database_fixed():
|
| 13 |
"""Vide la base de données de manière robuste."""
|
|
|
|
| 6 |
import psycopg2
|
| 7 |
from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT
|
| 8 |
|
| 9 |
+
# L'URL vient de Settings, pas d'une constante.
|
| 10 |
+
#
|
| 11 |
+
# Elle etait ecrite en dur ici, mot de passe compris, et pointait sur un port
|
| 12 |
+
# (5432) et une base (`jurix_db`) qui n'existent pas : le script ne pouvait de
|
| 13 |
+
# toute facon plus se connecter. Passer par Settings lui rend son utilite ET
|
| 14 |
+
# retire le secret du depot.
|
| 15 |
+
import sys
|
| 16 |
+
from pathlib import Path
|
| 17 |
+
|
| 18 |
+
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
| 19 |
+
|
| 20 |
+
from app.core.config import settings # noqa: E402
|
| 21 |
+
|
| 22 |
+
# psycopg2 ne comprend pas le prefixe +asyncpg de SQLAlchemy.
|
| 23 |
+
DATABASE_URL = settings.DATABASE_URL.replace("postgresql+asyncpg://", "postgresql://")
|
| 24 |
|
| 25 |
def reset_database_fixed():
|
| 26 |
"""Vide la base de données de manière robuste."""
|
|
@@ -1,29 +0,0 @@
|
|
| 1 |
-
"""Final verification of Articles 4, 9, 10 after all fixes."""
|
| 2 |
-
import sys
|
| 3 |
-
sys.path.insert(0, '.')
|
| 4 |
-
|
| 5 |
-
from sqlalchemy import create_engine, text
|
| 6 |
-
from app.core.config import settings
|
| 7 |
-
|
| 8 |
-
sync_url = settings.DATABASE_URL.replace('+asyncpg', '')
|
| 9 |
-
engine = create_engine(sync_url)
|
| 10 |
-
|
| 11 |
-
with engine.connect() as conn:
|
| 12 |
-
result = conn.execute(text("""
|
| 13 |
-
SELECT number, section, content
|
| 14 |
-
FROM articles
|
| 15 |
-
WHERE law_id = 1 AND number IN ('4', '9', '10')
|
| 16 |
-
ORDER BY number::int
|
| 17 |
-
"""))
|
| 18 |
-
|
| 19 |
-
with open('final_verification.txt', 'w', encoding='utf-8') as f:
|
| 20 |
-
for row in result:
|
| 21 |
-
number, section, content = row
|
| 22 |
-
f.write(f"\n{'='*60}\n")
|
| 23 |
-
f.write(f"ARTICLE {number}\n")
|
| 24 |
-
f.write(f"Section: {section}\n")
|
| 25 |
-
f.write(f"{'='*60}\n")
|
| 26 |
-
f.write(f"{content}\n")
|
| 27 |
-
f.write(f"\n[Length: {len(content)} chars]\n")
|
| 28 |
-
|
| 29 |
-
print("Saved to final_verification.txt")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@@ -1,89 +0,0 @@
|
|
| 1 |
-
"""
|
| 2 |
-
Test pdfplumber extraction and compare with pypdf.
|
| 3 |
-
"""
|
| 4 |
-
import sys
|
| 5 |
-
sys.path.insert(0, '.')
|
| 6 |
-
|
| 7 |
-
from pathlib import Path
|
| 8 |
-
|
| 9 |
-
# File ID for Constitution
|
| 10 |
-
file_id = "e824bec8-f852-4a9c-aa27-5bf03f9b857f"
|
| 11 |
-
file_path = Path(f"data/uploads/{file_id}.pdf")
|
| 12 |
-
|
| 13 |
-
print(f"📄 Testing extraction from: {file_path}")
|
| 14 |
-
|
| 15 |
-
if not file_path.exists():
|
| 16 |
-
print(f"❌ File not found: {file_path}")
|
| 17 |
-
exit(1)
|
| 18 |
-
|
| 19 |
-
# Test pdfplumber
|
| 20 |
-
print("\n" + "=" * 60)
|
| 21 |
-
print("PDFPLUMBER EXTRACTION")
|
| 22 |
-
print("=" * 60)
|
| 23 |
-
|
| 24 |
-
import pdfplumber
|
| 25 |
-
import re
|
| 26 |
-
|
| 27 |
-
with pdfplumber.open(file_path) as pdf:
|
| 28 |
-
# Get page 5 (where Article 4 should be)
|
| 29 |
-
page5 = pdf.pages[4] # 0-indexed
|
| 30 |
-
text_pdfplumber = page5.extract_text(x_tolerance=3, y_tolerance=3)
|
| 31 |
-
|
| 32 |
-
print(f"Page 5 text length: {len(text_pdfplumber)} chars")
|
| 33 |
-
|
| 34 |
-
# Find Article 4
|
| 35 |
-
art4_match = re.search(r'Article\s*4\s*[.:]', text_pdfplumber, re.IGNORECASE)
|
| 36 |
-
if art4_match:
|
| 37 |
-
start = art4_match.start()
|
| 38 |
-
print("\nARTICLE 4 area:")
|
| 39 |
-
print("-" * 40)
|
| 40 |
-
print(text_pdfplumber[start:start+500])
|
| 41 |
-
|
| 42 |
-
# Test pypdf for comparison
|
| 43 |
-
print("\n" + "=" * 60)
|
| 44 |
-
print("PYPDF EXTRACTION (for comparison)")
|
| 45 |
-
print("=" * 60)
|
| 46 |
-
|
| 47 |
-
from pypdf import PdfReader
|
| 48 |
-
|
| 49 |
-
reader = PdfReader(file_path)
|
| 50 |
-
page5 = reader.pages[4]
|
| 51 |
-
|
| 52 |
-
try:
|
| 53 |
-
text_pypdf = page5.extract_text(extraction_mode="layout")
|
| 54 |
-
except TypeError:
|
| 55 |
-
text_pypdf = page5.extract_text()
|
| 56 |
-
|
| 57 |
-
print(f"Page 5 text length: {len(text_pypdf)} chars")
|
| 58 |
-
|
| 59 |
-
art4_match = re.search(r'Article\s*4\s*[.:]', text_pypdf, re.IGNORECASE)
|
| 60 |
-
if art4_match:
|
| 61 |
-
start = art4_match.start()
|
| 62 |
-
print("\nARTICLE 4 area:")
|
| 63 |
-
print("-" * 40)
|
| 64 |
-
print(text_pypdf[start:start+500])
|
| 65 |
-
|
| 66 |
-
# Compare which one correctly has "- Le Président" and "- Le Parlement"
|
| 67 |
-
print("\n" + "=" * 60)
|
| 68 |
-
print("QUALITY CHECK")
|
| 69 |
-
print("=" * 60)
|
| 70 |
-
|
| 71 |
-
if "- Le Président" in text_pdfplumber or "-Le Président" in text_pdfplumber:
|
| 72 |
-
print("✅ pdfplumber: Found '- Le Président'")
|
| 73 |
-
else:
|
| 74 |
-
print("❌ pdfplumber: Missing '- Le Président'")
|
| 75 |
-
|
| 76 |
-
if "- Le Président" in text_pypdf or "-Le Président" in text_pypdf:
|
| 77 |
-
print("✅ pypdf: Found '- Le Président'")
|
| 78 |
-
else:
|
| 79 |
-
print("❌ pypdf: Missing '- Le Président'")
|
| 80 |
-
|
| 81 |
-
if "- Le Parlement" in text_pdfplumber or "-Le Parlement" in text_pdfplumber:
|
| 82 |
-
print("✅ pdfplumber: Found '- Le Parlement'")
|
| 83 |
-
else:
|
| 84 |
-
print("❌ pdfplumber: Missing '- Le Parlement'")
|
| 85 |
-
|
| 86 |
-
if "- Le Parlement" in text_pypdf or "-Le Parlement" in text_pypdf:
|
| 87 |
-
print("✅ pypdf: Found '- Le Parlement'")
|
| 88 |
-
else:
|
| 89 |
-
print("❌ pypdf: Missing '- Le Parlement'")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|