Datasets:

License:
dcl-ibl-bas commited on
Commit
d4e676c
·
verified ·
1 Parent(s): a3d443c

Upload 2 files

Browse files
ifgpt-dataset-queries.cypher ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // ============================================================================
2
+ // IfGPT Dataset — Cypher queries
3
+ // Source: IfGPT search WordPress widget (https://ifgpt.dcl.bas.bg)
4
+ // Graph schema:
5
+ // (:Document)-[:LICENSED_WITH]->(:Licence)-[:HAS_LICENCE_CATEGORY]->(:LicenceCategory)
6
+ // (:Document)-[:BELONGS_TO]->(:Domain)
7
+ // (:Domain)-[:SUBCATEGORY_OF]->(:Domain)
8
+ // (:Document)-[:WRITTEN_BY]->(:Author)
9
+ // (:Document)-[:HAS_STYLE]->(:Style)
10
+ // (:Document)-[:HAS_TYPE]->(:Type)
11
+ // (:Document)-[:HAS_MEDIUM]->(:Medium)
12
+ // Document properties:
13
+ // Identifier, DocumentTitle, URL, PublicationDate, CollectionDate,
14
+ // LicenceLink, Subdomain, NumberParagraphs, NumberSentences,
15
+ // NumberWords, NumberTokens
16
+ // ============================================================================
17
+
18
+
19
+ // ----------------------------------------------------------------------------
20
+ // 1. Total document count (used in the header subtitle)
21
+ // ----------------------------------------------------------------------------
22
+ MATCH (m:Document)
23
+ RETURN count(m) AS total;
24
+
25
+
26
+ // ----------------------------------------------------------------------------
27
+ // 2. All licences (populates the Licence checkbox list)
28
+ // ----------------------------------------------------------------------------
29
+ MATCH (l:Licence)
30
+ RETURN l.Type AS licence
31
+ ORDER BY l.Type;
32
+
33
+
34
+ // ----------------------------------------------------------------------------
35
+ // 3. Top-level domains only (populates the Domain checkbox list)
36
+ // Excludes sub-domains that have a SUBCATEGORY_OF edge to a parent Domain.
37
+ // ----------------------------------------------------------------------------
38
+ MATCH (dom:Domain)
39
+ WHERE NOT (dom)-[:SUBCATEGORY_OF]->(:Domain)
40
+ RETURN dom.Name AS domain
41
+ ORDER BY domain;
42
+
43
+
44
+ // ----------------------------------------------------------------------------
45
+ // 4. Filtered search — total count
46
+ // Optional MATCH clauses and WHERE conditions are added by buildQuery().
47
+ // Parameters that may be passed in:
48
+ // $categories : ["free", "restricted"]
49
+ // $licences : ["CC-BY-SA-4.0", ...]
50
+ // $domains : ["POLITICS", ...]
51
+ // $dateFrom : "2010-01-01"
52
+ // $dateTo : "2020-12-31"
53
+ // $kw0..$kwN : keyword strings matched against DocumentTitle
54
+ // ----------------------------------------------------------------------------
55
+ MATCH (d:Document)
56
+ MATCH (d)-[:LICENSED_WITH]->(licCatNode:Licence)-[:HAS_LICENCE_CATEGORY]->(catNode:LicenceCategory)
57
+ MATCH (d)-[:LICENSED_WITH]->(licNode:Licence)
58
+ MATCH (d)-[:BELONGS_TO]->(domNode:Domain)
59
+ WHERE catNode.Name IN $categories
60
+ AND licNode.Type IN $licences
61
+ AND domNode.Name IN $domains
62
+ AND d.PublicationDate >= $dateFrom
63
+ AND d.PublicationDate <= $dateTo
64
+ AND (toLower(d.DocumentTitle) CONTAINS toLower($kw0)
65
+ OR toLower(d.DocumentTitle) CONTAINS toLower($kw1))
66
+ RETURN count(DISTINCT d) AS total;
67
+
68
+
69
+ // ----------------------------------------------------------------------------
70
+ // 5. Filtered search — sum of words
71
+ // Same WHERE as above, plus d.NumberWords IS NOT NULL.
72
+ // ----------------------------------------------------------------------------
73
+ MATCH (d:Document)
74
+ // ...same optional MATCH/WHERE clauses as query 4...
75
+ AND d.NumberWords IS NOT NULL
76
+ RETURN sum(d.NumberWords) AS total;
77
+
78
+
79
+ // ----------------------------------------------------------------------------
80
+ // 6. Paginated result page (20 docs per page) with all related entities
81
+ // $skip, $limit are Neo4j integers.
82
+ // ----------------------------------------------------------------------------
83
+ MATCH (d:Document)
84
+ // ...optional MATCH/WHERE clauses from buildQuery()...
85
+ WITH DISTINCT d
86
+ ORDER BY d.DocumentTitle
87
+ SKIP $skip LIMIT $limit
88
+ OPTIONAL MATCH (d)-[:WRITTEN_BY]->(aN:Author)
89
+ OPTIONAL MATCH (d)-[:BELONGS_TO]->(dN:Domain)
90
+ OPTIONAL MATCH (d)-[:LICENSED_WITH]->(lN:Licence)
91
+ OPTIONAL MATCH (d)-[:HAS_STYLE]->(sN:Style)
92
+ OPTIONAL MATCH (d)-[:HAS_TYPE]->(tN:Type)
93
+ OPTIONAL MATCH (d)-[:HAS_MEDIUM]->(mN:Medium)
94
+ WITH d,
95
+ collect(DISTINCT aN.Name) AS authors,
96
+ collect(DISTINCT dN.Name) AS domains,
97
+ collect(DISTINCT lN.Type) AS licences,
98
+ collect(DISTINCT sN.Name) AS styles,
99
+ collect(DISTINCT tN.Name) AS types,
100
+ collect(DISTINCT mN.Name) AS mediums
101
+ RETURN d.Identifier AS id,
102
+ d.DocumentTitle AS title,
103
+ authors,
104
+ domains,
105
+ licences,
106
+ styles,
107
+ types,
108
+ d.PublicationDate AS pubDate,
109
+ d.URL AS url,
110
+ d.NumberParagraphs AS paragraphs,
111
+ d.NumberSentences AS sentences,
112
+ d.NumberWords AS words,
113
+ mediums;
114
+
115
+
116
+ // ----------------------------------------------------------------------------
117
+ // 7. Full export query (same shape as #6 but called in batches of 200)
118
+ // Use without LIMIT/SKIP to fetch everything, or iterate as in JS code.
119
+ // ----------------------------------------------------------------------------
120
+ MATCH (d:Document)
121
+ WITH DISTINCT d
122
+ ORDER BY d.DocumentTitle
123
+ OPTIONAL MATCH (d)-[:WRITTEN_BY]->(aN:Author)
124
+ OPTIONAL MATCH (d)-[:BELONGS_TO]->(dN:Domain)
125
+ OPTIONAL MATCH (d)-[:LICENSED_WITH]->(lN:Licence)
126
+ OPTIONAL MATCH (d)-[:HAS_STYLE]->(sN:Style)
127
+ OPTIONAL MATCH (d)-[:HAS_TYPE]->(tN:Type)
128
+ OPTIONAL MATCH (d)-[:HAS_MEDIUM]->(mN:Medium)
129
+ RETURN d.Identifier AS id,
130
+ d.DocumentTitle AS title,
131
+ collect(DISTINCT aN.Name) AS authors,
132
+ collect(DISTINCT dN.Name) AS domains,
133
+ collect(DISTINCT lN.Type) AS licences,
134
+ collect(DISTINCT sN.Name) AS styles,
135
+ collect(DISTINCT tN.Name) AS types,
136
+ d.PublicationDate AS pubDate,
137
+ d.URL AS url,
138
+ d.NumberParagraphs AS paragraphs,
139
+ d.NumberSentences AS sentences,
140
+ d.NumberWords AS words,
141
+ collect(DISTINCT mN.Name) AS mediums;
ifgpt-dataset-search.js ADDED
@@ -0,0 +1,600 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* ============================================================================
2
+ * IfGPT Dataset — Neo4j search & extraction logic
3
+ * Extracted and cleaned from the IfGPT WordPress widget.
4
+ *
5
+ * Requires neo4j-driver (browser build):
6
+ * https://cdn.jsdelivr.net/npm/neo4j-driver@5.14.0/lib/browser/neo4j-web.min.js
7
+ *
8
+ * Public API (window.IfGPTSearch):
9
+ * - search() : run a filtered search using current form state
10
+ * - downloadJSON() : export the full result set as JSON (batched 200/page)
11
+ * - clearForm() : reset all filters
12
+ * - selectAll(p) : tick every checkbox whose id starts with `p`
13
+ * - clearAll(p) : untick every checkbox whose id starts with `p`
14
+ * ========================================================================== */
15
+
16
+ (function () {
17
+ if (window.IfGPTSearch) return;
18
+ window.IfGPTSearch = {};
19
+
20
+ // --- Config ---------------------------------------------------------------
21
+ const cfg = {
22
+ uri: 'neo4j+s://8fab59d8.databases.neo4j.io',
23
+ user: 'neo4j',
24
+ password: 'HPa7HpbVTKwadDVkSZbbjvb5-5gxJPaAgWIP68xbcbk',
25
+ };
26
+
27
+ // --- State ----------------------------------------------------------------
28
+ let driver = null;
29
+ let currentPage = 1;
30
+ const pageSize = 20;
31
+ let totalRecords = 0;
32
+ let totalWords = 0;
33
+
34
+ // --- DOM helpers ----------------------------------------------------------
35
+ const el = (id) => document.getElementById(id);
36
+ const txt = (id, t) => { const e = el(id); if (e) e.textContent = t; };
37
+ const status = (msg, type) => {
38
+ const s = el('ifgpt-status');
39
+ if (!s) return;
40
+ s.className = 'status status-' + type;
41
+ s.textContent = msg;
42
+ s.style.display = 'block';
43
+ };
44
+
45
+ // --- Checkbox utilities ---------------------------------------------------
46
+ IfGPTSearch.selectAll = (prefix) => {
47
+ document.querySelectorAll('input[id^="' + prefix + '"]')
48
+ .forEach((cb) => { cb.checked = true; });
49
+ };
50
+ IfGPTSearch.clearAll = (prefix) => {
51
+ document.querySelectorAll('input[id^="' + prefix + '"]')
52
+ .forEach((cb) => { cb.checked = false; });
53
+ };
54
+ const getSelected = (prefix) =>
55
+ Array.from(document.querySelectorAll('input[id^="' + prefix + '"]:checked'))
56
+ .map((cb) => cb.value);
57
+
58
+ // --- Connect & bootstrap --------------------------------------------------
59
+ async function connect() {
60
+ try {
61
+ status('Свързване...', 'info');
62
+ driver = neo4j.driver(cfg.uri, neo4j.auth.basic(cfg.user, cfg.password));
63
+ await driver.verifyConnectivity();
64
+ status('Свързано!', 'success');
65
+
66
+ await loadTotal();
67
+ await Promise.all([loadLicences(), loadDomains()]);
68
+
69
+ status('Готово', 'success');
70
+ setTimeout(() => { el('ifgpt-status').style.display = 'none'; }, 2000);
71
+ } catch (e) {
72
+ status('Грешка: ' + e.message, 'error');
73
+ console.error(e);
74
+ }
75
+ }
76
+
77
+ async function loadTotal() {
78
+ const s = driver.session({ defaultAccessMode: neo4j.session.READ });
79
+ try {
80
+ const r = await s.run('MATCH (m:Document) RETURN count(m) AS total');
81
+ const t = r.records[0].get('total').toNumber();
82
+ txt('ifgpt-subtitle', 'Търсене в ' + t.toLocaleString() + ' документа');
83
+ } finally {
84
+ await s.close();
85
+ }
86
+ }
87
+
88
+ async function loadLicences() {
89
+ const s = driver.session({ defaultAccessMode: neo4j.session.READ });
90
+ try {
91
+ const r = await s.run(
92
+ 'MATCH (l:Licence) RETURN l.Type AS licence ORDER BY l.Type'
93
+ );
94
+ renderCheckboxes(
95
+ el('ifgpt-licenseCheckboxes'),
96
+ r.records.map((rec) => rec.get('licence')),
97
+ 'lic-'
98
+ );
99
+ } finally {
100
+ await s.close();
101
+ }
102
+ }
103
+
104
+ async function loadDomains() {
105
+ const s = driver.session({ defaultAccessMode: neo4j.session.READ });
106
+ try {
107
+ const r = await s.run(
108
+ 'MATCH (dom:Domain) ' +
109
+ 'WHERE NOT (dom)-[:SUBCATEGORY_OF]->(:Domain) ' +
110
+ 'RETURN dom.Name AS domain ORDER BY domain'
111
+ );
112
+ renderCheckboxes(
113
+ el('ifgpt-domainCheckboxes'),
114
+ r.records.map((rec) => rec.get('domain')),
115
+ 'dom-'
116
+ );
117
+ } finally {
118
+ await s.close();
119
+ }
120
+ }
121
+
122
+ function renderCheckboxes(container, values, idPrefix) {
123
+ container.innerHTML = '';
124
+ values.forEach((val, i) => {
125
+ const d = document.createElement('div');
126
+ d.className = 'checkbox-item';
127
+ const cb = document.createElement('input');
128
+ cb.type = 'checkbox';
129
+ cb.id = idPrefix + i;
130
+ cb.value = val;
131
+ const lbl = document.createElement('label');
132
+ lbl.setAttribute('for', idPrefix + i);
133
+ lbl.textContent = val;
134
+ d.appendChild(cb);
135
+ d.appendChild(lbl);
136
+ container.appendChild(d);
137
+ });
138
+ }
139
+
140
+ // --- Dynamic query builder ------------------------------------------------
141
+ //
142
+ // Returns { matchClause, whereClause, params } based on the current state
143
+ // of the filter form.
144
+ //
145
+ function buildQuery() {
146
+ const cats = getSelected('cat-');
147
+ const lics = getSelected('lic-');
148
+ const doms = getSelected('dom-');
149
+ const yFrom = el('ifgpt-yearFrom').value;
150
+ const yTo = el('ifgpt-yearTo').value;
151
+ const kw = el('ifgpt-keywords').value.trim();
152
+
153
+ let matchClause = 'MATCH (d:Document)';
154
+ const where = [];
155
+ const params = {};
156
+
157
+ if (cats.length > 0) {
158
+ matchClause +=
159
+ ' MATCH (d)-[:LICENSED_WITH]->(licCatNode:Licence)' +
160
+ '-[:HAS_LICENCE_CATEGORY]->(catNode:LicenceCategory)';
161
+ where.push('catNode.Name IN $categories');
162
+ params.categories = cats;
163
+ }
164
+ if (lics.length > 0) {
165
+ matchClause += ' MATCH (d)-[:LICENSED_WITH]->(licNode:Licence)';
166
+ where.push('licNode.Type IN $licences');
167
+ params.licences = lics;
168
+ }
169
+ if (doms.length > 0) {
170
+ matchClause += ' MATCH (d)-[:BELONGS_TO]->(domNode:Domain)';
171
+ where.push('domNode.Name IN $domains');
172
+ params.domains = doms;
173
+ }
174
+ if (yFrom) {
175
+ where.push('d.PublicationDate >= $dateFrom');
176
+ params.dateFrom = yFrom + '-01-01';
177
+ }
178
+ if (yTo) {
179
+ where.push('d.PublicationDate <= $dateTo');
180
+ params.dateTo = yTo + '-12-31';
181
+ }
182
+ if (kw) {
183
+ const list = kw.split(',').map((k) => k.trim()).filter(Boolean);
184
+ if (list.length > 0) {
185
+ const cond = list
186
+ .map((_, i) => 'toLower(d.DocumentTitle) CONTAINS toLower($kw' + i + ')')
187
+ .join(' OR ');
188
+ where.push('(' + cond + ')');
189
+ list.forEach((k, i) => { params['kw' + i] = k; });
190
+ }
191
+ }
192
+
193
+ const whereClause = where.length > 0 ? ' WHERE ' + where.join(' AND ') : '';
194
+ return { mc: matchClause, wc: whereClause, p: params };
195
+ }
196
+
197
+ // --- Stats (count + sum of words) ----------------------------------------
198
+ async function getStats() {
199
+ const q = buildQuery();
200
+ const s = driver.session({ defaultAccessMode: neo4j.session.READ });
201
+ try {
202
+ const cr = await s.run(
203
+ q.mc + q.wc + ' RETURN count(DISTINCT d) AS total',
204
+ q.p
205
+ );
206
+ totalRecords = cr.records[0].get('total').toNumber();
207
+
208
+ const wr = await s.run(
209
+ q.mc + q.wc +
210
+ (q.wc ? ' AND ' : ' WHERE ') +
211
+ 'd.NumberWords IS NOT NULL RETURN sum(d.NumberWords) AS total',
212
+ q.p
213
+ );
214
+ const wv = wr.records[0].get('total');
215
+ totalWords = wv ? wv.toNumber() : 0;
216
+
217
+ txt('ifgpt-totalDocs', totalRecords.toLocaleString());
218
+ txt('ifgpt-totalWords', totalWords.toLocaleString());
219
+ } catch (e) {
220
+ console.error('Stats error:', e);
221
+ txt('ifgpt-totalDocs', 'Грешка');
222
+ txt('ifgpt-totalWords', 'Грешка');
223
+ } finally {
224
+ await s.close();
225
+ }
226
+ }
227
+
228
+ // --- Paginated page query -------------------------------------------------
229
+ //
230
+ // The big query: 20 documents, with all related entities (Author, Domain,
231
+ // Licence, Style, Type, Medium) collected into arrays.
232
+ //
233
+ const PAGE_RETURN_TAIL =
234
+ ' WITH DISTINCT d ' +
235
+ 'ORDER BY d.DocumentTitle SKIP $skip LIMIT $limit ' +
236
+ 'OPTIONAL MATCH (d)-[:WRITTEN_BY]->(aN:Author) ' +
237
+ 'OPTIONAL MATCH (d)-[:BELONGS_TO]->(dN:Domain) ' +
238
+ 'OPTIONAL MATCH (d)-[:LICENSED_WITH]->(lN:Licence) ' +
239
+ 'OPTIONAL MATCH (d)-[:HAS_STYLE]->(sN:Style) ' +
240
+ 'OPTIONAL MATCH (d)-[:HAS_TYPE]->(tN:Type) ' +
241
+ 'OPTIONAL MATCH (d)-[:HAS_MEDIUM]->(mN:Medium) ' +
242
+ 'WITH d, ' +
243
+ ' collect(DISTINCT aN.Name) AS authors, ' +
244
+ ' collect(DISTINCT dN.Name) AS domains, ' +
245
+ ' collect(DISTINCT lN.Type) AS licences, ' +
246
+ ' collect(DISTINCT sN.Name) AS styles, ' +
247
+ ' collect(DISTINCT tN.Name) AS types, ' +
248
+ ' collect(DISTINCT mN.Name) AS mediums ' +
249
+ 'RETURN d.Identifier AS id, d.DocumentTitle AS title, ' +
250
+ ' authors, domains, licences, styles, types, ' +
251
+ ' d.PublicationDate AS pubDate, d.URL AS url, ' +
252
+ ' d.NumberParagraphs AS paragraphs, d.NumberSentences AS sentences, ' +
253
+ ' d.NumberWords AS words, mediums';
254
+
255
+ async function loadPage(pg) {
256
+ const q = buildQuery();
257
+ q.p.skip = neo4j.int((pg - 1) * pageSize);
258
+ q.p.limit = neo4j.int(pageSize);
259
+
260
+ const s = driver.session({ defaultAccessMode: neo4j.session.READ });
261
+ try {
262
+ const r = await s.run(q.mc + q.wc + PAGE_RETURN_TAIL, q.p);
263
+ currentPage = pg;
264
+ txt('ifgpt-currentPage', pg);
265
+ showResults(r.records);
266
+ makePagination();
267
+ } catch (e) {
268
+ console.error('Page load error:', e);
269
+ txt('ifgpt-resultsList', 'Грешка при зареждане: ' + e.message);
270
+ } finally {
271
+ await s.close();
272
+ }
273
+ }
274
+
275
+ // --- Result rendering -----------------------------------------------------
276
+ function showResults(recs) {
277
+ const c = el('ifgpt-resultsList');
278
+ if (recs.length === 0) { c.innerHTML = 'Няма резултати'; return; }
279
+ c.innerHTML = '';
280
+
281
+ recs.forEach((rec) => {
282
+ const card = document.createElement('div');
283
+ card.className = 'result-item';
284
+
285
+ const t = document.createElement('div');
286
+ t.className = 'result-title';
287
+ t.textContent = rec.get('title') || 'Без заглавие';
288
+ card.appendChild(t);
289
+
290
+ // Tag row: arrays of related-entity names + publication date
291
+ const m = document.createElement('div');
292
+ m.className = 'result-meta';
293
+ ['authors', 'domains', 'licences', 'styles', 'types', 'mediums'].forEach((f) => {
294
+ try {
295
+ const v = rec.get(f);
296
+ if (Array.isArray(v)) {
297
+ v.forEach((vv) => {
298
+ if (vv) {
299
+ const tg = document.createElement('span');
300
+ tg.className = 'result-tag';
301
+ tg.textContent = vv;
302
+ m.appendChild(tg);
303
+ }
304
+ });
305
+ }
306
+ } catch (err) { console.log('Field ' + f + ' error:', err); }
307
+ });
308
+
309
+ try {
310
+ const pd = rec.get('pubDate');
311
+ if (pd && pd !== 'N/A') {
312
+ const dateStr = formatDate(pd);
313
+ if (dateStr) {
314
+ const tg = document.createElement('span');
315
+ tg.className = 'result-tag';
316
+ tg.textContent = dateStr;
317
+ m.appendChild(tg);
318
+ }
319
+ }
320
+ } catch (err) { console.log('Date error:', err); }
321
+ card.appendChild(m);
322
+
323
+ // Detail row: id, url, paragraphs, sentences, words
324
+ const det = document.createElement('div');
325
+ det.className = 'result-details';
326
+ const add = (lbl, val) => {
327
+ if (val === null || val === undefined) return;
328
+ const itm = document.createElement('div');
329
+ itm.className = 'detail-item';
330
+ const ls = document.createElement('span');
331
+ ls.className = 'detail-label';
332
+ ls.textContent = lbl + ': ';
333
+ itm.appendChild(ls);
334
+ if (typeof val === 'object') {
335
+ if (val.href) {
336
+ const lnk = document.createElement('a');
337
+ lnk.href = val.href;
338
+ lnk.target = '_blank';
339
+ lnk.textContent = val.text;
340
+ itm.appendChild(lnk);
341
+ } else {
342
+ const dv = val.toNumber ? val.toNumber() : val;
343
+ itm.appendChild(document.createTextNode(String(dv)));
344
+ }
345
+ } else {
346
+ itm.appendChild(document.createTextNode(String(val)));
347
+ }
348
+ det.appendChild(itm);
349
+ };
350
+
351
+ add('ID', rec.get('id'));
352
+ try {
353
+ const u = rec.get('url');
354
+ if (u) {
355
+ const cu = u.startsWith('file://') ? u.substring(u.indexOf('http')) : u;
356
+ if (cu && cu.startsWith('http')) add('URL', { href: cu, text: 'Виж' });
357
+ }
358
+ } catch (err) { /* ignore */ }
359
+ ['paragraphs', 'sentences', 'words'].forEach((f, i) => {
360
+ try {
361
+ const v = rec.get(f);
362
+ if (v !== null && v !== undefined) {
363
+ const label = ['Абзаци', 'Изречения', 'Думи'][i];
364
+ add(label, typeof v === 'object' ? (v.toNumber ? v.toNumber() : v) : v);
365
+ }
366
+ } catch (err) { /* ignore */ }
367
+ });
368
+
369
+ card.appendChild(det);
370
+ c.appendChild(card);
371
+ });
372
+ }
373
+
374
+ function formatDate(pd) {
375
+ let y, mo, d;
376
+ if (typeof pd === 'string') {
377
+ const parts = pd.split('-');
378
+ y = parseInt(parts[0]) || null;
379
+ mo = parseInt(parts[1]) || 1;
380
+ d = parseInt(parts[2]) || 1;
381
+ } else if (pd && pd.year) {
382
+ y = pd.year.toNumber ? pd.year.toNumber() : pd.year;
383
+ mo = pd.month ? (pd.month.toNumber ? pd.month.toNumber() : pd.month) : 1;
384
+ d = pd.day ? (pd.day.toNumber ? pd.day.toNumber() : pd.day) : 1;
385
+ }
386
+ if (!y) return null;
387
+ return y + '-' + String(mo).padStart(2, '0') + '-' + String(d).padStart(2, '0');
388
+ }
389
+
390
+ // --- Pagination -----------------------------------------------------------
391
+ function makePagination() {
392
+ const tp = Math.ceil(totalRecords / pageSize);
393
+ const top = el('ifgpt-topPagination');
394
+ const bot = el('ifgpt-bottomPagination');
395
+ top.innerHTML = '';
396
+ bot.innerHTML = '';
397
+ if (tp <= 1) return;
398
+
399
+ const build = (container) => {
400
+ const prev = document.createElement('button');
401
+ prev.className = 'page-btn';
402
+ prev.textContent = '← Пред.';
403
+ prev.disabled = currentPage === 1;
404
+ prev.onclick = () => { if (currentPage > 1) loadPage(currentPage - 1); };
405
+ container.appendChild(prev);
406
+
407
+ const start = Math.max(1, currentPage - 2);
408
+ const end = Math.min(tp, currentPage + 2);
409
+
410
+ if (start > 1) {
411
+ const fb = document.createElement('button');
412
+ fb.className = 'page-btn';
413
+ fb.textContent = '1';
414
+ fb.onclick = () => loadPage(1);
415
+ container.appendChild(fb);
416
+ if (start > 2) {
417
+ const sp = document.createElement('span');
418
+ sp.textContent = '...';
419
+ sp.style.padding = '8px';
420
+ container.appendChild(sp);
421
+ }
422
+ }
423
+ for (let i = start; i <= end; i++) {
424
+ ((n) => {
425
+ const btn = document.createElement('button');
426
+ btn.className = 'page-btn' + (n === currentPage ? ' active' : '');
427
+ btn.textContent = n;
428
+ btn.onclick = () => loadPage(n);
429
+ container.appendChild(btn);
430
+ })(i);
431
+ }
432
+ if (end < tp) {
433
+ if (end < tp - 1) {
434
+ const sp = document.createElement('span');
435
+ sp.textContent = '...';
436
+ sp.style.padding = '8px';
437
+ container.appendChild(sp);
438
+ }
439
+ const lb = document.createElement('button');
440
+ lb.className = 'page-btn';
441
+ lb.textContent = tp;
442
+ lb.onclick = () => loadPage(tp);
443
+ container.appendChild(lb);
444
+ }
445
+ const next = document.createElement('button');
446
+ next.className = 'page-btn';
447
+ next.textContent = 'След. →';
448
+ next.disabled = currentPage === tp;
449
+ next.onclick = () => { if (currentPage < tp) loadPage(currentPage + 1); };
450
+ container.appendChild(next);
451
+ };
452
+
453
+ build(top);
454
+ build(bot);
455
+ }
456
+
457
+ // --- Public actions -------------------------------------------------------
458
+
459
+ IfGPTSearch.search = async function () {
460
+ if (!driver) { alert('Няма връзка'); return; }
461
+ el('ifgpt-results').classList.remove('hidden');
462
+ txt('ifgpt-resultsList', 'Зареждане...');
463
+ const dlBtn = el('ifgpt-downloadBtn');
464
+ const dlInfo = el('ifgpt-downloadInfo');
465
+ if (dlBtn) dlBtn.disabled = true;
466
+ if (dlInfo) dlInfo.textContent = '';
467
+ try {
468
+ await getStats();
469
+ await loadPage(1);
470
+ if (dlBtn) dlBtn.disabled = false;
471
+ if (dlInfo) dlInfo.textContent = totalRecords.toLocaleString() + ' документа';
472
+ } catch (e) {
473
+ console.error(e);
474
+ txt('ifgpt-resultsList', 'Грешка: ' + e.message);
475
+ }
476
+ };
477
+
478
+ IfGPTSearch.downloadJSON = async function () {
479
+ if (!driver) { alert('Няма връзка'); return; }
480
+ const dlBtn = el('ifgpt-downloadBtn');
481
+ const dlInfo = el('ifgpt-downloadInfo');
482
+ dlBtn.disabled = true;
483
+ dlBtn.textContent = 'Зареждане...';
484
+ if (dlInfo) dlInfo.textContent =
485
+ 'Извличане на всички ' + totalRecords.toLocaleString() + ' записа...';
486
+
487
+ try {
488
+ const q = buildQuery();
489
+ const all = [];
490
+ const batchSize = 200;
491
+
492
+ for (let skip = 0; skip < totalRecords; skip += batchSize) {
493
+ const bp = Object.assign({}, q.p);
494
+ bp.skip = neo4j.int(skip);
495
+ bp.limit = neo4j.int(batchSize);
496
+
497
+ const s = driver.session({ defaultAccessMode: neo4j.session.READ });
498
+ let r;
499
+ try {
500
+ r = await s.run(q.mc + q.wc + PAGE_RETURN_TAIL, bp);
501
+ } finally {
502
+ await s.close();
503
+ }
504
+
505
+ r.records.forEach((rec) => {
506
+ const fv = (f) => {
507
+ try {
508
+ const v = rec.get(f);
509
+ if (v === null || v === undefined) return null;
510
+ if (typeof v === 'object' && v.toNumber) return v.toNumber();
511
+ return v;
512
+ } catch (e) { return null; }
513
+ };
514
+ let pd = null;
515
+ try {
516
+ const raw = rec.get('pubDate');
517
+ if (raw && raw !== 'N/A') pd = formatDate(raw);
518
+ } catch (e) { /* ignore */ }
519
+ let url = null;
520
+ try {
521
+ const u = fv('url');
522
+ if (u) url = u.startsWith('file://')
523
+ ? u.substring(u.indexOf('http'))
524
+ : u;
525
+ } catch (e) { /* ignore */ }
526
+ all.push({
527
+ id: fv('id'),
528
+ title: fv('title'),
529
+ authors: rec.get('authors'),
530
+ domains: rec.get('domains'),
531
+ licences: rec.get('licences'),
532
+ styles: rec.get('styles'),
533
+ types: rec.get('types'),
534
+ publicationDate: pd,
535
+ url: url,
536
+ paragraphs: fv('paragraphs'),
537
+ sentences: fv('sentences'),
538
+ words: fv('words'),
539
+ mediums: rec.get('mediums'),
540
+ });
541
+ });
542
+ }
543
+
544
+ const output = {
545
+ exportedAt: new Date().toISOString(),
546
+ totalDocuments: totalRecords,
547
+ totalWords: totalWords,
548
+ documents: all,
549
+ };
550
+ const blob = new Blob([JSON.stringify(output, null, 2)],
551
+ { type: 'application/json' });
552
+ const a = document.createElement('a');
553
+ a.href = URL.createObjectURL(blob);
554
+ a.download = 'metadata-' + new Date().toISOString().slice(0, 10) + '.json';
555
+ document.body.appendChild(a);
556
+ a.click();
557
+ document.body.removeChild(a);
558
+ URL.revokeObjectURL(a.href);
559
+ if (dlInfo) dlInfo.textContent = totalRecords.toLocaleString() + ' документа';
560
+ } catch (e) {
561
+ console.error('Download error:', e);
562
+ alert('Грешка при изтегляне: ' + e.message);
563
+ } finally {
564
+ dlBtn.disabled = false;
565
+ dlBtn.textContent = 'МЕТАДАННИ (json)';
566
+ }
567
+ };
568
+
569
+ IfGPTSearch.clearForm = function () {
570
+ document.querySelectorAll('input[type="checkbox"]')
571
+ .forEach((cb) => { cb.checked = false; });
572
+ el('ifgpt-yearFrom').value = '';
573
+ el('ifgpt-yearTo').value = '';
574
+ el('ifgpt-keywords').value = '';
575
+ el('ifgpt-results').classList.add('hidden');
576
+ const dlBtn = el('ifgpt-downloadBtn');
577
+ const dlInfo = el('ifgpt-downloadInfo');
578
+ if (dlBtn) dlBtn.disabled = true;
579
+ if (dlInfo) dlInfo.textContent = '';
580
+ };
581
+
582
+ // --- Bootstrap ------------------------------------------------------------
583
+ function loadNeo4j() {
584
+ if (window.neo4j) { connect(); return; }
585
+ const s = document.createElement('script');
586
+ s.src = 'https://cdn.jsdelivr.net/npm/neo4j-driver@5.14.0/lib/browser/neo4j-web.min.js';
587
+ s.onload = connect;
588
+ s.onerror = () => {
589
+ const st = el('ifgpt-status');
590
+ if (st) st.textContent = 'Грешка при зареждане';
591
+ };
592
+ document.head.appendChild(s);
593
+ }
594
+
595
+ if (document.readyState === 'loading') {
596
+ document.addEventListener('DOMContentLoaded', loadNeo4j);
597
+ } else {
598
+ loadNeo4j();
599
+ }
600
+ })();