# --- Chargement et Dérivation Clé de Chiffrement ---
load_dotenv(find_dotenv())
PASSPHRASE_VAR_NAME = "TEXT_CONFIG_PASSPHRASE"
passphrase = os.getenv(PASSPHRASE_VAR_NAME)
ENCRYPTION_KEY = None # Sera défini si la dérivation réussit
FIXED_SALT = b'q\x8b\t\x97\x8b\xe9\xa3\xf2\xe4\x8e\xea\xf5\xe8\xb7\xd6\x8c' # Exemple de sel fixe (16 bytes)
print(f"Vérification de la phrase secrète '{PASSPHRASE_VAR_NAME}' dans .env...")
if passphrase:
print(f"✅ Phrase secrète trouvée. Dérivation de la clé...")
try:
kdf = PBKDF2HMAC(
algorithm=hashes.SHA256(), length=32, salt=FIXED_SALT,
iterations=480000, backend=default_backend()
)
derived_key_raw = kdf.derive(passphrase.encode('utf-8'))
ENCRYPTION_KEY = base64.urlsafe_b64encode(derived_key_raw)
# Optionnel: commenter le test si la clé dérivée pose problème avec Fernet(key) directement
# try:
# Fernet(ENCRYPTION_KEY)
# print("✅ Clé de chiffrement dérivée avec succès et valide.")
# except Exception as e_fernet:
# print(f"⚠️ Clé dérivée semble invalide pour Fernet : {e_fernet}.")
# ENCRYPTION_KEY = None # Invalider si test échoue
if ENCRYPTION_KEY: print("✅ Clé de chiffrement dérivée et encodée.")
except Exception as e:
print(f"⚠️ Erreur dérivation clé : {e}. Chiffrement désactivé.")
ENCRYPTION_KEY = None
else:
print(f"⚠️ Variable '{PASSPHRASE_VAR_NAME}' non trouvée dans .env. Chiffrement désactivé.")
# --- URLs et Chemins ---
TIKA_URL_PARTS = ["https:", "", "tika", "open-webui", "myia", "io", "tika"]
# --- LIGNE DÉCOMMENTÉE ---
# Reconstruit l'URL Tika une seule fois ici pour être utilisée globalement
TIKA_SERVER_URL = f"{TIKA_URL_PARTS[0]}//{'.'.join(TIKA_URL_PARTS[2:-1])}/{TIKA_URL_PARTS[-1]}"
# -------------------------
JINA_READER_PREFIX = "https://r.jina.ai/"
CACHE_DIR = Path("./text_cache")
CONFIG_FILE = Path("./extract_sources.json.gz.enc")
# --- Création Cache Dir ---
try:
CACHE_DIR.mkdir(parents=True, exist_ok=True)
print(f"Cache répertoire assuré : {CACHE_DIR.resolve()}")
except Exception as e:
print(f"Erreur création répertoire cache {CACHE_DIR}: {e}")
# --- Structure par Défaut (avec nouvelle structure URL) ---
DEFAULT_EXTRACT_SOURCES = [
{"source_name": "Exemple Vide (Config manquante)", "source_type": "jina",
"schema": "https:", "host_parts": ["example", "com"], "path": "/",
"extracts": []}
]
# --- Définition Initiale des Sources & Extraits (Structure Corrigée) ---
# (Cette structure est utilisée comme fallback si le fichier .enc n'existe pas/n'est pas lisible)
EXTRACT_SOURCES = [
{
"source_name": "Lincoln-Douglas Débat 1 (NPS)", "source_type": "jina",
"schema": "https:", "host_parts": ["www", "nps", "gov"], "path": "/liho/learn/historyculture/debate1.htm",
"extracts": [
{"extract_name": "1. Débat Complet (Ottawa, 1858)", "start_marker": "**August 21, 1858**", "end_marker": "(Three times three cheers were here given for Senator Douglas.)"},
{"extract_name": "2. Discours Principal de Lincoln", "start_marker": "MY FELLOW-CITIZENS: When a man hears himself", "end_marker": "The Judge can take his half hour."},
{"extract_name": "3. Discours d'Ouverture de Douglas", "start_marker": "Ladies and gentlemen: I appear before you", "end_marker": "occupy an half hour in replying to him."},
{"extract_name": "4. Lincoln sur Droits Naturels/Égalité", "start_marker": "I will say here, while upon this subject,", "end_marker": "equal of every living man._ [Great applause.]"},
{"extract_name": "5. Douglas sur Race/Dred Scott", "start_marker": "utterly opposed to the Dred Scott decision,", "end_marker": "equality with the white man. (\"Good.\")"},
]
},
{
"source_name": "Lincoln-Douglas Débat 2 (NPS)", "source_type": "jina",
"schema": "https:", "host_parts": ["www", "nps", "gov"], "path": "/liho/learn/historyculture/debate2.htm",
"extracts": [
{"extract_name": "1. Débat Complet (Freeport, 1858)", "start_marker": "It was a cloudy, cool, and damp day.", "end_marker": "I cannot, gentlemen, my time has expired."},
{"extract_name": "2. Discours Principal de Douglas", "start_marker": "**Mr. Douglas' Speech**\n\nLadies and Gentlemen-", "end_marker": "stopped on the moment."},
{"extract_name": "3. Discours d'Ouverture de Lincoln", "start_marker": "LADIES AND GENTLEMEN - On Saturday last,", "end_marker": "Go on, Judge Douglas."},
{"extract_name": "4. Doctrine de Freeport (Douglas)", "start_marker": "The next question propounded to me by Mr. Lincoln is,", "end_marker": "satisfactory on that point."},
{"extract_name": "5. Lincoln répond aux 7 questions", "start_marker": "The first one of these interrogatories is in these words:,", "end_marker": "aggravate the slavery question among ourselves. [Cries of good, good.]"},
]
},
{
"source_name": "Corpus de recherche (chiffré, hors dépôt public) - A", "source_type": "jina",
"schema": "", "host_parts": [], "path": "",
"extracts": [
{"extract_name": "Extraits chargés depuis extract_sources.json.gz.enc", "start_marker": "", "end_marker": ""},
]
},
{
"source_name": "Corpus de recherche (chiffré, hors dépôt public) - B", "source_type": "jina",
"schema": "", "host_parts": [], "path": "",
"extracts": [
{"extract_name": "Extraits chargés depuis extract_sources.json.gz.enc", "start_marker": "", "end_marker": ""},
]
},
]
# --- Initialisation variable globale ---
# Sera mise à jour par load_extract_definitions lors de l'appel à configure_analysis_task
current_extract_definitions = []
print(f"Configuration UI chargée. {len(EXTRACT_SOURCES)} sources initiales définies.")