@tricoteuses/senat 2.10.1 → 2.10.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/loaders.js CHANGED
@@ -211,10 +211,10 @@ export function* iterLoadSenatAgendasGrouped(dataDir, session) {
211
211
  if (!g || typeof g !== "object")
212
212
  continue;
213
213
  const gr = g;
214
- if (!gr.date || !gr.slot)
214
+ if (!gr.date || !gr.uid || !gr.titre)
215
215
  continue;
216
- if (!Array.isArray(gr.reunions))
217
- gr.reunions = [];
216
+ if (!Array.isArray(gr.events))
217
+ gr.events = [];
218
218
  yield { item: gr };
219
219
  }
220
220
  }
@@ -259,7 +259,7 @@ async function linkCriSlotIntoAgendaGrouped(dataDir, yyyymmdd, slot, crUid, cr,
259
259
  captationVideo: false,
260
260
  titre: dTitre,
261
261
  objet: dObjet || "",
262
- reunions: [],
262
+ events: [],
263
263
  compteRenduRefUid: crUid,
264
264
  };
265
265
  groups.push(newGroup);
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Needs to be run after retrieve_agenda.ts !
3
+ * - downloads the ZIP of comptes-rendus des débats (CRI) from data.senat.fr
4
+ * - extracts XML files, distributes them by session/year
5
+ */
6
+ export {};
@@ -0,0 +1,273 @@
1
+ /**
2
+ * Needs to be run after retrieve_agenda.ts !
3
+ * - downloads the ZIP of comptes-rendus des débats (CRI) from data.senat.fr
4
+ * - extracts XML files, distributes them by session/year
5
+ */
6
+ import assert from "assert";
7
+ import commandLineArgs from "command-line-args";
8
+ import fs from "fs-extra";
9
+ import path from "path";
10
+ import StreamZip from "node-stream-zip";
11
+ import * as cheerio from "cheerio";
12
+ import { AGENDA_FOLDER, COMPTES_RENDUS_FOLDER, DATA_ORIGINAL_FOLDER, DATA_TRANSFORMED_FOLDER, } from "../loaders";
13
+ import { commonOptions } from "./shared/cli_helpers";
14
+ import { deriveTitreObjetFromSommaire, parseCompteRenduSlotFromFile, parseYYYYMMDD, sessionStartYearFromDate } from "../model/compte_rendu";
15
+ import { makeGroupUid } from "../utils/reunion_grouping";
16
+ import { getSessionsFromStart } from "../types/sessions";
17
+ import { ensureAndClearDir, fetchWithRetry } from "./shared/util";
18
+ import { computeIntervalsBySlot } from "../utils/cr_spliting";
19
+ const optionsDefinitions = [
20
+ ...commonOptions,
21
+ {
22
+ help: "parse and convert comptes-rendus des débats into JSON",
23
+ name: "parseDebats",
24
+ type: Boolean,
25
+ }
26
+ ];
27
+ const options = commandLineArgs(optionsDefinitions);
28
+ const CRI_ZIP_URL = "https://data.senat.fr/data/debats/cri.zip";
29
+ const SLOT_ORDER = ["MATIN", "APRES-MIDI", "SOIR"];
30
+ class CompteRenduError extends Error {
31
+ constructor(message, url) {
32
+ super(`An error occurred while retrieving ${url}: ${message}`);
33
+ }
34
+ }
35
+ function pickFirstSlotOfDay(slots) {
36
+ for (const s of SLOT_ORDER)
37
+ if (slots.includes(s))
38
+ return s;
39
+ return null;
40
+ }
41
+ function loadAgendaSPSlotsForDate(dataDir, yyyymmdd, session) {
42
+ const dirPath = path.join(dataDir, AGENDA_FOLDER, DATA_TRANSFORMED_FOLDER, session.toString());
43
+ if (!fs.existsSync(dirPath)) {
44
+ console.warn(`[AGENDA] Directory not found for session ${session} → ${dirPath}`);
45
+ return null;
46
+ }
47
+ const pattern = new RegExp(`^RUSN${yyyymmdd}IDS-(MATIN|APRES-MIDI|SOIR)\\.json$`);
48
+ const ALLOWED_SLOTS = new Set(["MATIN", "APRES-MIDI", "SOIR"]);
49
+ try {
50
+ const files = fs.readdirSync(dirPath);
51
+ const matched = files.filter((f) => pattern.test(f));
52
+ if (matched.length === 0) {
53
+ return null;
54
+ }
55
+ const found = new Set();
56
+ for (const name of matched) {
57
+ const m = name.match(pattern);
58
+ const raw = (m?.[1] ?? "");
59
+ if (ALLOWED_SLOTS.has(raw))
60
+ found.add(raw);
61
+ }
62
+ const slots = Array.from(found);
63
+ if (slots.length === 0) {
64
+ return null;
65
+ }
66
+ return { filePath: dirPath, slots };
67
+ }
68
+ catch {
69
+ return null;
70
+ }
71
+ }
72
+ async function downloadCriZip(zipPath) {
73
+ if (!options["silent"])
74
+ console.log(`Downloading CRI zip ${CRI_ZIP_URL}…`);
75
+ const response = await fetchWithRetry(CRI_ZIP_URL);
76
+ if (!response.ok) {
77
+ if (response.status === 404) {
78
+ console.warn(`CRI zip ${CRI_ZIP_URL} not found`);
79
+ return;
80
+ }
81
+ throw new CompteRenduError(String(response.status), CRI_ZIP_URL);
82
+ }
83
+ const buf = Buffer.from(await response.arrayBuffer());
84
+ await fs.writeFile(zipPath, buf);
85
+ if (!options["silent"]) {
86
+ const mb = (buf.length / (1024 * 1024)).toFixed(1);
87
+ console.log(`[CRI] Downloaded ${mb} MB → ${zipPath}`);
88
+ }
89
+ }
90
+ async function extractAndDistributeXmlBySession(zipPath, originalRoot) {
91
+ const zip = new StreamZip.async({ file: zipPath });
92
+ const entries = await zip.entries();
93
+ let count = 0;
94
+ for (const entryName of Object.keys(entries)) {
95
+ if (!entryName.toLowerCase().endsWith(".xml"))
96
+ continue;
97
+ // ex: d20231005.xml
98
+ const base = path.basename(entryName);
99
+ const m = base.match(/^d(\d{8})\.xml$/i);
100
+ if (!m)
101
+ continue;
102
+ const yyyymmdd = m[1];
103
+ const dt = parseYYYYMMDD(yyyymmdd);
104
+ if (!dt)
105
+ continue;
106
+ const session = sessionStartYearFromDate(dt);
107
+ const destDir = path.join(originalRoot, String(session));
108
+ await fs.ensureDir(destDir);
109
+ const outPath = path.join(destDir, base);
110
+ await zip.extract(entryName, outPath);
111
+ count++;
112
+ }
113
+ await zip.close();
114
+ return count;
115
+ }
116
+ async function linkCriSlotIntoAgendaGrouped(dataDir, yyyymmdd, slot, crUid, cr, session) {
117
+ const groupedDir = path.join(dataDir, AGENDA_FOLDER, DATA_TRANSFORMED_FOLDER, session.toString());
118
+ fs.ensureDirSync(groupedDir);
119
+ const groupedPath = path.join(groupedDir, 'RUSN' + yyyymmdd + 'IDS-' + slot + '.json');
120
+ let groups = [];
121
+ if (fs.existsSync(groupedPath)) {
122
+ try {
123
+ groups = JSON.parse(fs.readFileSync(groupedPath, "utf8"));
124
+ if (!Array.isArray(groups))
125
+ groups = [];
126
+ }
127
+ catch (e) {
128
+ console.warn(`[AGENDA] unreadable grouped JSON → ${groupedPath} (${e}) → recreating`);
129
+ groups = [];
130
+ }
131
+ }
132
+ // find existing group with same slot
133
+ const sameSlot = groups.filter(g => g?.slot === slot);
134
+ let target = null;
135
+ if (sameSlot.length > 1) {
136
+ console.warn(`[AGENDA] multiple groups for ${yyyymmdd} ${slot} in ${groupedPath} → linking the first`);
137
+ }
138
+ target = sameSlot[0] ?? null;
139
+ const dateISO = `${yyyymmdd.slice(0, 4)}-${yyyymmdd.slice(4, 6)}-${yyyymmdd.slice(6, 8)}`;
140
+ const sommaire = cr?.metadonnees?.sommaire;
141
+ const { titre: dTitre, objet: dObjet } = deriveTitreObjetFromSommaire(sommaire, slot);
142
+ if (!target) {
143
+ const newGroup = {
144
+ uid: makeGroupUid(dateISO, slot),
145
+ chambre: "SN",
146
+ date: dateISO,
147
+ slot,
148
+ type: "Séance publique",
149
+ startTime: null,
150
+ endTime: null,
151
+ captationVideo: false,
152
+ titre: dTitre,
153
+ objet: dObjet || "",
154
+ events: [],
155
+ compteRenduRefUid: crUid,
156
+ };
157
+ groups.push(newGroup);
158
+ }
159
+ else {
160
+ target.compteRenduRefUid = crUid;
161
+ }
162
+ await fs.writeJSON(groupedPath, groups, { spaces: 2 });
163
+ console.log(`[AGENDA] Linked CR ${crUid} → ${path.basename(groupedPath)} [${slot}]`);
164
+ }
165
+ async function retrieveCriXmlDump(dataDir, options = {}) {
166
+ const root = path.join(dataDir, COMPTES_RENDUS_FOLDER);
167
+ ensureAndClearDir(root);
168
+ const originalRoot = path.join(root, DATA_ORIGINAL_FOLDER);
169
+ fs.ensureDirSync(originalRoot);
170
+ const transformedRoot = path.join(root, DATA_TRANSFORMED_FOLDER);
171
+ if (options["parseDebats"])
172
+ fs.ensureDirSync(transformedRoot);
173
+ const sessions = getSessionsFromStart(options["fromSession"]);
174
+ // 1) Download ZIP global + distribut by session
175
+ const zipPath = path.join(dataDir, "cri.zip");
176
+ console.log("[CRI] Downloading global CRI zip…");
177
+ await downloadCriZip(zipPath);
178
+ console.log("[CRI] Extracting + distributing XMLs by session…");
179
+ for (const session of sessions) {
180
+ const dir = path.join(originalRoot, String(session));
181
+ if (await fs.pathExists(dir)) {
182
+ for (const f of await fs.readdir(dir))
183
+ if (/\.xml$/i.test(f))
184
+ await fs.remove(path.join(dir, f));
185
+ }
186
+ }
187
+ const n = await extractAndDistributeXmlBySession(zipPath, originalRoot);
188
+ if (n === 0) {
189
+ console.warn("[CRI] No XML extracted. Archive empty or layout changed?");
190
+ }
191
+ else {
192
+ console.log(`[CRI] Distributed ${n} XML file(s) into session folders.`);
193
+ }
194
+ if (!options["parseDebats"]) {
195
+ console.log("[CRI] parseDebats not requested → done.");
196
+ return;
197
+ }
198
+ for (const session of sessions) {
199
+ const originalSessionDir = path.join(originalRoot, String(session));
200
+ if (!(await fs.pathExists(originalSessionDir))) {
201
+ continue;
202
+ }
203
+ const xmlFiles = (await fs.readdir(originalSessionDir))
204
+ .filter((f) => /^d\d{8}\.xml$/i.test(f))
205
+ .sort();
206
+ const transformedSessionDir = path.join(transformedRoot, String(session));
207
+ if (options["parseDebats"])
208
+ await fs.ensureDir(transformedSessionDir);
209
+ for (const f of xmlFiles) {
210
+ const yyyymmdd = f.slice(1, 9);
211
+ const xmlPath = path.join(originalSessionDir, f);
212
+ // 1) Deduce slot(s) from agenda if it exsits
213
+ // TODO: A updater car maintenant les agendas sont déjà enregistrés par slot et plus à la journée seulement
214
+ const agendaInfo = loadAgendaSPSlotsForDate(dataDir, yyyymmdd, session);
215
+ const firstSlotOfDay = pickFirstSlotOfDay(agendaInfo?.slots ?? []);
216
+ // 2) Detect slots from CRI content
217
+ let slotsInCri = [];
218
+ try {
219
+ const raw = await fs.readFile(xmlPath, "utf8");
220
+ const $ = cheerio.load(raw, { xml: false });
221
+ const order = $("body *").toArray();
222
+ const idx = new Map(order.map((el, i) => [el, i]));
223
+ const intervals = computeIntervalsBySlot($, idx, firstSlotOfDay ?? undefined);
224
+ const uniq = new Set();
225
+ for (const iv of intervals)
226
+ if (iv.slot && iv.slot !== "UNKNOWN")
227
+ uniq.add(iv.slot);
228
+ slotsInCri = Array.from(uniq);
229
+ }
230
+ catch (e) {
231
+ console.warn(`[CRI] [${session}] Cannot read/parse ${f}:`, e);
232
+ continue;
233
+ }
234
+ if (slotsInCri.length === 0) {
235
+ slotsInCri = [firstSlotOfDay ?? "MATIN"];
236
+ }
237
+ // 3) Parse & write each slot
238
+ for (const slot of slotsInCri) {
239
+ const outName = `CRSSN${yyyymmdd}-${slot}.json`;
240
+ const cr = await parseCompteRenduSlotFromFile(xmlPath, slot, firstSlotOfDay ?? slot);
241
+ if (!cr) {
242
+ console.warn(`[CRI] [${session}] Empty or no points for ${yyyymmdd} (${slot}) → skip`);
243
+ continue;
244
+ }
245
+ const outDir = transformedSessionDir;
246
+ await fs.ensureDir(outDir);
247
+ const outPath = path.join(outDir, outName);
248
+ await fs.writeJSON(outPath, cr, { spaces: 2 });
249
+ try {
250
+ await linkCriSlotIntoAgendaGrouped(dataDir, yyyymmdd, slot, cr.uid, cr, session);
251
+ }
252
+ catch (e) {
253
+ console.warn(`[AGENDA] [${session}] Could not link CR into grouped for ${yyyymmdd} ${slot}:`, e);
254
+ }
255
+ }
256
+ }
257
+ }
258
+ }
259
+ async function main() {
260
+ const dataDir = options["dataDir"];
261
+ assert(dataDir, "Missing argument: data directory");
262
+ console.time("CRI processing time");
263
+ await retrieveCriXmlDump(dataDir, options);
264
+ if (!options["silent"]) {
265
+ console.timeEnd("CRI processing time");
266
+ }
267
+ }
268
+ main()
269
+ .then(() => process.exit(0))
270
+ .catch((error) => {
271
+ console.error(error);
272
+ process.exit(1);
273
+ });
@@ -27,7 +27,7 @@ export interface GroupedReunion {
27
27
  organe?: string;
28
28
  objet?: string;
29
29
  lieu?: string;
30
- reunions: AgendaEvent[];
30
+ events: AgendaEvent[];
31
31
  compteRenduRefUid?: string;
32
32
  urlVideo?: string;
33
33
  timecodeDebutVideo?: number;
@@ -64,7 +64,7 @@ export function groupNonSPByTypeOrganeHour(events) {
64
64
  captationVideo: enriched.some(x => x.ev.captationVideo === true),
65
65
  titre: compactTitleList(enriched.map(x => x.ev.titre || "").filter(Boolean), 8),
66
66
  objet: joinObjets(enriched.map(x => x.ev)),
67
- reunions: enriched.map(x => x.ev),
67
+ events: enriched.map(x => x.ev),
68
68
  };
69
69
  out[suffix].push(group);
70
70
  }
@@ -142,7 +142,7 @@ export function groupSeancePubliqueBySlot(events) {
142
142
  captationVideo,
143
143
  titre: compactTitleList(titres, 5),
144
144
  objet: joinObjets(sorted.map((x) => x.ev)),
145
- reunions: sorted.map((x) => x.ev),
145
+ events: sorted.map((x) => x.ev),
146
146
  });
147
147
  }
148
148
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tricoteuses/senat",
3
- "version": "2.10.1",
3
+ "version": "2.10.2",
4
4
  "description": "Handle French Sénat's open data",
5
5
  "keywords": [
6
6
  "France",