barath19 OpenAI Codex commited on
Commit
2414447
·
1 Parent(s): 45a3a86

feat: image extraction via in-Space vision model (MiniCPM-V-4.6)

Browse files

Add image -> text extraction so users can drop in a document or ID image and
have the fields extracted, then redacted by the existing core.

- redac/vision.py: extract_text_from_image() loads MiniCPM-V-4.6 via
transformers and runs under @spaces.GPU (ZeroGPU). REDAC_MOCK=1 returns a
canned extraction for GPU-less local UI testing.
- app.py: split into Text and Image tabs sharing one redaction core; image
flow shows raw extracted fields, redacted output, entity table, rehydrate.
- redac/detect.py: phone recognizer no longer matches ISO/common dates.
- requirements.txt: transformers, torchvision, accelerate, sentencepiece,
pillow, spaces.

Co-authored-by: OpenAI Codex <codex@openai.com>

Files changed (5) hide show
  1. app.py +95 -51
  2. redac/__init__.py +2 -0
  3. redac/detect.py +9 -0
  4. redac/vision.py +82 -0
  5. requirements.txt +6 -0
app.py CHANGED
@@ -1,16 +1,24 @@
1
  """Redac — a local privacy gateway.
2
 
3
- V1 (text): paste confidential text, Redac detects PII locally and produces a
4
- reversibly-redacted version plus an entity table. The redacted text is what
5
- you would safely hand to any downstream model; the mapping stays local so the
6
- answer can be rehydrated.
7
-
8
- All compute runs in-process (in-Space). No external API calls.
 
 
9
  """
10
 
11
  import gradio as gr
12
 
13
- from redac import detect_entities, redact, rehydrate, DEFAULT_LABELS
 
 
 
 
 
 
14
 
15
  EXAMPLE = (
16
  "Patient John A. Doe, DOB 1985-04-12, was admitted on 2026-06-01. "
@@ -19,69 +27,105 @@ EXAMPLE = (
19
  )
20
 
21
 
22
- def run_redaction(text, labels, threshold):
23
  entities = detect_entities(text, labels=labels or DEFAULT_LABELS, threshold=threshold)
24
  redacted, mapping = redact(text, entities)
25
  table = [[e.label, e.text, f"{e.score:.2f}", e.source] for e in entities]
26
  summary = f"{len(entities)} PII span(s) redacted into {len(mapping)} placeholder(s)."
27
- # mapping is returned into state so rehydrate can use it; never shown raw.
28
  return redacted, table, summary, mapping
29
 
30
 
 
 
 
 
 
 
 
 
 
 
 
 
31
  def do_rehydrate(redacted_text, mapping):
32
  if not mapping:
33
  return "Run a redaction first."
34
  return rehydrate(redacted_text, mapping)
35
 
36
 
37
- with gr.Blocks(title="Redac", theme=gr.themes.Soft()) as demo:
38
  gr.Markdown(
39
  "# 🖍️ Redac\n"
40
- "**A local privacy gateway.** Detect and redact PII *before* text reaches "
41
- "a downstream model. Redaction is reversible: the mapping stays local."
42
  )
43
 
44
- mapping_state = gr.State({})
45
-
46
- with gr.Row():
47
- with gr.Column():
48
- inp = gr.Textbox(
49
- label="Confidential text",
50
- placeholder="Paste a document, message, or record...",
51
- lines=10,
52
- value=EXAMPLE,
53
- )
54
- labels = gr.Dropdown(
55
- label="PII types to detect",
56
- choices=DEFAULT_LABELS,
57
- value=DEFAULT_LABELS,
58
- multiselect=True,
59
- )
60
- threshold = gr.Slider(
61
- 0.1, 0.9, value=0.45, step=0.05, label="Detection threshold"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
  )
63
- run_btn = gr.Button("Redact", variant="primary")
64
- with gr.Column():
65
- out = gr.Textbox(label="Redacted (safe to send downstream)", lines=10)
66
- summary = gr.Markdown()
67
- entities = gr.Dataframe(
68
- headers=["type", "value", "score", "source"],
69
- label="Detected PII",
70
- wrap=True,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
71
  )
72
- with gr.Accordion("Rehydrate (local only)", open=False):
73
- rehydrate_btn = gr.Button("Restore original values")
74
- restored = gr.Textbox(label="Rehydrated", lines=6)
75
-
76
- run_btn.click(
77
- run_redaction,
78
- inputs=[inp, labels, threshold],
79
- outputs=[out, entities, summary, mapping_state],
80
- )
81
- rehydrate_btn.click(
82
- do_rehydrate, inputs=[out, mapping_state], outputs=[restored]
83
- )
84
 
85
 
86
  if __name__ == "__main__":
87
- demo.launch(server_name="0.0.0.0", server_port=7860)
 
1
  """Redac — a local privacy gateway.
2
 
3
+ Two entry points, one redaction core:
4
+ - Text: paste confidential text -> detect PII -> reversibly redact.
5
+ - Image: upload a document/ID image -> a local vision model extracts the
6
+ fields -> the extracted text is redacted the same way.
7
+
8
+ The redacted text is what you would safely hand to a downstream LLM; the
9
+ mapping stays local so any answer can be rehydrated. All compute runs
10
+ in-Space (vision model on ZeroGPU). No external API calls.
11
  """
12
 
13
  import gradio as gr
14
 
15
+ from redac import (
16
+ detect_entities,
17
+ redact,
18
+ rehydrate,
19
+ extract_text_from_image,
20
+ DEFAULT_LABELS,
21
+ )
22
 
23
  EXAMPLE = (
24
  "Patient John A. Doe, DOB 1985-04-12, was admitted on 2026-06-01. "
 
27
  )
28
 
29
 
30
+ def _redact_text(text, labels, threshold):
31
  entities = detect_entities(text, labels=labels or DEFAULT_LABELS, threshold=threshold)
32
  redacted, mapping = redact(text, entities)
33
  table = [[e.label, e.text, f"{e.score:.2f}", e.source] for e in entities]
34
  summary = f"{len(entities)} PII span(s) redacted into {len(mapping)} placeholder(s)."
 
35
  return redacted, table, summary, mapping
36
 
37
 
38
+ def run_text(text, labels, threshold):
39
+ return _redact_text(text, labels, threshold)
40
+
41
+
42
+ def run_image(image, labels, threshold):
43
+ extracted = extract_text_from_image(image)
44
+ if not extracted:
45
+ return "", "", [], "No image / nothing extracted.", {}
46
+ redacted, table, summary, mapping = _redact_text(extracted, labels, threshold)
47
+ return extracted, redacted, table, summary, mapping
48
+
49
+
50
  def do_rehydrate(redacted_text, mapping):
51
  if not mapping:
52
  return "Run a redaction first."
53
  return rehydrate(redacted_text, mapping)
54
 
55
 
56
+ with gr.Blocks(title="Redac") as demo:
57
  gr.Markdown(
58
  "# 🖍️ Redac\n"
59
+ "**A local privacy gateway.** Detect and redact PII *before* it reaches "
60
+ "a downstream model. Reversible: the mapping stays local."
61
  )
62
 
63
+ with gr.Tabs():
64
+ # --- Text tab --------------------------------------------------------
65
+ with gr.Tab("Text"):
66
+ t_map = gr.State({})
67
+ with gr.Row():
68
+ with gr.Column():
69
+ t_in = gr.Textbox(
70
+ label="Confidential text",
71
+ placeholder="Paste a document, message, or record...",
72
+ lines=10,
73
+ value=EXAMPLE,
74
+ )
75
+ t_labels = gr.Dropdown(
76
+ label="PII types", choices=DEFAULT_LABELS,
77
+ value=DEFAULT_LABELS, multiselect=True,
78
+ )
79
+ t_thr = gr.Slider(0.1, 0.9, value=0.45, step=0.05, label="Threshold")
80
+ t_btn = gr.Button("Redact", variant="primary")
81
+ with gr.Column():
82
+ t_out = gr.Textbox(label="Redacted (safe to send downstream)", lines=10)
83
+ t_sum = gr.Markdown()
84
+ t_tab = gr.Dataframe(
85
+ headers=["type", "value", "score", "source"],
86
+ label="Detected PII", wrap=True,
87
+ )
88
+ with gr.Accordion("Rehydrate (local only)", open=False):
89
+ t_reh_btn = gr.Button("Restore original values")
90
+ t_reh = gr.Textbox(label="Rehydrated", lines=6)
91
+
92
+ t_btn.click(run_text, [t_in, t_labels, t_thr], [t_out, t_tab, t_sum, t_map])
93
+ t_reh_btn.click(do_rehydrate, [t_out, t_map], [t_reh])
94
+
95
+ # --- Image tab -------------------------------------------------------
96
+ with gr.Tab("Image"):
97
+ gr.Markdown(
98
+ "Upload a document or ID image. A local vision model "
99
+ "(MiniCPM-V-4.6) extracts the fields, then Redac redacts them."
100
  )
101
+ i_map = gr.State({})
102
+ with gr.Row():
103
+ with gr.Column():
104
+ i_in = gr.Image(label="Document / ID image", type="pil")
105
+ i_labels = gr.Dropdown(
106
+ label="PII types", choices=DEFAULT_LABELS,
107
+ value=DEFAULT_LABELS, multiselect=True,
108
+ )
109
+ i_thr = gr.Slider(0.1, 0.9, value=0.45, step=0.05, label="Threshold")
110
+ i_btn = gr.Button("Extract & redact", variant="primary")
111
+ with gr.Column():
112
+ i_extracted = gr.Textbox(label="Extracted fields (raw)", lines=8)
113
+ i_out = gr.Textbox(label="Redacted (safe to send downstream)", lines=8)
114
+ i_sum = gr.Markdown()
115
+ i_tab = gr.Dataframe(
116
+ headers=["type", "value", "score", "source"],
117
+ label="Detected PII", wrap=True,
118
+ )
119
+ with gr.Accordion("Rehydrate (local only)", open=False):
120
+ i_reh_btn = gr.Button("Restore original values")
121
+ i_reh = gr.Textbox(label="Rehydrated", lines=6)
122
+
123
+ i_btn.click(
124
+ run_image, [i_in, i_labels, i_thr],
125
+ [i_extracted, i_out, i_tab, i_sum, i_map],
126
  )
127
+ i_reh_btn.click(do_rehydrate, [i_out, i_map], [i_reh])
 
 
 
 
 
 
 
 
 
 
 
128
 
129
 
130
  if __name__ == "__main__":
131
+ demo.launch(server_name="0.0.0.0", server_port=7860, theme=gr.themes.Soft())
redac/__init__.py CHANGED
@@ -3,6 +3,7 @@ confidential text reaches a downstream model. Reversible by design."""
3
 
4
  from .detect import Entity, detect_entities, DEFAULT_LABELS
5
  from .redact import redact, rehydrate
 
6
 
7
  __all__ = [
8
  "Entity",
@@ -10,4 +11,5 @@ __all__ = [
10
  "DEFAULT_LABELS",
11
  "redact",
12
  "rehydrate",
 
13
  ]
 
3
 
4
  from .detect import Entity, detect_entities, DEFAULT_LABELS
5
  from .redact import redact, rehydrate
6
+ from .vision import extract_text_from_image
7
 
8
  __all__ = [
9
  "Entity",
 
11
  "DEFAULT_LABELS",
12
  "redact",
13
  "rehydrate",
14
+ "extract_text_from_image",
15
  ]
redac/detect.py CHANGED
@@ -58,6 +58,12 @@ _REGEX_RECOGNIZERS = [
58
  ]
59
 
60
 
 
 
 
 
 
 
61
  def _regex_entities(text: str) -> List[Entity]:
62
  out: List[Entity] = []
63
  for label, pattern in _REGEX_RECOGNIZERS:
@@ -65,6 +71,9 @@ def _regex_entities(text: str) -> List[Entity]:
65
  span = m.group().strip()
66
  if len(span) < 4:
67
  continue
 
 
 
68
  out.append(
69
  Entity(
70
  start=m.start(),
 
58
  ]
59
 
60
 
61
+ # Common date shapes the greedy phone pattern would otherwise swallow.
62
+ _DATE_RE = re.compile(
63
+ r"^\d{4}[./-]\d{1,2}[./-]\d{1,2}$|^\d{1,2}[./-]\d{1,2}[./-]\d{2,4}$"
64
+ )
65
+
66
+
67
  def _regex_entities(text: str) -> List[Entity]:
68
  out: List[Entity] = []
69
  for label, pattern in _REGEX_RECOGNIZERS:
 
71
  span = m.group().strip()
72
  if len(span) < 4:
73
  continue
74
+ # Don't let the phone recognizer misfire on dates.
75
+ if label == "phone number" and _DATE_RE.match(span):
76
+ continue
77
  out.append(
78
  Entity(
79
  start=m.start(),
redac/vision.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Image -> text extraction with a local vision model (MiniCPM-V-4.6).
2
+
3
+ Runs in-Space on ZeroGPU via the @spaces.GPU decorator. The model reads a
4
+ document/ID image and returns the fields as plain text, which then flows
5
+ through the same PII detection + redaction core as typed text.
6
+
7
+ Local dev: set REDAC_MOCK=1 to skip the model entirely and return a canned
8
+ extraction, so the Gradio UI runs on a laptop with no GPU.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import os
14
+ from functools import lru_cache
15
+
16
+ MODEL_ID = "openbmb/MiniCPM-V-4.6"
17
+
18
+ EXTRACTION_PROMPT = (
19
+ "You are a document data extractor. Read this image and transcribe ALL "
20
+ "personal and sensitive information you can find. Output one field per "
21
+ "line as 'field: value'. Include, when present: full name, date of birth, "
22
+ "address, passport/ID/driver-license number, national ID or social "
23
+ "security number, phone, email, and any account or card numbers. "
24
+ "Transcribe values exactly as written. Do not invent fields."
25
+ )
26
+
27
+ _MOCK_EXTRACTION = (
28
+ "full name: John A. Doe\n"
29
+ "date of birth: 1985-04-12\n"
30
+ "address: 221B Baker Street, London\n"
31
+ "passport number: X1234567\n"
32
+ "national id number: 123-45-6789\n"
33
+ "email: john.doe@example.com\n"
34
+ "phone: +49 151 23456789"
35
+ )
36
+
37
+
38
+ def _is_mock() -> bool:
39
+ return os.environ.get("REDAC_MOCK", "").strip() in {"1", "true", "True"}
40
+
41
+
42
+ # ZeroGPU decorator; degrade to a no-op decorator when `spaces` is absent
43
+ # (local dev) so the module imports cleanly off-Space.
44
+ try:
45
+ import spaces # type: ignore
46
+
47
+ _gpu = spaces.GPU(duration=120)
48
+ except Exception: # pragma: no cover - local fallback
49
+ def _gpu(fn):
50
+ return fn
51
+
52
+
53
+ @lru_cache(maxsize=1)
54
+ def _load_model():
55
+ import torch
56
+ from transformers import AutoModel, AutoTokenizer
57
+
58
+ model = AutoModel.from_pretrained(
59
+ MODEL_ID,
60
+ trust_remote_code=True,
61
+ attn_implementation="sdpa",
62
+ torch_dtype=torch.bfloat16,
63
+ ).eval()
64
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_ID, trust_remote_code=True)
65
+ return model, tokenizer
66
+
67
+
68
+ @_gpu
69
+ def _chat(image, prompt: str) -> str:
70
+ model, tokenizer = _load_model()
71
+ model = model.to("cuda")
72
+ msgs = [{"role": "user", "content": [image, prompt]}]
73
+ return model.chat(image=None, msgs=msgs, tokenizer=tokenizer)
74
+
75
+
76
+ def extract_text_from_image(image, prompt: str | None = None) -> str:
77
+ """Return extracted field text from a PIL image. Honors REDAC_MOCK."""
78
+ if image is None:
79
+ return ""
80
+ if _is_mock():
81
+ return _MOCK_EXTRACTION
82
+ return _chat(image.convert("RGB"), prompt or EXTRACTION_PROMPT).strip()
requirements.txt CHANGED
@@ -1,4 +1,10 @@
1
  gradio==6.18.0
2
  gliner>=0.2.13
3
  torch
 
 
 
 
 
4
  huggingface_hub
 
 
1
  gradio==6.18.0
2
  gliner>=0.2.13
3
  torch
4
+ torchvision
5
+ transformers>=4.44
6
+ accelerate
7
+ sentencepiece
8
+ pillow
9
  huggingface_hub
10
+ spaces