v0.0.5: CSV отдельно, timestamp имена, прогресс в таблице
Deploy drhider / validate (push) Waiting to run

This commit is contained in:
2026-07-13 10:40:00 +04:00
parent 613b645456
commit e4975fb37e
4 changed files with 197 additions and 10 deletions
+1 -1
View File
@@ -20,7 +20,7 @@ if _sys_path_root not in sys.path:
sys.path.insert(0, _sys_path_root) sys.path.insert(0, _sys_path_root)
# Версия приложения (меняется при изменениях) # Версия приложения (меняется при изменениях)
VERSION = "0.0.4" VERSION = "0.0.5"
def create_app(): def create_app():
+26 -6
View File
@@ -1,20 +1,23 @@
""" """
Blueprint: API DrHider. Blueprint: API DrHider.
Three endpoints: Four endpoints:
- POST /api/upload — upload one file -> {session_id} - POST /api/upload — upload one file -> {session_id}
- POST /api/process/{sid} — process all session files -> {status:"done"} - POST /api/process/{sid} — process all session files -> {status:"done"}
- GET /api/download/{sid} — download ZIP - GET /api/download/{sid} — download ZIP (with timestamp name)
- GET /api/csv/{sid} — download CSV separately
""" """
import io import io
import zipfile import zipfile
import traceback import traceback
from datetime import datetime
from flask import Blueprint, request, send_file, jsonify from flask import Blueprint, request, send_file, jsonify
from drhider import obfuscate_files, LLMClient from drhider import obfuscate_files, LLMClient
from drhider.builder import build_zip, build_mapping_csv from drhider.builder import build_zip, build_mapping_csv
from session import create_session, add_file, get_files, store_result, get_result, cleanup, file_count from session import (create_session, add_file, get_files, store_result,
get_result, store_csv, get_csv, cleanup, file_count)
api_bp = Blueprint("api", __name__, url_prefix="/api") api_bp = Blueprint("api", __name__, url_prefix="/api")
@@ -64,8 +67,10 @@ def process(sid):
elif not name.endswith("/"): elif not name.endswith("/"):
all_results.append((name, zf.read(name))) all_results.append((name, zf.read(name)))
csv_str = build_mapping_csv(all_mapping) if all_mapping else "" csv_str = build_mapping_csv(all_mapping) if all_mapping else ""
final_zip = build_zip(all_results, mapping_csv=csv_str) final_zip = build_zip(all_results) # CSV — отдельно, не в ZIP
store_result(sid, final_zip) store_result(sid, final_zip)
if csv_str:
store_csv(sid, csv_str)
return jsonify({"ok": True, "status": "done", "files": len(all_results)}) return jsonify({"ok": True, "status": "done", "files": len(all_results)})
except Exception as e: except Exception as e:
traceback.print_exc() traceback.print_exc()
@@ -78,6 +83,21 @@ def download(sid):
zip_data = get_result(sid) zip_data = get_result(sid)
if zip_data is None: if zip_data is None:
return jsonify({"ok": False, "error": "Not found"}), 404 return jsonify({"ok": False, "error": "Not found"}), 404
cleanup(sid) ts = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
return send_file(io.BytesIO(zip_data), mimetype="application/zip", return send_file(io.BytesIO(zip_data), mimetype="application/zip",
as_attachment=True, download_name="drhider_output.zip") as_attachment=True, download_name=f"drhider_{ts}.zip")
@api_bp.route("/csv/<sid>", methods=["GET"])
def csv_download(sid):
"""Download CSV separately."""
csv_str = get_csv(sid)
if csv_str is None:
return jsonify({"ok": False, "error": "Not found"}), 404
cleanup(sid)
ts = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
buf = io.BytesIO()
buf.write('\ufeff'.encode('utf-8') + csv_str.encode('utf-8'))
buf.seek(0)
return send_file(buf, mimetype="text/csv",
as_attachment=True, download_name=f"mapping_{ts}.csv")
+32
View File
@@ -136,3 +136,35 @@ def cleanup(sid: str):
s = _sessions.pop(sid, None) s = _sessions.pop(sid, None)
if s and s.get("timer"): if s and s.get("timer"):
s["timer"].cancel() s["timer"].cancel()
def store_csv(sid: str, csv_str: str) -> bool:
"""Сохранить CSV с таблицей замен.
Args:
sid: Идентификатор сессии
csv_str: Строка CSV
Returns:
True если сессия существует, False если нет.
"""
with _lock:
s = _sessions.get(sid)
if not s:
return False
s["csv"] = csv_str
return True
def get_csv(sid: str) -> Optional[str]:
"""Получить CSV с таблицей замен.
Args:
sid: Идентификатор сессии
Returns:
Строка CSV или None если нет.
"""
with _lock:
s = _sessions.get(sid)
return s.get("csv") if s else None
+138 -3
View File
@@ -3,6 +3,9 @@
<head> <head>
<meta charset="UTF-8"> <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Expires" content="0">
<title>DrHider — обфускация документов</title> <title>DrHider — обфускация документов</title>
<style> <style>
:root { :root {
@@ -13,6 +16,8 @@
--card: #ffffff; --card: #ffffff;
--text: #1a1a1a; --text: #1a1a1a;
--muted: #6b7280; --muted: #6b7280;
--red: #ef4444;
--green: #22c55e;
} }
* { box-sizing: border-box; margin: 0; padding: 0; } * { box-sizing: border-box; margin: 0; padding: 0; }
body { font: 14px system-ui, sans-serif; color: var(--text); background: var(--bg); min-height: 100vh; } body { font: 14px system-ui, sans-serif; color: var(--text); background: var(--bg); min-height: 100vh; }
@@ -32,6 +37,9 @@
font-weight: 600; font-size: 14px; border-bottom: 1px solid var(--brand-gray); font-weight: 600; font-size: 14px; border-bottom: 1px solid var(--brand-gray);
} }
.card-body { padding: 12px; } .card-body { padding: 12px; }
.sub { font-size: 12px; color: var(--muted); margin-bottom: 10px; line-height: 1.5; }
.file-input-wrap { margin-bottom: 10px; }
.file-input-wrap input[type="file"] { width: 100%; font-size: 13px; }
.table-wrap { border: 1px solid var(--brand-gray); border-radius: 8px; overflow: hidden; } .table-wrap { border: 1px solid var(--brand-gray); border-radius: 8px; overflow: hidden; }
table { width: 100%; border-collapse: collapse; font-size: 13px; } table { width: 100%; border-collapse: collapse; font-size: 13px; }
th { th {
@@ -43,7 +51,15 @@
padding: 5px 8px; border-right: 1px solid var(--brand-gray); padding: 5px 8px; border-right: 1px solid var(--brand-gray);
border-bottom: 1px solid var(--brand-gray); border-bottom: 1px solid var(--brand-gray);
} }
tr:hover td { background: rgba(37,99,235,.03); }
.name-cell { max-width: 340px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.num-cell { text-align: right; white-space: nowrap; }
.empty-row td { color: var(--muted); text-align: center; padding: 20px; } .empty-row td { color: var(--muted); text-align: center; padding: 20px; }
.remove-btn {
cursor: pointer; color: #f87171; background: none; border: none;
padding: 2px 4px; font-size: 14px; line-height: 1;
}
.remove-btn:hover { color: var(--red); }
.footer-bar { .footer-bar {
margin-top: 10px; display: flex; justify-content: space-between; align-items: center; margin-top: 10px; display: flex; justify-content: space-between; align-items: center;
font-size: 12px; color: var(--muted); font-size: 12px; color: var(--muted);
@@ -55,6 +71,14 @@
display: inline-flex; align-items: center; gap: 5px; display: inline-flex; align-items: center; gap: 5px;
} }
.btn-primary { background: var(--brand-primary); border-color: var(--brand-primary); color: #fff; } .btn-primary { background: var(--brand-primary); border-color: var(--brand-primary); color: #fff; }
.btn-primary:hover { opacity: .9; }
.btn:disabled { opacity: .4; cursor: not-allowed; }
.status { margin-top: 10px; padding: 8px 12px; border-radius: 8px; font-size: 13px; display: none; }
.status.progress { background: #eff6ff; border: 1px solid var(--brand-primary); color: var(--brand-primary); display: block; }
.status.done { background: #f0fdf4; border: 1px solid var(--green); color: #16a34a; display: block; }
.status.error { background: #fef2f2; border: 1px solid var(--red); color: #991b1b; display: block; }
.dl-btns { display: none; gap: 8px; margin-top: 8px; }
.dl-btns.show { display: flex; }
</style> </style>
</head> </head>
<body> <body>
@@ -66,6 +90,13 @@
<div class="card"> <div class="card">
<div class="card-header">Обфускация документов</div> <div class="card-header">Обфускация документов</div>
<div class="card-body"> <div class="card-body">
<p class="sub">
Загрузите документы (.docx, .pdf, .txt, .zip) — получите ZIP с обезличенными копиями.<br>
CSV с таблицей замен скачивается отдельно.
</p>
<div class="file-input-wrap">
<input type="file" id="fileInput" multiple accept=".docx,.pdf,.txt,.doc,.zip">
</div>
<div class="table-wrap"> <div class="table-wrap">
<table> <table>
<thead> <thead>
@@ -76,17 +107,121 @@
<th style="width:32px;"></th> <th style="width:32px;"></th>
</tr> </tr>
</thead> </thead>
<tbody> <tbody id="fileList">
<tr class="empty-row"><td colspan="4">Нет выбранных файлов</td></tr> <tr class="empty-row"><td colspan="4">Нет выбранных файлов</td></tr>
</tbody> </tbody>
</table> </table>
</div> </div>
<div class="footer-bar"> <div class="footer-bar">
<span>0 файлов</span> <span id="fileCount">0 файлов</span>
<button class="btn btn-primary">🛡️ Обфусцировать</button> <button class="btn btn-primary" id="uploadBtn" disabled onclick="uploadFiles()">🛡️ Обфусцировать</button>
</div>
<div class="status" id="status"></div>
<div class="dl-btns" id="dlBtns">
<button class="btn btn-primary" id="dlZip" onclick="downloadZip()">📦 Скачать ZIP</button>
<button class="btn" id="dlCsv" onclick="downloadCsv()">📋 Скачать CSV</button>
</div> </div>
</div> </div>
</div> </div>
</div> </div>
<script>
const fi = document.getElementById('fileInput');
const fl = document.getElementById('fileList');
const fc = document.getElementById('fileCount');
const ub = document.getElementById('uploadBtn');
const st = document.getElementById('status');
const db = document.getElementById('dlBtns');
let sf = [];
let currentSid = '';
function fs(b) { return b < 1024 ? b + ' B' : b < 1048576 ? (b / 1024).toFixed(1) + ' KB' : (b / 1048576).toFixed(1) + ' MB'; }
function rr() {
if (sf.length === 0) { fl.innerHTML = '<tr class="empty-row"><td colspan="4">Нет выбранных файлов</td></tr>'; }
else { fl.innerHTML = sf.map((f, i) => '<tr id="row-' + i + '"><td class="name-cell">' + f.name + '</td><td class="num-cell">' + fs(f.size) + '</td><td class="num-cell" id="st-' + i + '" style="font-size:12px;">—</td><td><button class="remove-btn" onclick="rm(' + i + ')">✕</button></td></tr>').join(''); }
fc.textContent = sf.length + ' файлов';
ub.disabled = sf.length === 0;
}
function rm(i) { sf.splice(i, 1); const d = new DataTransfer(); sf.forEach(f => d.items.add(f)); fi.files = d.files; rr(); }
window.addEventListener('load', () => { sf = []; fi.value = ''; rr(); });
fi.addEventListener('change', () => { sf = Array.from(fi.files); rr(); });
function ss(idx, h) { const e = document.getElementById('st-' + idx); if (e) e.innerHTML = h; }
async function uploadFiles() {
if (sf.length === 0) return;
ub.disabled = true;
db.classList.remove('show');
const total = sf.length;
// Фаза 1: загрузка
for (let i = 0; i < total; i++) {
const f = sf[i], n = i + 1;
ss(i, '<span style="color:#2563eb">⏳ загрузка</span>');
st.className = 'status progress';
st.textContent = 'Загрузка ' + n + '/' + total + ': ' + f.name;
const fd = new FormData();
fd.append('files', f, f.name);
if (currentSid) fd.append('session', currentSid);
try {
const resp = await fetch('/api/upload', { method: 'POST', body: fd });
const data = await resp.json();
if (!data.ok) throw new Error(data.error);
currentSid = data.session;
ss(i, '<span style="color:#22c55e">✓ загружен</span>');
} catch (err) {
ss(i, '<span style="color:#ef4444">✗</span>');
st.className = 'status error';
st.textContent = 'Ошибка загрузки: ' + err.message;
ub.disabled = false;
return;
}
}
// Фаза 2: обработка
for (let i = 0; i < total; i++) ss(i, '<span style="color:#2563eb">⏳</span>');
st.className = 'status progress';
st.textContent = 'Обработка...';
const t0 = performance.now();
const ptimer = setInterval(() => {
const sec = Math.round((performance.now() - t0) / 1000);
st.textContent = 'Обработка... ' + sec + 'с';
}, 1000);
try {
const resp = await fetch('/api/process/' + currentSid, { method: 'POST' });
const data = await resp.json();
clearInterval(ptimer);
if (!data.ok) throw new Error(data.error);
for (let i = 0; i < total; i++) ss(i, '<span style="color:#22c55e">✓</span>');
st.className = 'status done';
st.textContent = '✅ Обработано ' + data.files + ' файлов за ' + ((performance.now() - t0) / 1000).toFixed(1) + 'с';
db.classList.add('show');
} catch (err) {
clearInterval(ptimer);
st.className = 'status error';
st.textContent = 'Ошибка: ' + err.message;
}
ub.disabled = false;
}
function downloadZip() {
if (!currentSid) return;
const a = document.createElement('a');
a.href = '/api/download/' + currentSid;
a.download = 'drhider.zip';
a.click();
}
function downloadCsv() {
if (!currentSid) return;
const a = document.createElement('a');
a.href = '/api/csv/' + currentSid;
a.download = 'mapping.csv';
a.click();
}
</script>
</body> </body>
</html> </html>