stephenebert commited on
Commit
2164c4f
Β·
verified Β·
1 Parent(s): add6df8

Update tagger.py

Browse files
Files changed (1) hide show
  1. tagger.py +56 -49
tagger.py CHANGED
@@ -1,5 +1,14 @@
1
  from __future__ import annotations
2
 
 
 
 
 
 
 
 
 
 
3
  import datetime as _dt
4
  import json as _json
5
  import pathlib as _pl
@@ -7,54 +16,47 @@ import re as _re
7
  import sys as _sys
8
  from typing import List
9
 
10
- import nltk
11
  from PIL import Image
12
  from transformers import BlipForConditionalGeneration, BlipProcessor
13
 
14
- # ─── ensure punkt + perceptron tagger are downloaded ──────────────────────────
15
- for res, subdir in [
16
- ("punkt", "tokenizers"),
17
- ("averaged_perceptron_tagger", "taggers"),
18
- ]:
19
- try:
20
- nltk.data.find(f"{subdir}/{res}")
21
- except LookupError:
22
- nltk.download(res, quiet=True)
23
-
24
- # ─── where we dump the caption+tags JSON sidecars ──────────────────────────────
25
- CAP_TAG_DIR = _pl.Path.home() / "Desktop" / "image_tags"
26
- CAP_TAG_DIR.mkdir(exist_ok=True, parents=True)
27
 
28
- # ─── load the BLIP model once ──────────────────────────────────────────────────
 
29
  _processor = BlipProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
30
- _model = BlipForConditionalGeneration.from_pretrained("Salesforce/blip-image-captioning-base")
 
 
31
 
32
- # ─── allowed POS prefixes ──────────────────────────────────────────────────────
33
- _POS = {"nouns": ("NN",), "adjs": ("JJ",), "verbs": ("VB",)}
34
-
35
- def _caption_to_tags(
36
- caption: str,
37
- k: int,
38
- keep_nouns: bool,
39
- keep_adjs: bool,
40
- keep_verbs: bool,
41
- ) -> List[str]:
42
- from nltk.tokenize import wordpunct_tokenize
43
-
44
- allowed = []
45
- if keep_nouns: allowed += _POS["nouns"]
46
- if keep_adjs: allowed += _POS["adjs"]
47
- if keep_verbs: allowed += _POS["verbs"]
48
 
 
 
 
 
 
 
 
 
49
  seen, out = set(), []
50
- for w, pos in nltk.pos_tag(wordpunct_tokenize(caption.lower())):
51
- if any(pos.startswith(pref) for pref in allowed):
52
- clean = _re.sub(r"[^a-z0-9-]", "", w)
53
- if clean and clean not in seen:
54
- out.append(clean)
55
- seen.add(clean)
56
- if len(out) >= k:
57
- break
58
  return out
59
 
60
  def tag_pil_image(
@@ -62,22 +64,26 @@ def tag_pil_image(
62
  stem: str,
63
  *,
64
  top_k: int = 5,
65
- keep_nouns: bool = True,
66
- keep_adjs: bool = True,
67
- keep_verbs: bool = True,
68
  ) -> List[str]:
69
- # 1) generate caption
70
- ids = _model.generate(**_processor(images=img, return_tensors="pt"), max_length=30)
 
 
 
 
71
  caption = _processor.decode(ids[0], skip_special_tokens=True)
72
- # 2) extract tags
73
- tags = _caption_to_tags(caption, top_k, keep_nouns, keep_adjs, keep_verbs)
74
- # 3) persist side-car JSON for main.py to read back
75
  payload = {
76
  "caption": caption,
77
  "tags": tags,
78
  "timestamp": _dt.datetime.now(_dt.timezone.utc).isoformat(),
79
  }
80
- (_p := CAP_TAG_DIR / f"{stem}.json").write_text(_json.dumps(payload, indent=2))
81
  return tags
82
 
83
  if __name__ == "__main__":
@@ -89,3 +95,4 @@ if __name__ == "__main__":
89
  k = int(_sys.argv[2]) if len(_sys.argv) > 2 else 5
90
  with Image.open(path).convert("RGB") as im:
91
  print("tags:", ", ".join(tag_pil_image(im, path.stem, top_k=k)))
 
 
1
  from __future__ import annotations
2
 
3
+ """
4
+ Image captioning + simple tag extraction (no POS/NLTK).
5
+
6
+ - Caption: Salesforce/blip-image-captioning-base (Transformers)
7
+ - Tags: first unique meaningful words from the caption (stopwords removed)
8
+ - Sidecar: writes ./data/<stem>.json with {"caption","tags","timestamp"}
9
+ """
10
+
11
+ import os
12
  import datetime as _dt
13
  import json as _json
14
  import pathlib as _pl
 
16
  import sys as _sys
17
  from typing import List
18
 
19
+ import torch
20
  from PIL import Image
21
  from transformers import BlipForConditionalGeneration, BlipProcessor
22
 
23
+ # Where to save caption+tags JSON (writable on Hugging Face Spaces)
24
+ CAP_TAG_DIR = _pl.Path(os.environ.get("CAP_TAG_DIR", "./data")).resolve()
25
+ CAP_TAG_DIR.mkdir(parents=True, exist_ok=True)
 
 
 
 
 
 
 
 
 
 
26
 
27
+ # Device + model
28
+ _device = "cuda" if torch.cuda.is_available() else "cpu"
29
  _processor = BlipProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
30
+ _model = BlipForConditionalGeneration.from_pretrained(
31
+ "Salesforce/blip-image-captioning-base"
32
+ ).to(_device)
33
 
34
+ # Very small stopword list to keep tags clean (no NLTK required)
35
+ _STOP = {
36
+ "a", "an", "the", "and", "or", "but", "if", "then", "so", "to", "from",
37
+ "of", "in", "on", "at", "by", "for", "with", "without", "into", "out",
38
+ "is", "are", "was", "were", "be", "being", "been", "it", "its", "this",
39
+ "that", "these", "those", "as", "over", "under", "near", "above", "below",
40
+ "up", "down", "left", "right"
41
+ }
 
 
 
 
 
 
 
 
42
 
43
+ def _caption_to_tags_simple(caption: str, k: int) -> List[str]:
44
+ """
45
+ Convert a caption string to up to k simple tags:
46
+ - lowercase alphanumeric/hyphen tokens
47
+ - remove short/stopword tokens
48
+ - keep first unique occurrences (order-preserving)
49
+ """
50
+ tokens = _re.findall(r"[a-z0-9-]+", caption.lower())
51
  seen, out = set(), []
52
+ for w in tokens:
53
+ if len(w) <= 2 or w in _STOP:
54
+ continue
55
+ if w not in seen:
56
+ out.append(w)
57
+ seen.add(w)
58
+ if len(out) >= k:
59
+ break
60
  return out
61
 
62
  def tag_pil_image(
 
64
  stem: str,
65
  *,
66
  top_k: int = 5,
67
+ keep_nouns: bool = True, # kept for API compatibility; ignored
68
+ keep_adjs: bool = True, # kept for API compatibility; ignored
69
+ keep_verbs: bool = True, # kept for API compatibility; ignored
70
  ) -> List[str]:
71
+ """Generate a caption and simple tags for a PIL image."""
72
+ inputs = _processor(images=img, return_tensors="pt")
73
+ if _device == "cuda":
74
+ inputs = {k: v.to(_device) for k, v in inputs.items()}
75
+ with torch.inference_mode():
76
+ ids = _model.generate(**inputs, max_length=30)
77
  caption = _processor.decode(ids[0], skip_special_tokens=True)
78
+
79
+ tags = _caption_to_tags_simple(caption, top_k)
80
+
81
  payload = {
82
  "caption": caption,
83
  "tags": tags,
84
  "timestamp": _dt.datetime.now(_dt.timezone.utc).isoformat(),
85
  }
86
+ (CAP_TAG_DIR / f"{stem}.json").write_text(_json.dumps(payload, indent=2))
87
  return tags
88
 
89
  if __name__ == "__main__":
 
95
  k = int(_sys.argv[2]) if len(_sys.argv) > 2 else 5
96
  with Image.open(path).convert("RGB") as im:
97
  print("tags:", ", ".join(tag_pil_image(im, path.stem, top_k=k)))
98
+