-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
562 lines (480 loc) · 20.3 KB
/
Copy pathserver.py
File metadata and controls
562 lines (480 loc) · 20.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
#!/usr/bin/env python3
"""
server.py — LexFlow web server.
Usage:
pip install flask
python server.py # runs on http://localhost:5001
python server.py --port 8080
python server.py --cert cert.pem --key key.pem # HTTPS
"""
import sys
import os
import json
import logging
import threading
import time
import re
import uuid
import argparse
import requests as _requests
_HERE = os.path.dirname(os.path.abspath(__file__))
_CODE_DIR = os.path.join(_HERE, 'code')
_CLASSES_DIR = os.path.join(_CODE_DIR, 'classes')
for _d in (_CODE_DIR, _CLASSES_DIR):
if _d not in sys.path:
sys.path.insert(0, _d)
try:
from google import genai as _genai
except ImportError:
_genai = None
from LegislationSearch import LegislationSearch as _LegislationSearch
_legislation_search = _LegislationSearch()
try:
from flask import Flask, request, jsonify, Response, send_file, abort
except ImportError:
sys.exit("Flask is required: pip install flask")
from classes.Downloader import Downloader
import backend_handler as _pipeline
# ---------------------------------------------------------------------------
# App
# ---------------------------------------------------------------------------
app = Flask(__name__, static_folder=None)
BASE_URL = 'https://legislatie.just.ro/Public/DetaliiDocument/'
INPUT_DIR = os.path.join(_HERE, 'input')
OUTPUT_DIR = os.path.join(_HERE, 'output')
_jobs: dict = {}
_jobs_lock = threading.Lock()
def _safe_json(obj) -> str:
"""JSON-encode obj and escape </ so injected strings can't break a <script> block."""
return json.dumps(obj, ensure_ascii=False).replace('</', r'\u003c/')
def _esc_html(s: str) -> str:
return str(s).replace('&', '&').replace('<', '<').replace('>', '>').replace('"', '"')
_SUMMARY_HTML = r"""<!DOCTYPE html>
<html lang="ro">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Rezumat — __TITLE_HTML__</title>
<style>
* { box-sizing: border-box; margin: 0; padding: 0; }
body { font-family: Georgia, 'Times New Roman', serif; background: #fafaf8; color: #1a1a1a; min-height: 100vh; }
#topbar { position: sticky; top: 0; background: #fff; border-bottom: 1px solid #e0e0e0;
padding: 10px 24px; display: flex; align-items: center; gap: 12px;
box-shadow: 0 1px 4px rgba(0,0,0,.07); z-index: 10; }
#topbar h1 { font-size: 13px; font-family: Arial, sans-serif; font-weight: 700; flex: 1;
overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.tbtn { padding: 5px 13px; font-size: 12px; cursor: pointer; border: 1px solid #ccc;
border-radius: 4px; background: #f6f7f9; font-family: Arial, sans-serif; white-space: nowrap; }
.tbtn:hover { background: #e4e6ec; }
#content { max-width: 720px; margin: 0 auto; padding: 40px 24px 80px;
font-size: 15px; line-height: 1.8; }
#status { color: #888; font-style: italic; font-family: Arial, sans-serif;
font-size: 13px; margin-bottom: 12px; }
#summary-text { white-space: pre-wrap; }
.ai-cursor { display: inline-block; width: 2px; height: 1em; background: #1565c0;
vertical-align: text-bottom; animation: blink .8s step-end infinite; }
@keyframes blink { 50% { opacity: 0; } }
#error-msg { color: #c62828; font-family: Arial, sans-serif; font-size: 13px; margin-top: 12px; }
.badge { font-size: 11px; padding: 2px 8px; border-radius: 10px; font-family: Arial, sans-serif; }
.badge.cached { background: #dcfce7; color: #166534; }
.badge.live { background: #e8f0fe; color: #1565c0; }
@media print { #topbar { display: none; } #content { padding: 0; } }
</style>
</head>
<body>
<div id="topbar">
<h1 title="__TITLE_HTML__">Rezumat AI — __TITLE_HTML__</h1>
<span id="badge" class="badge live">Generare…</span>
<button class="tbtn" id="regen-btn" onclick="regenerate()" style="display:none">Regenerează</button>
<button class="tbtn" onclick="window.print()">Print</button>
<button class="tbtn" onclick="window.close()">Închide</button>
</div>
<div id="content">
<p id="status"></p>
<div id="summary-text"></div>
<div id="error-msg"></div>
</div>
<script>
var DOC_ID = '__DOC_ID__';
var CACHED = __CACHED_JSON__;
var TITLE = __TITLE_JSON__;
function showCached() {
document.getElementById('status').textContent = '';
document.getElementById('summary-text').textContent = CACHED;
document.getElementById('badge').className = 'badge cached';
document.getElementById('badge').textContent = 'Salvat local';
document.getElementById('regen-btn').style.display = '';
}
function regenerate() {
CACHED = null;
document.getElementById('regen-btn').style.display = 'none';
document.getElementById('badge').className = 'badge live';
document.getElementById('badge').textContent = 'Generare…';
document.getElementById('summary-text').textContent = '';
document.getElementById('error-msg').textContent = '';
startGenerate();
}
function startGenerate() {
var el = document.getElementById('summary-text');
var stat = document.getElementById('status');
stat.textContent = 'Se generează rezumatul…';
var cursor = document.createElement('span');
cursor.className = 'ai-cursor';
el.appendChild(cursor);
var accumulated = '';
fetch('/api/summarize', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ doc_id: DOC_ID, title: TITLE })
}).then(function(resp) {
if (!resp.ok) {
return resp.json().then(function(d) { throw new Error(d.error || resp.statusText); });
}
var reader = resp.body.getReader();
var decoder = new TextDecoder();
var buf = '';
function pump() {
reader.read().then(function(result) {
if (result.done) {
cursor.remove();
stat.textContent = '';
document.getElementById('badge').className = 'badge cached';
document.getElementById('badge').textContent = 'Salvat local';
document.getElementById('regen-btn').style.display = '';
return;
}
buf += decoder.decode(result.value, { stream: true });
var parts = buf.split('\n\n');
buf = parts.pop();
parts.forEach(function(part) {
if (!part.startsWith('data:')) return;
try {
var msg = JSON.parse(part.slice(5).trim());
if (msg.type === 'chunk') {
accumulated += msg.text;
el.textContent = accumulated;
el.appendChild(cursor);
window.scrollTo(0, document.body.scrollHeight);
} else if (msg.type === 'done') {
cursor.remove();
stat.textContent = '';
document.getElementById('badge').className = 'badge cached';
document.getElementById('badge').textContent = 'Salvat local';
document.getElementById('regen-btn').style.display = '';
} else if (msg.type === 'error') {
cursor.remove();
stat.textContent = '';
document.getElementById('error-msg').textContent = 'Eroare: ' + msg.text;
}
} catch(e) {}
});
pump();
}).catch(function(err) {
cursor.remove();
document.getElementById('error-msg').textContent = 'Eroare de conexiune: ' + String(err);
});
}
pump();
}).catch(function(err) {
document.getElementById('status').textContent = '';
document.getElementById('error-msg').textContent = 'Eroare: ' + String(err);
});
}
if (CACHED) {
showCached();
} else {
startGenerate();
}
</script>
</body>
</html>"""
# ---------------------------------------------------------------------------
# Log capture
# ---------------------------------------------------------------------------
class _JobLogHandler(logging.Handler):
"""Appends formatted log records from the owning thread to the job log."""
def __init__(self, job_id: str, thread_id: int):
super().__init__()
self.job_id = job_id
self.thread_id = thread_id
def emit(self, record: logging.LogRecord):
if threading.current_thread().ident != self.thread_id:
return
msg = self.format(record)
with _jobs_lock:
job = _jobs.get(self.job_id)
if job is not None:
job['log'].append(msg)
# ---------------------------------------------------------------------------
# Pipeline worker
# ---------------------------------------------------------------------------
def _extract_doc_id(text: str):
text = text.strip()
m = re.search(r'DetaliiDocument(?:Afis)?/(\d+)', text)
if m:
return m.group(1)
if re.fullmatch(r'\d+', text):
return text
return None
def _run_job(job_id: str, doc_id: str, depth: int = 1):
handler = _JobLogHandler(job_id, threading.current_thread().ident)
handler.setFormatter(logging.Formatter('[%(levelname)s] %(message)s'))
root = logging.getLogger()
root.addHandler(handler)
try:
os.makedirs(os.path.join(INPUT_DIR, doc_id), exist_ok=True)
Downloader(output_dir=INPUT_DIR).download(BASE_URL + doc_id)
html_path = os.path.join(INPUT_DIR, doc_id, 'index.html')
with open(html_path, encoding='utf-8') as f:
html = f.read()
_pipeline.create_view_tree(html, doc_id)
_pipeline.run_link_graph(doc_id, depth=depth, allow_download=True)
with _jobs_lock:
_jobs[job_id]['status'] = 'done'
except Exception as exc:
logging.error(f"Job {job_id} failed: {exc}")
with _jobs_lock:
_jobs[job_id]['status'] = 'error'
_jobs[job_id]['error'] = str(exc)
finally:
root.removeHandler(handler)
# ---------------------------------------------------------------------------
# Routes
# ---------------------------------------------------------------------------
@app.route('/')
def index():
return send_file(os.path.join(_HERE, 'web', 'index.html'))
@app.route('/generate', methods=['POST'])
def generate():
data = request.get_json(silent=True) or {}
raw = data.get('input', '').strip()
doc_id = _extract_doc_id(raw)
if not doc_id:
return jsonify({'error': 'URL sau ID invalid. Exemple: 103284 sau https://legislatie.just.ro/Public/DetaliiDocument/103284'}), 400
depth = min(max(int(data.get('depth', 1)), 1), 3)
job_id = uuid.uuid4().hex[:8]
with _jobs_lock:
_jobs[job_id] = {
'status': 'running',
'doc_id': doc_id,
'log': [],
'error': None,
}
t = threading.Thread(target=_run_job, args=(job_id, doc_id, depth), daemon=True)
t.start()
return jsonify({'job_id': job_id, 'doc_id': doc_id})
@app.route('/stream/<job_id>')
def stream(job_id: str):
with _jobs_lock:
if job_id not in _jobs:
abort(404)
def _events():
sent = 0
while True:
with _jobs_lock:
job = _jobs.get(job_id, {})
logs = job.get('log', [])
status = job.get('status', 'running')
error = job.get('error', '')
doc_id = job.get('doc_id', '')
new = logs[sent:]
for line in new:
yield f"data: {json.dumps({'type': 'log', 'text': line})}\n\n"
sent += len(new)
if status == 'done':
yield f"data: {json.dumps({'type': 'done', 'doc_id': doc_id})}\n\n"
return
if status == 'error':
yield f"data: {json.dumps({'type': 'error', 'text': error})}\n\n"
return
time.sleep(0.15)
return Response(
_events(),
mimetype='text/event-stream',
headers={'Cache-Control': 'no-cache', 'X-Accel-Buffering': 'no'},
)
@app.route('/graph/<doc_id>')
def graph(doc_id: str):
if not re.fullmatch(r'\d+', doc_id):
abort(400)
path = os.path.join(OUTPUT_DIR, doc_id, 'link_graph.html')
if not os.path.exists(path):
abort(404, description=f'Graful pentru documentul {doc_id} nu a fost generat încă.')
return send_file(os.path.abspath(path))
@app.route('/api/search')
def api_search():
q = request.args.get('q', '').strip()
tipdoc = request.args.get('type', '').strip()
year = request.args.get('year', '').strip()
if len(q) < 2:
return jsonify([])
if tipdoc in {'5', '17'}:
return jsonify([])
try:
results = _legislation_search.search(
title=q,
doc_type=tipdoc,
year=year,
)
except Exception as exc:
return jsonify({'error': str(exc)}), 502
return jsonify(results)
def _extract_article_text(law_text: str, article_title: str) -> str:
"""Extract a single article's text from the full law text by its title line."""
art_re = re.compile(r'^Articolul\s+\S+', re.IGNORECASE)
lines = law_text.split('\n')
collecting = False
result: list[str] = []
for line in lines:
stripped = line.strip()
if art_re.match(stripped):
if stripped == article_title:
collecting = True
result = [line]
elif collecting:
break
elif collecting:
result.append(line)
return '\n'.join(result)
@app.route('/api/summarize', methods=['POST'])
def api_summarize():
if _genai is None:
return jsonify({'error': 'Pachetul google-genai nu este instalat: pip install google-genai'}), 501
data = request.get_json(silent=True) or {}
doc_id = data.get('doc_id', '').strip()
article_title = data.get('article_title', '').strip()
title = data.get('title', 'Document legislativ').strip()
if not doc_id:
return jsonify({'error': 'doc_id este necesar'}), 400
if not re.fullmatch(r'\d+', doc_id):
return jsonify({'error': 'doc_id invalid'}), 400
law_path = os.path.join(OUTPUT_DIR, doc_id, 'complete_law.txt')
if not os.path.exists(law_path):
try:
from CompleteLawGenerator import generate as _gen_law
law_text = _gen_law(doc_id)
os.makedirs(os.path.dirname(law_path), exist_ok=True)
with open(law_path, 'w', encoding='utf-8') as f:
f.write(law_text)
except Exception as exc:
return jsonify({'error': f'Nu s-a putut genera textul legii: {exc}'}), 500
else:
with open(law_path, encoding='utf-8') as f:
law_text = f.read()
if article_title:
law_text = _extract_article_text(law_text, article_title)
if not law_text:
return jsonify({'error': f'Articolul "{article_title}" nu a fost găsit în document'}), 404
MAX_CHARS = 60_000
if len(law_text) > MAX_CHARS:
law_text = law_text[:MAX_CHARS] + '\n\n[Textul a fost trunchiat din cauza dimensiunii mari...]'
api_key = os.environ.get('GEMINI_API_KEY', '').strip()
if not api_key:
return jsonify({'error': 'GEMINI_API_KEY nu este setat. Exportați variabila de mediu înainte de a porni serverul.'}), 503
prompt = (
f'Ești un expert juridic care explică legislația română pe înțelesul tuturor.\n\n'
f'Documentul următor este: "{title}".\n\n'
f'Generează un rezumat clar, structurat și ușor de înțeles în română, care să acopere:\n'
f'1. Scopul și contextul documentului\n'
f'2. Principalele drepturi și obligații stabilite\n'
f'3. Sancțiunile prevăzute (dacă există)\n'
f'4. Aspectele practice importante pentru cetățeni\n\n'
f'Textul documentului:\n{law_text}\n\n'
f'Răspunde direct cu rezumatul, fără introducere sau meta-comentarii:'
)
def _stream():
accumulated: list = []
try:
client = _genai.Client(api_key=api_key)
for chunk in client.models.generate_content_stream(
model='gemini-3.1-flash-lite',
contents=prompt,
):
if chunk.text:
accumulated.append(chunk.text)
yield f"data: {json.dumps({'type': 'chunk', 'text': chunk.text})}\n\n"
if doc_id and accumulated:
try:
summary_path = os.path.join(OUTPUT_DIR, doc_id, 'summary.txt')
os.makedirs(os.path.dirname(summary_path), exist_ok=True)
with open(summary_path, 'w', encoding='utf-8') as _f:
_f.write(''.join(accumulated))
except Exception as _save_exc:
logging.warning(f"Could not save summary: {_save_exc}")
yield f"data: {json.dumps({'type': 'done'})}\n\n"
except Exception as exc:
yield f"data: {json.dumps({'type': 'error', 'text': str(exc)})}\n\n"
return Response(
_stream(),
mimetype='text/event-stream',
headers={'Cache-Control': 'no-cache', 'X-Accel-Buffering': 'no'},
)
@app.route('/api/summary/<doc_id>')
def api_summary_get(doc_id: str):
if not re.fullmatch(r'\d+', doc_id):
abort(400)
summary_path = os.path.join(OUTPUT_DIR, doc_id, 'summary.txt')
if not os.path.exists(summary_path):
abort(404)
with open(summary_path, encoding='utf-8') as f:
text = f.read()
return jsonify({'text': text})
@app.route('/summary/<doc_id>')
def summary_page(doc_id: str):
if not re.fullmatch(r'\d+', doc_id):
abort(400)
cached_text = None
summary_path = os.path.join(OUTPUT_DIR, doc_id, 'summary.txt')
if os.path.exists(summary_path):
with open(summary_path, encoding='utf-8') as f:
cached_text = f.read()
title = doc_id
graph_path = os.path.join(OUTPUT_DIR, doc_id, 'link_graph.json')
if os.path.exists(graph_path):
try:
with open(graph_path, encoding='utf-8') as f:
gdata = json.load(f)
for node in gdata.get('nodes', []):
if node.get('is_root') or node.get('id') == doc_id:
title = node.get('document') or title
break
except Exception:
pass
if title == doc_id:
details_path = os.path.join(INPUT_DIR, doc_id, 'details.txt')
if os.path.exists(details_path):
with open(details_path, encoding='utf-8') as f:
for line in f:
if line.startswith('Document:'):
title = line.split(':', 1)[1].strip()
break
html = (_SUMMARY_HTML
.replace('__DOC_ID__', doc_id)
.replace('__TITLE_HTML__', _esc_html(title))
.replace('__TITLE_JSON__', _safe_json(title))
.replace('__CACHED_JSON__', _safe_json(cached_text) if cached_text is not None else 'null'))
return Response(html, mimetype='text/html')
@app.errorhandler(404)
def not_found(e):
return jsonify({'error': str(e)}), 404
# ---------------------------------------------------------------------------
# Entry point
# ---------------------------------------------------------------------------
if __name__ == '__main__':
ap = argparse.ArgumentParser(description='LexFlow web server')
ap.add_argument('--port', type=int, default=5001)
ap.add_argument('--host', default='0.0.0.0')
ap.add_argument('--cert', default=None, help='Path to SSL certificate file (PEM)')
ap.add_argument('--key', default=None, help='Path to SSL private key file (PEM)')
args = ap.parse_args()
os.makedirs(INPUT_DIR, exist_ok=True)
os.makedirs(OUTPUT_DIR, exist_ok=True)
logging.basicConfig(level=logging.INFO, format='%(asctime)s [%(levelname)s] %(message)s')
ssl_context = None
if args.cert and args.key:
ssl_context = (args.cert, args.key)
elif args.cert or args.key:
ap.error('--cert and --key must be provided together')
scheme = 'https' if ssl_context else 'http'
print(f"\n LexFlow → {scheme}://localhost:{args.port}\n")
app.run(host=args.host, port=args.port, debug=False, threaded=True, ssl_context=ssl_context)