Spaces:
Sleeping

antaris commited on
Commit
8eebcff
·
verified ·
1 Parent(s): 1ec8799

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +325 -34
app.py CHANGED
@@ -1,26 +1,39 @@
1
- # app.py
2
  from __future__ import annotations
3
 
4
- import gradio as gr
 
 
5
  import re
 
 
 
 
6
 
7
 
 
 
 
 
8
  _ISIN_BODY_RE = re.compile(r"^[A-Z0-9]{11}$")
9
- _ISIN_FULL_RE = re.compile(r"^[A-Z0-9]{12}$")
10
 
11
 
12
  def normalize_isin(s: str) -> str:
13
- return re.sub(r"[\s-]+", "", s).upper()
14
 
15
 
16
  def expand_isin_body(body: str) -> str:
 
 
 
 
17
  body = normalize_isin(body)
18
  if not _ISIN_BODY_RE.fullmatch(body):
19
  raise ValueError(
20
  "ISIN-Body muss aus genau 11 alphanumerischen Zeichen bestehen."
21
  )
22
 
23
- out = []
24
  for ch in body:
25
  if ch.isdigit():
26
  out.append(ch)
@@ -30,8 +43,15 @@ def expand_isin_body(body: str) -> str:
30
 
31
 
32
  def luhn_mod10_check_digit_from_expanded(expanded_digits: str) -> str:
 
 
 
 
 
 
 
33
  total = 0
34
- double = True
35
 
36
  for ch in reversed(expanded_digits):
37
  n = int(ch)
@@ -46,7 +66,8 @@ def luhn_mod10_check_digit_from_expanded(expanded_digits: str) -> str:
46
 
47
 
48
  def compute_isin_check_digit(body: str) -> str:
49
- return luhn_mod10_check_digit_from_expanded(expand_isin_body(body))
 
50
 
51
 
52
  def complete_isin(body: str) -> str:
@@ -61,23 +82,68 @@ def validate_isin(isin: str) -> bool:
61
  return compute_isin_check_digit(isin[:-1]) == isin[-1]
62
 
63
 
64
- def run_isin_tool(user_input: str) -> str:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
65
  s = normalize_isin(user_input)
66
 
67
  if _ISIN_BODY_RE.fullmatch(s):
68
  full = complete_isin(s)
 
69
  return (
70
  f"Eingabe erkannt als 11-stelliger ISIN-Body.\n\n"
71
  f"Vollständige ISIN: {full}\n"
72
- f"Prüfziffer: {full[-1]}"
 
 
73
  )
74
 
75
  if _ISIN_FULL_RE.fullmatch(s):
76
- ok = validate_isin(s)
 
77
  return (
78
  f"Eingabe erkannt als vollständige 12-stellige ISIN.\n\n"
79
  f"ISIN: {s}\n"
80
- f"Status: {'gültig' if ok else 'ungültig'}"
 
 
81
  )
82
 
83
  return (
@@ -89,26 +155,251 @@ def run_isin_tool(user_input: str) -> str:
89
  )
90
 
91
 
92
- demo = gr.Interface(
93
- fn=run_isin_tool,
94
- inputs=gr.Textbox(
95
- label="ISIN oder ISIN-Body",
96
- placeholder="z.B. US037833100 oder US0378331005",
97
- lines=1,
98
- ),
99
- outputs=gr.Textbox(label="Ergebnis", lines=8),
100
- title="ISIN Check Digit Rechner / Validator",
101
- description=(
102
- "Berechnet aus einem 11-stelligen ISIN-Body die Prüfziffer "
103
- "oder validiert eine vollständige 12-stellige ISIN."
104
- ),
105
- examples=[
106
- ["US037833100"],
107
- ["US0378331005"],
108
- ["AU0000XVGZA"],
109
- ["AU0000XVGZA3"],
110
- ],
111
- )
112
-
113
- if __name__ == "__main__":
114
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  from __future__ import annotations
2
 
3
+ import csv
4
+ import io
5
+ import random
6
  import re
7
+ from functools import lru_cache
8
+
9
+ import gradio as gr
10
+ import requests
11
 
12
 
13
+ # ------------------------------------------------------------
14
+ # ISIN core
15
+ # ------------------------------------------------------------
16
+
17
  _ISIN_BODY_RE = re.compile(r"^[A-Z0-9]{11}$")
18
+ _ISIN_FULL_RE = re.compile(r"^[A-Z]{2}[A-Z0-9]{9}[0-9]$")
19
 
20
 
21
  def normalize_isin(s: str) -> str:
22
+ return re.sub(r"[\s-]+", "", (s or "")).upper()
23
 
24
 
25
  def expand_isin_body(body: str) -> str:
26
+ """
27
+ Expand an 11-char ISIN body to digits:
28
+ A -> 10, ..., Z -> 35, digits stay unchanged.
29
+ """
30
  body = normalize_isin(body)
31
  if not _ISIN_BODY_RE.fullmatch(body):
32
  raise ValueError(
33
  "ISIN-Body muss aus genau 11 alphanumerischen Zeichen bestehen."
34
  )
35
 
36
+ out: list[str] = []
37
  for ch in body:
38
  if ch.isdigit():
39
  out.append(ch)
 
43
 
44
 
45
  def luhn_mod10_check_digit_from_expanded(expanded_digits: str) -> str:
46
+ """
47
+ Main implementation:
48
+ traverse from right to left, double every second digit.
49
+ """
50
+ if not expanded_digits.isdigit():
51
+ raise ValueError("expanded_digits muss nur aus Ziffern bestehen.")
52
+
53
  total = 0
54
+ double = True # because the check digit will be appended on the right
55
 
56
  for ch in reversed(expanded_digits):
57
  n = int(ch)
 
66
 
67
 
68
  def compute_isin_check_digit(body: str) -> str:
69
+ expanded = expand_isin_body(body)
70
+ return luhn_mod10_check_digit_from_expanded(expanded)
71
 
72
 
73
  def complete_isin(body: str) -> str:
 
82
  return compute_isin_check_digit(isin[:-1]) == isin[-1]
83
 
84
 
85
+ # ------------------------------------------------------------
86
+ # Independent reference implementation
87
+ # (different formulation, same mathematical result)
88
+ # ------------------------------------------------------------
89
+
90
+ def compute_isin_check_digit_reference(body: str) -> str:
91
+ """
92
+ Reference implementation of the same rule, but written independently:
93
+ - expand letters
94
+ - reason from LEFT using parity of the final full length
95
+ """
96
+ digits = [int(ch) for ch in expand_isin_body(body)]
97
+
98
+ # final full number length = len(digits) + 1 (for the check digit)
99
+ full_len = len(digits) + 1
100
+ parity = full_len % 2
101
+
102
+ total = 0
103
+ for i, n in enumerate(digits):
104
+ if i % 2 == parity:
105
+ n *= 2
106
+ if n > 9:
107
+ n -= 9
108
+ total += n
109
+
110
+ return str((10 - (total % 10)) % 10)
111
+
112
+
113
+ def validate_isin_reference(isin: str) -> bool:
114
+ isin = normalize_isin(isin)
115
+ if not _ISIN_FULL_RE.fullmatch(isin):
116
+ return False
117
+ return compute_isin_check_digit_reference(isin[:-1]) == isin[-1]
118
+
119
+
120
+ # ------------------------------------------------------------
121
+ # Manual UI helpers
122
+ # ------------------------------------------------------------
123
+
124
+ def run_manual_isin_tool(user_input: str) -> str:
125
  s = normalize_isin(user_input)
126
 
127
  if _ISIN_BODY_RE.fullmatch(s):
128
  full = complete_isin(s)
129
+ ref = compute_isin_check_digit_reference(s)
130
  return (
131
  f"Eingabe erkannt als 11-stelliger ISIN-Body.\n\n"
132
  f"Vollständige ISIN: {full}\n"
133
+ f"Prüfziffer: {full[-1]}\n"
134
+ f"Referenz-Prüfziffer: {ref}\n"
135
+ f"Konsistenz: {'OK' if ref == full[-1] else 'ABWEICHUNG'}"
136
  )
137
 
138
  if _ISIN_FULL_RE.fullmatch(s):
139
+ ok_main = validate_isin(s)
140
+ ok_ref = validate_isin_reference(s)
141
  return (
142
  f"Eingabe erkannt als vollständige 12-stellige ISIN.\n\n"
143
  f"ISIN: {s}\n"
144
+ f"Validierung (Hauptimplementierung): {'gültig' if ok_main else 'ungültig'}\n"
145
+ f"Validierung (Referenzimplementierung): {'gültig' if ok_ref else 'ungültig'}\n"
146
+ f"Konsistenz: {'OK' if ok_main == ok_ref else 'ABWEICHUNG'}"
147
  )
148
 
149
  return (
 
155
  )
156
 
157
 
158
+ # ------------------------------------------------------------
159
+ # Online dataset self-test
160
+ # ------------------------------------------------------------
161
+
162
+ REMOTE_SOURCES = {
163
+ "NSDL mirror (India ISIN dataset on GitHub)": {
164
+ "url": "https://raw.githubusercontent.com/captn3m0/india-isin-data/main/ISIN.csv",
165
+ "description": (
166
+ "Öffentliches CSV-Repo mit realen ISINs; gut für externe Regressionstests."
167
+ ),
168
+ }
169
+ }
170
+
171
+
172
+ def _extract_isins_from_csv_text(text: str) -> list[str]:
173
+ """
174
+ Parse robustly:
175
+ 1) try DictReader and a column named 'isin'
176
+ 2) fallback to regex extraction from whole text
177
+ """
178
+ out: list[str] = []
179
+
180
+ try:
181
+ reader = csv.DictReader(io.StringIO(text))
182
+ if reader.fieldnames:
183
+ field_map = {f.strip().lower(): f for f in reader.fieldnames if f}
184
+ isin_field = field_map.get("isin")
185
+ if isin_field:
186
+ for row in reader:
187
+ candidate = normalize_isin(row.get(isin_field, ""))
188
+ if _ISIN_FULL_RE.fullmatch(candidate):
189
+ out.append(candidate)
190
+ except csv.Error:
191
+ pass
192
+
193
+ if not out:
194
+ for candidate in re.findall(r"\b[A-Z]{2}[A-Z0-9]{9}[0-9]\b", text.upper()):
195
+ if _ISIN_FULL_RE.fullmatch(candidate):
196
+ out.append(candidate)
197
+
198
+ # de-duplicate but preserve deterministic order
199
+ seen = set()
200
+ deduped = []
201
+ for x in out:
202
+ if x not in seen:
203
+ seen.add(x)
204
+ deduped.append(x)
205
+
206
+ return deduped
207
+
208
+
209
+ @lru_cache(maxsize=4)
210
+ def fetch_remote_isins(source_name: str) -> tuple[str, ...]:
211
+ source = REMOTE_SOURCES[source_name]
212
+ resp = requests.get(
213
+ source["url"],
214
+ timeout=30,
215
+ headers={"User-Agent": "ISIN-Validator-Demo/1.0"},
216
+ )
217
+ resp.raise_for_status()
218
+
219
+ isins = _extract_isins_from_csv_text(resp.text)
220
+ if not isins:
221
+ raise RuntimeError("Keine gültigen ISINs im Online-Datensatz gefunden.")
222
+
223
+ return tuple(isins)
224
+
225
+
226
+ def _parse_seed(seed_text: str | None) -> int | None:
227
+ s = (seed_text or "").strip()
228
+ if not s:
229
+ return None
230
+ return int(s)
231
+
232
+
233
+ def _render_result_table(rows: list[dict[str, str]], max_rows: int = 20) -> str:
234
+ head = "| # | modus | ISIN | result_main | result_ref | ok |\n|---:|---|---|---|---|---|\n"
235
+ body_lines = []
236
+ for row in rows[:max_rows]:
237
+ body_lines.append(
238
+ f"| {row['idx']} | {row['mode']} | `{row['isin']}` | "
239
+ f"`{row['result_main']}` | `{row['result_ref']}` | {row['ok']} |"
240
+ )
241
+ tail = ""
242
+ if len(rows) > max_rows:
243
+ tail = f"\n\n… weitere {len(rows) - max_rows} Zeilen ausgeblendet."
244
+ return head + "\n".join(body_lines) + tail
245
+
246
+
247
+ def run_online_self_test(
248
+ sample_count: int,
249
+ mode: str,
250
+ seed_text: str,
251
+ source_name: str,
252
+ ) -> str:
253
+ try:
254
+ seed = _parse_seed(seed_text)
255
+ rng = random.Random(seed)
256
+
257
+ dataset = list(fetch_remote_isins(source_name))
258
+ if not dataset:
259
+ return "Fehler: Online-Datensatz leer."
260
+
261
+ n = max(1, min(int(sample_count), len(dataset)))
262
+ sample = rng.sample(dataset, k=n)
263
+
264
+ rows: list[dict[str, str]] = []
265
+ failures: list[dict[str, str]] = []
266
+
267
+ for idx, isin in enumerate(sample, start=1):
268
+ op = mode
269
+ if mode == "mixed":
270
+ op = rng.choice(["compute", "verify"])
271
+
272
+ if op == "verify":
273
+ main = str(validate_isin(isin))
274
+ ref = str(validate_isin_reference(isin))
275
+ ok = (main == "True") and (ref == "True")
276
+ else:
277
+ # compute
278
+ main = complete_isin(isin[:-1])
279
+ ref = isin[:-1] + compute_isin_check_digit_reference(isin[:-1])
280
+ ok = (main == isin) and (ref == isin)
281
+
282
+ row = {
283
+ "idx": str(idx),
284
+ "mode": op,
285
+ "isin": isin,
286
+ "result_main": main,
287
+ "result_ref": ref,
288
+ "ok": "✅" if ok else "❌",
289
+ }
290
+ rows.append(row)
291
+ if not ok:
292
+ failures.append(row)
293
+
294
+ passed = len(rows) - len(failures)
295
+ rate = 100.0 * passed / len(rows)
296
+
297
+ summary = (
298
+ f"## Online-Selbsttest\n\n"
299
+ f"- Quelle: **{source_name}**\n"
300
+ f"- Geladene Datensätze: **{len(dataset)}**\n"
301
+ f"- Stichprobe: **{len(rows)}**\n"
302
+ f"- Modus: **{mode}**\n"
303
+ f"- Seed: **{seed if seed is not None else 'zufällig'}**\n"
304
+ f"- Bestanden: **{passed}/{len(rows)} ({rate:.1f}%)**\n"
305
+ )
306
+
307
+ note = (
308
+ "\n**Hinweis:** Dieser Test vergleicht gegen reale Online-ISINs "
309
+ "und nutzt zusätzlich eine unabhängig formulierte Referenzimplementierung. "
310
+ "Das ist ein starker externer Check, aber kein mathematischer Universalbeweis.\n"
311
+ )
312
+
313
+ if failures:
314
+ fail_block = "\n### Fehlgeschlagene Fälle\n\n" + _render_result_table(
315
+ failures, max_rows=20
316
+ )
317
+ else:
318
+ fail_block = "\n### Erste Stichproben\n\n" + _render_result_table(
319
+ rows, max_rows=20
320
+ )
321
+
322
+ return summary + note + fail_block
323
+
324
+ except requests.RequestException as e:
325
+ return f"Netzwerkfehler beim Laden des Online-Datensatzes:\n\n`{type(e).__name__}: {e}`"
326
+ except Exception as e:
327
+ return f"Fehler im Selbsttest:\n\n`{type(e).__name__}: {e}`"
328
+
329
+
330
+ # ------------------------------------------------------------
331
+ # Gradio UI
332
+ # ------------------------------------------------------------
333
+
334
+ with gr.Blocks() as demo:
335
+ gr.Markdown(
336
+ """
337
+ # ISIN Rechner / Validator
338
+
339
+ Diese App kann:
340
+ 1. eine ISIN-Prüfziffer berechnen,
341
+ 2. eine vollständige ISIN validieren,
342
+ 3. einen Online-Selbsttest gegen reale veröffentlichte ISINs ausführen.
343
+ """
344
+ )
345
+
346
+ with gr.Tab("Manuell"):
347
+ with gr.Row():
348
+ manual_input = gr.Textbox(
349
+ label="ISIN oder ISIN-Body",
350
+ placeholder="z.B. US037833100 oder US0378331005",
351
+ lines=1,
352
+ )
353
+ manual_button = gr.Button("Berechnen / Validieren")
354
+ manual_output = gr.Textbox(label="Ergebnis", lines=10)
355
+
356
+ manual_button.click(
357
+ fn=run_manual_isin_tool,
358
+ inputs=manual_input,
359
+ outputs=manual_output,
360
+ )
361
+
362
+ with gr.Tab("Online-Selbsttest"):
363
+ gr.Markdown(
364
+ """
365
+ Der Selbsttest lädt zufällige echte ISINs aus einem öffentlichen Online-Datensatz,
366
+ wählt eine Stichprobe und prüft dann `compute`, `verify` oder beides gemischt.
367
+ """
368
+ )
369
+
370
+ with gr.Row():
371
+ source_name = gr.Dropdown(
372
+ choices=list(REMOTE_SOURCES.keys()),
373
+ value=list(REMOTE_SOURCES.keys())[0],
374
+ label="Datenquelle",
375
+ )
376
+ mode = gr.Dropdown(
377
+ choices=["compute", "verify", "mixed"],
378
+ value="mixed",
379
+ label="Testmodus",
380
+ )
381
+
382
+ with gr.Row():
383
+ sample_count = gr.Slider(
384
+ minimum=1,
385
+ maximum=200,
386
+ value=25,
387
+ step=1,
388
+ label="Anzahl zufälliger ISINs",
389
+ )
390
+ seed_text = gr.Textbox(
391
+ label="Seed (optional)",
392
+ placeholder="z.B. 42",
393
+ lines=1,
394
+ )
395
+
396
+ online_button = gr.Button("Online-Selbsttest starten")
397
+ online_output = gr.Markdown()
398
+
399
+ online_button.click(
400
+ fn=run_online_self_test,
401
+ inputs=[sample_count, mode, seed_text, source_name],
402
+ outputs=online_output,
403
+ )
404
+
405
+ demo.launch()