GautamKishore commited on
Commit
3d57a4d
·
verified ·
1 Parent(s): 4a56948

Upload model/pico_type/cli.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. model/pico_type/cli.py +25 -17
model/pico_type/cli.py CHANGED
@@ -9,7 +9,16 @@ import sys
9
 
10
  import numpy as np
11
 
12
- from .labels import ALL_HEADS, COARSE_LABELS, MODALITY_LABELS, SUBTYPE_LABELS, CODE_LANG_LABELS, TEXT_LANG_LABELS, FILE_MIME_LABELS, RISK_LABELS
 
 
 
 
 
 
 
 
 
13
 
14
  LABEL_TABLES = {
15
  "coarse": COARSE_LABELS,
@@ -33,6 +42,7 @@ def load_onnx_model(tier: str = "base", model_dir: str = "checkpoints"):
33
 
34
  def load_torch_model(tier: str = "base", checkpoint: str = ""):
35
  import torch
 
36
  from .arch import PicoType, PicoTypeConfig
37
  cfg = PicoTypeConfig(max_bytes=1024)
38
  model = PicoType(cfg)
@@ -42,9 +52,8 @@ def load_torch_model(tier: str = "base", checkpoint: str = ""):
42
  return model, tier
43
 
44
 
45
- def run_onnx(session, text: str, max_bytes: int = 1024) -> dict:
46
- text_bytes = text.encode("utf-8")[:max_bytes]
47
- ids = np.frombuffer(text_bytes, dtype=np.uint8).astype(np.int64)
48
  seq_len = len(ids)
49
  if seq_len > max_bytes:
50
  ids = ids[:max_bytes]
@@ -76,11 +85,10 @@ def _softmax(x):
76
  return e / e.sum()
77
 
78
 
79
- def run_torch(model, tier: str, text: str, max_bytes: int = 1024) -> dict:
80
  import torch
81
  model = model[0] if isinstance(model, tuple) else model
82
- text_bytes = text.encode("utf-8")[:max_bytes]
83
- ids = torch.tensor([list(text_bytes)], dtype=torch.long)
84
  mask = torch.ones(1, ids.shape[1], dtype=torch.bool)
85
  with torch.no_grad():
86
  logits_dict = model(ids, mask)
@@ -99,17 +107,17 @@ def run_torch(model, tier: str, text: str, max_bytes: int = 1024) -> dict:
99
  return out
100
 
101
 
102
- def read_text(args) -> str:
103
  if args.text:
104
- return args.text
105
  if args.file:
106
- with open(args.file, "r", encoding="utf-8", errors="replace") as f:
107
  return f.read()
108
  if args.clip:
109
  import subprocess
110
- return subprocess.check_output(["pbpaste"], text=True)
111
  if not sys.stdin.isatty():
112
- return sys.stdin.read()
113
  raise ValueError("No input provided. Use --text, --file, --clip, or pipe content.")
114
 
115
 
@@ -128,27 +136,27 @@ def build_parser():
128
  def main():
129
  args = build_parser().parse_args()
130
  try:
131
- text = read_text(args)
132
  except ValueError as e:
133
  print(e, file=sys.stderr)
134
  sys.exit(1)
135
 
136
- if not text.strip():
137
  print('{"error": "empty input"}')
138
  sys.exit(0)
139
 
140
  onnx_path = os.path.join(args.model_dir, f"picotype_{args.tier}.onnx")
141
  if os.path.exists(onnx_path):
142
  session = load_onnx_model(args.tier, args.model_dir)
143
- result = run_onnx(session, text)
144
  elif args.checkpoint:
145
  model = load_torch_model(args.tier, args.checkpoint)
146
- result = run_torch(model, args.tier, text)
147
  else:
148
  print(f"ONNX model not found at {onnx_path}. Use --checkpoint to use PyTorch.", file=sys.stderr)
149
  sys.exit(1)
150
 
151
- result["text_length"] = len(text)
152
  result["tier"] = args.tier
153
  indent = 2 if args.pretty else None
154
  json.dump(result, sys.stdout, indent=indent, ensure_ascii=False)
 
9
 
10
  import numpy as np
11
 
12
+ from .labels import (
13
+ ALL_HEADS,
14
+ COARSE_LABELS,
15
+ CODE_LANG_LABELS,
16
+ FILE_MIME_LABELS,
17
+ MODALITY_LABELS,
18
+ RISK_LABELS,
19
+ SUBTYPE_LABELS,
20
+ TEXT_LANG_LABELS,
21
+ )
22
 
23
  LABEL_TABLES = {
24
  "coarse": COARSE_LABELS,
 
42
 
43
  def load_torch_model(tier: str = "base", checkpoint: str = ""):
44
  import torch
45
+
46
  from .arch import PicoType, PicoTypeConfig
47
  cfg = PicoTypeConfig(max_bytes=1024)
48
  model = PicoType(cfg)
 
52
  return model, tier
53
 
54
 
55
+ def run_onnx(session, data: bytes, max_bytes: int = 1024) -> dict:
56
+ ids = np.frombuffer(data[:max_bytes], dtype=np.uint8).astype(np.int64)
 
57
  seq_len = len(ids)
58
  if seq_len > max_bytes:
59
  ids = ids[:max_bytes]
 
85
  return e / e.sum()
86
 
87
 
88
+ def run_torch(model, tier: str, data: bytes, max_bytes: int = 1024) -> dict:
89
  import torch
90
  model = model[0] if isinstance(model, tuple) else model
91
+ ids = torch.tensor([list(data[:max_bytes])], dtype=torch.long)
 
92
  mask = torch.ones(1, ids.shape[1], dtype=torch.bool)
93
  with torch.no_grad():
94
  logits_dict = model(ids, mask)
 
107
  return out
108
 
109
 
110
+ def read_input(args) -> bytes:
111
  if args.text:
112
+ return args.text.encode("utf-8")
113
  if args.file:
114
+ with open(args.file, "rb") as f:
115
  return f.read()
116
  if args.clip:
117
  import subprocess
118
+ return subprocess.check_output(["pbpaste"]).rstrip(b"\n")
119
  if not sys.stdin.isatty():
120
+ return sys.stdin.buffer.read()
121
  raise ValueError("No input provided. Use --text, --file, --clip, or pipe content.")
122
 
123
 
 
136
  def main():
137
  args = build_parser().parse_args()
138
  try:
139
+ data = read_input(args)
140
  except ValueError as e:
141
  print(e, file=sys.stderr)
142
  sys.exit(1)
143
 
144
+ if not data.strip():
145
  print('{"error": "empty input"}')
146
  sys.exit(0)
147
 
148
  onnx_path = os.path.join(args.model_dir, f"picotype_{args.tier}.onnx")
149
  if os.path.exists(onnx_path):
150
  session = load_onnx_model(args.tier, args.model_dir)
151
+ result = run_onnx(session, data)
152
  elif args.checkpoint:
153
  model = load_torch_model(args.tier, args.checkpoint)
154
+ result = run_torch(model, args.tier, data)
155
  else:
156
  print(f"ONNX model not found at {onnx_path}. Use --checkpoint to use PyTorch.", file=sys.stderr)
157
  sys.exit(1)
158
 
159
+ result["text_length"] = len(data)
160
  result["tier"] = args.tier
161
  indent = 2 if args.pretty else None
162
  json.dump(result, sys.stdout, indent=indent, ensure_ascii=False)