Spaces:
Sleeping
Sleeping
Update pipelines/anonymize.py
Browse files- pipelines/anonymize.py +34 -11
pipelines/anonymize.py
CHANGED
|
@@ -1,28 +1,51 @@
|
|
| 1 |
-
# 最低限の動作用スタブ。実運用は実名/連絡先のマスキング等を実装してください。
|
| 2 |
from reportlab.pdfgen import canvas
|
| 3 |
from reportlab.lib.pagesizes import A4
|
| 4 |
from io import BytesIO
|
|
|
|
|
|
|
| 5 |
|
| 6 |
|
| 7 |
-
def anonymize_text(text: str):
|
| 8 |
"""
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
置換マップを返してください。
|
| 12 |
"""
|
| 13 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
|
| 15 |
|
| 16 |
def render_anonymized_pdf(text: str) -> bytes:
|
|
|
|
|
|
|
|
|
|
| 17 |
buf = BytesIO()
|
| 18 |
c = canvas.Canvas(buf, pagesize=A4)
|
| 19 |
width, height = A4
|
| 20 |
-
|
|
|
|
|
|
|
|
|
|
| 21 |
for line in text.splitlines():
|
| 22 |
-
if y <
|
| 23 |
c.showPage()
|
| 24 |
-
y = height -
|
| 25 |
-
|
| 26 |
-
y
|
|
|
|
|
|
|
| 27 |
c.save()
|
| 28 |
return buf.getvalue()
|
|
|
|
|
|
|
| 1 |
from reportlab.pdfgen import canvas
|
| 2 |
from reportlab.lib.pagesizes import A4
|
| 3 |
from io import BytesIO
|
| 4 |
+
import re
|
| 5 |
+
from typing import Dict, Tuple
|
| 6 |
|
| 7 |
|
| 8 |
+
def anonymize_text(text: str) -> Tuple[str, Dict[str, str]]:
|
| 9 |
"""
|
| 10 |
+
最小実装:メール/電話を [REDACTED] に置換。氏名などの高度な匿名化は未実装。
|
| 11 |
+
実運用では固有表現抽出や辞書を組み合わせて拡張してください。
|
|
|
|
| 12 |
"""
|
| 13 |
+
mapping: Dict[str, str] = {}
|
| 14 |
+
|
| 15 |
+
def _replace(pattern: str, label: str, s: str) -> str:
|
| 16 |
+
def _sub(m):
|
| 17 |
+
val = m.group(0)
|
| 18 |
+
if val not in mapping:
|
| 19 |
+
mapping[val] = f"[{label}_REDACTED]"
|
| 20 |
+
return mapping[val]
|
| 21 |
+
return re.sub(pattern, _sub, s)
|
| 22 |
+
|
| 23 |
+
# email
|
| 24 |
+
text = _replace(r"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}", "EMAIL", text)
|
| 25 |
+
# phone (緩め)
|
| 26 |
+
text = _replace(r"(?:\+?\d{1,3}[ -]?)?(?:\(\d{2,4}\)[ -]?)?\d{2,4}[ -]?\d{2,4}[ -]?\d{3,4}", "PHONE", text)
|
| 27 |
+
|
| 28 |
+
return text, mapping
|
| 29 |
|
| 30 |
|
| 31 |
def render_anonymized_pdf(text: str) -> bytes:
|
| 32 |
+
"""
|
| 33 |
+
簡易PDF描画:A4 に左上から行単位で出力(自動改ページ)。
|
| 34 |
+
"""
|
| 35 |
buf = BytesIO()
|
| 36 |
c = canvas.Canvas(buf, pagesize=A4)
|
| 37 |
width, height = A4
|
| 38 |
+
x_margin, y_margin = 40, 40
|
| 39 |
+
line_height = 14
|
| 40 |
+
|
| 41 |
+
y = height - y_margin
|
| 42 |
for line in text.splitlines():
|
| 43 |
+
if y < y_margin:
|
| 44 |
c.showPage()
|
| 45 |
+
y = height - y_margin
|
| 46 |
+
# 長い行は雑に切る(ReportLab簡易実装)
|
| 47 |
+
c.drawString(x_margin, y, line[:120])
|
| 48 |
+
y -= line_height
|
| 49 |
+
|
| 50 |
c.save()
|
| 51 |
return buf.getvalue()
|