Spaces:
Sleeping
Sleeping
Delete executives/nexus_advanced_parser.py
Browse files
executives/nexus_advanced_parser.py
DELETED
|
@@ -1,116 +0,0 @@
|
|
| 1 |
-
# executives/nexus_advanced_parser.py
|
| 2 |
-
import os
|
| 3 |
-
import pandas as pd
|
| 4 |
-
from ollama import AsyncClient
|
| 5 |
-
import asyncio
|
| 6 |
-
import json
|
| 7 |
-
import re
|
| 8 |
-
import warnings
|
| 9 |
-
|
| 10 |
-
warnings.filterwarnings("ignore")
|
| 11 |
-
|
| 12 |
-
# Configuration des chemins d'accès (datasets isolés sur l'hôte)
|
| 13 |
-
DIR_DATA = "../datasets/"
|
| 14 |
-
OUTPUT_PARSED = os.path.join(DIR_DATA, "nexus_qwen_parsed.csv")
|
| 15 |
-
MODEL_LOCAL = "qwen2.5:14b"
|
| 16 |
-
|
| 17 |
-
# 1. Cartographie des fichiers d'Open Data classiques
|
| 18 |
-
FICHIERS_CIBLES = {
|
| 19 |
-
"CYBERSÉCURITÉ": "Attack_Dataset.csv",
|
| 20 |
-
"TRANSPORT & MOBILITÉ": "foire-aux-questions.csv",
|
| 21 |
-
"ASSISTANCE SOCIALE": "Tweets.csv",
|
| 22 |
-
"RISQUES ENVIRONNEMENTAUX": "ARIA.csv"
|
| 23 |
-
}
|
| 24 |
-
|
| 25 |
-
# 2. Cartographie des fichiers massifs complexes
|
| 26 |
-
FICHIER_SP = "services_public.csv"
|
| 27 |
-
FICHIER_MTA = "MTA_Customer_Feedback_Data__2014-2019.csv"
|
| 28 |
-
FICHIER_DMR = "dans-ma-rue.csv"
|
| 29 |
-
|
| 30 |
-
async def prompt_qwen(client, contexte, domaine):
|
| 31 |
-
sys_prompt = f"""Tu es un opérateur d'urgence d'élite. Transforme cette information technique ou ce signalement administratif brut en une phrase d'urgence réaliste prononcée au téléphone par un citoyen (paniqué, en colère, stressé ou laconique).
|
| 32 |
-
Le domaine cible est strictement : {domaine}.
|
| 33 |
-
Ne mets aucune formule de politesse. Va droit au but.
|
| 34 |
-
Génère UNIQUEMENT un objet JSON strict au format suivant :
|
| 35 |
-
{{"texte": "la phrase d'appel générée en français", "domaine": "{domaine}", "severite": 2, "impact": 1, "cible": 0, "friction": "MANQUE_LIEU"}}"""
|
| 36 |
-
|
| 37 |
-
try:
|
| 38 |
-
response = await client.chat(
|
| 39 |
-
model=MODEL_LOCAL,
|
| 40 |
-
messages=[{'role': 'system', 'content': sys_prompt}, {'role': 'user', 'content': contexte}],
|
| 41 |
-
options={'temperature': 0.7, 'num_predict': 150}
|
| 42 |
-
)
|
| 43 |
-
content = re.sub(r'```json\s*|```', '', response['message']['content'].strip())
|
| 44 |
-
data = json.loads(content)
|
| 45 |
-
data['domaine'] = domaine.upper()
|
| 46 |
-
return data
|
| 47 |
-
except:
|
| 48 |
-
return None
|
| 49 |
-
|
| 50 |
-
async def executer_parsing():
|
| 51 |
-
print("==================================================")
|
| 52 |
-
print("🧠 ÉTAPE 1/3 : EXTRACTION, REFORMULATION ET ALIGNEMENT (QWEN 14B)")
|
| 53 |
-
print("==================================================\n")
|
| 54 |
-
client = AsyncClient()
|
| 55 |
-
lignes_generees = []
|
| 56 |
-
|
| 57 |
-
# A. Traitement des fichiers standards
|
| 58 |
-
for domaine, fichier in FICHIERS_CIBLES.items():
|
| 59 |
-
chemin = os.path.join(DIR_DATA, fichier)
|
| 60 |
-
if os.path.exists(chemin):
|
| 61 |
-
print(f"⚙️ Extraction : {domaine} depuis {fichier}...")
|
| 62 |
-
df = pd.read_csv(chemin, nrows=50, on_bad_lines='skip', sep=';' if 'foire' in fichier else ',')
|
| 63 |
-
for _, row in df.iterrows():
|
| 64 |
-
contexte = " | ".join([str(v) for v in row.values[:3] if pd.notna(v)])
|
| 65 |
-
data = await prompt_qwen(client, contexte, domaine)
|
| 66 |
-
if data: lignes_generees.append(data)
|
| 67 |
-
|
| 68 |
-
# B. Le Mastodonte : Dans Ma Rue (Paris) -> SERVICES URBAINS
|
| 69 |
-
chemin_dmr = os.path.join(DIR_DATA, FICHIER_DMR)
|
| 70 |
-
if os.path.exists(chemin_dmr):
|
| 71 |
-
print(f"🚧 Extraction Sécurisée : SERVICES URBAINS depuis {FICHIER_DMR}...")
|
| 72 |
-
# Limite stricte pour éviter la saturation du GPU
|
| 73 |
-
df_dmr = pd.read_csv(chemin_dmr, nrows=120, on_bad_lines='skip', sep=None, engine='python')
|
| 74 |
-
for _, row in df_dmr.iterrows():
|
| 75 |
-
t_dec = row.get('TYPE DECLARATION', '')
|
| 76 |
-
s_dec = row.get('SOUS TYPE DECLARATION', '')
|
| 77 |
-
adr = row.get('ADRESSE', '')
|
| 78 |
-
contexte_dmr = f"Incident: {t_dec} - {s_dec} | Lieu: {adr}"
|
| 79 |
-
data = await prompt_qwen(client, contexte_dmr, "SERVICES URBAINS")
|
| 80 |
-
if data:
|
| 81 |
-
# Modulateur de friction : détection d'adresse
|
| 82 |
-
if any(word in str(data['texte']).lower() for word in ["rue", "avenue", "boulevard", "paris", "place"]):
|
| 83 |
-
data['friction'] = "COMPLET"
|
| 84 |
-
lignes_generees.append(data)
|
| 85 |
-
|
| 86 |
-
# C. MTA Customer Feedback -> TRANSPORT & MOBILITÉ
|
| 87 |
-
chemin_mta = os.path.join(DIR_DATA, FICHIER_MTA)
|
| 88 |
-
if os.path.exists(chemin_mta):
|
| 89 |
-
print(f"🚆 Extraction : TRANSPORT & MOBILITÉ depuis {FICHIER_MTA}...")
|
| 90 |
-
df_mta = pd.read_csv(chemin_mta, nrows=50, on_bad_lines='skip')
|
| 91 |
-
for _, row in df_mta.iterrows():
|
| 92 |
-
contexte_mta = f"Agency: {row.get('Agency', '')} | Subject: {row.get('Subject Matter', '')} | Detail: {row.get('Subject Detail', '')}"
|
| 93 |
-
data = await prompt_qwen(client, contexte_mta, "TRANSPORT & MOBILITÉ")
|
| 94 |
-
if data: lignes_generees.append(data)
|
| 95 |
-
|
| 96 |
-
# D. Services Publics -> ASSISTANCE SOCIALE / SERVICES URBAINS
|
| 97 |
-
chemin_sp = os.path.join(DIR_DATA, FICHIER_SP)
|
| 98 |
-
if os.path.exists(chemin_sp):
|
| 99 |
-
print(f"🏛️ Extraction : TEXTES LÉGAUX depuis {FICHIER_SP}...")
|
| 100 |
-
df_sp = pd.read_csv(chemin_sp, nrows=50, on_bad_lines='skip')
|
| 101 |
-
for _, row in df_sp.iterrows():
|
| 102 |
-
contexte_sp = f"Titre: {row.get('title', '')} | Intro: {row.get('introduction', '')}"
|
| 103 |
-
domaine_sp = "SERVICES URBAINS" if "Impôts" not in str(row.get('themetitles', '')) else "ASSISTANCE SOCIALE"
|
| 104 |
-
data = await prompt_qwen(client, contexte_sp, domaine_sp)
|
| 105 |
-
if data: lignes_generees.append(data)
|
| 106 |
-
|
| 107 |
-
# Sauvegarde de la matrice consolidée
|
| 108 |
-
if lignes_generees:
|
| 109 |
-
df_output = pd.DataFrame(lignes_generees)
|
| 110 |
-
df_output.to_csv(OUTPUT_PARSED, index=False)
|
| 111 |
-
print(f"\n✅ PARSING TERMINÉ. Base d'inférence sémantique générée : {OUTPUT_PARSED} ({len(df_output)} lignes)")
|
| 112 |
-
else:
|
| 113 |
-
print("\n❌ ÉCHEC CRITIQUE : Qwen 14B n'a renvoyé aucune traduction valide.")
|
| 114 |
-
|
| 115 |
-
if __name__ == "__main__":
|
| 116 |
-
asyncio.run(executer_parsing())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|