Spaces:
Sleeping
Sleeping
Upload 3 files
Browse files- README.md +34 -7
- app.py +514 -0
- requirements.txt +4 -0
README.md
CHANGED
|
@@ -1,13 +1,40 @@
|
|
| 1 |
---
|
| 2 |
-
title: Indus Script
|
| 3 |
-
emoji:
|
| 4 |
-
colorFrom:
|
| 5 |
-
colorTo:
|
| 6 |
sdk: gradio
|
| 7 |
-
sdk_version:
|
| 8 |
app_file: app.py
|
| 9 |
pinned: false
|
| 10 |
-
license:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
---
|
| 12 |
|
| 13 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
+
title: Indus Script Models
|
| 3 |
+
emoji: πΊ
|
| 4 |
+
colorFrom: indigo
|
| 5 |
+
colorTo: purple
|
| 6 |
sdk: gradio
|
| 7 |
+
sdk_version: 4.44.0
|
| 8 |
app_file: app.py
|
| 9 |
pinned: false
|
| 10 |
+
license: cc-by-4.0
|
| 11 |
+
tags:
|
| 12 |
+
- indus-script
|
| 13 |
+
- ancient-scripts
|
| 14 |
+
- archaeology
|
| 15 |
+
- nlp
|
| 16 |
---
|
| 17 |
|
| 18 |
+
# Indus Script β Interactive Demo
|
| 19 |
+
|
| 20 |
+
Six tools for exploring the undeciphered Indus Valley Script (2600β1900 BCE).
|
| 21 |
+
|
| 22 |
+
## Tabs
|
| 23 |
+
|
| 24 |
+
| Tab | What it does |
|
| 25 |
+
|---|---|
|
| 26 |
+
| Sign Lookup | Enter T604 or 604 β see glyph, role, frequency |
|
| 27 |
+
| Validate Sequence | Enter any sequence β get BERT/N-gram/ELECTRA scores |
|
| 28 |
+
| Predict Masked Sign | Enter T638 [MASK] T420 β model predicts the missing sign |
|
| 29 |
+
| Generate Sequence | One click β generates a new grammatically valid inscription |
|
| 30 |
+
| Sign Explorer | Browse all 641 signs filtered by role (PREFIX/SUFFIX/CORE/RARE) |
|
| 31 |
+
| Sign β Number | Convert between T604 and 604 |
|
| 32 |
+
|
| 33 |
+
## Models used
|
| 34 |
+
|
| 35 |
+
- TinyBERT (classifier + MLM)
|
| 36 |
+
- N-gram RTL
|
| 37 |
+
- ELECTRA discriminator
|
| 38 |
+
- NanoGPT generator
|
| 39 |
+
|
| 40 |
+
All models from [hellosindh/indus-script-models](https://huggingface.co/hellosindh/indus-script-models)
|
app.py
ADDED
|
@@ -0,0 +1,514 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Indus Script β Interactive Demo
|
| 3 |
+
HuggingFace Space using models from hellosindh/indus-script-models
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import gradio as gr
|
| 7 |
+
import torch
|
| 8 |
+
import torch.nn as nn
|
| 9 |
+
import torch.nn.functional as F
|
| 10 |
+
import pickle
|
| 11 |
+
import json
|
| 12 |
+
import math
|
| 13 |
+
import sys
|
| 14 |
+
from pathlib import Path
|
| 15 |
+
from huggingface_hub import snapshot_download
|
| 16 |
+
|
| 17 |
+
# ββ Load models once at startup ββββββββββββββββββββββββββββββββ
|
| 18 |
+
MODEL_REPO = "hellosindh/indus-script-models"
|
| 19 |
+
LOCAL_DIR = Path("indus_models")
|
| 20 |
+
|
| 21 |
+
def setup():
|
| 22 |
+
if not LOCAL_DIR.exists() or not (LOCAL_DIR / "models" / "nanogpt_indus.pt").exists():
|
| 23 |
+
print("Downloading models...")
|
| 24 |
+
snapshot_download(repo_id=MODEL_REPO, local_dir=str(LOCAL_DIR))
|
| 25 |
+
return LOCAL_DIR / "models", LOCAL_DIR / "data"
|
| 26 |
+
|
| 27 |
+
MODEL_DIR, DATA_DIR = setup()
|
| 28 |
+
sys.path.insert(0, str(LOCAL_DIR))
|
| 29 |
+
|
| 30 |
+
device = torch.device("cpu")
|
| 31 |
+
BOS_ID, EOS_ID, PAD_ID = 814, 815, 816
|
| 32 |
+
|
| 33 |
+
# Load glyph map
|
| 34 |
+
with open(DATA_DIR / "id_to_glyph.json", encoding="utf-8") as f:
|
| 35 |
+
GLYPH = json.load(f)
|
| 36 |
+
|
| 37 |
+
def G(tid):
|
| 38 |
+
return GLYPH.get(str(tid), "")
|
| 39 |
+
|
| 40 |
+
# Load sign index if available
|
| 41 |
+
SIGN_INDEX = {}
|
| 42 |
+
sign_idx_path = DATA_DIR / "sign_index.json"
|
| 43 |
+
if sign_idx_path.exists():
|
| 44 |
+
with open(sign_idx_path, encoding="utf-8") as f:
|
| 45 |
+
data = json.load(f)
|
| 46 |
+
for s in data.get("signs", []):
|
| 47 |
+
SIGN_INDEX[s["mahadevan_id"]] = s
|
| 48 |
+
|
| 49 |
+
# ββ Load all models ββββββββββββββββββββββββββββββββββββββββββββ
|
| 50 |
+
from transformers import (BertForMaskedLM, BertForSequenceClassification,
|
| 51 |
+
BertModel, BertConfig, PreTrainedTokenizerFast)
|
| 52 |
+
|
| 53 |
+
tok_path = DATA_DIR / "indus_tokenizer"
|
| 54 |
+
TOK = PreTrainedTokenizerFast.from_pretrained(str(tok_path))
|
| 55 |
+
|
| 56 |
+
CLS = BertForSequenceClassification.from_pretrained(
|
| 57 |
+
str(MODEL_DIR / "cls")).to(device).eval()
|
| 58 |
+
MLM = BertForMaskedLM.from_pretrained(
|
| 59 |
+
str(MODEL_DIR / "mlm")).to(device).eval()
|
| 60 |
+
|
| 61 |
+
class ElectraDisc(nn.Module):
|
| 62 |
+
def __init__(self, cfg):
|
| 63 |
+
super().__init__()
|
| 64 |
+
self.bert = BertModel(cfg)
|
| 65 |
+
self.classifier = nn.Linear(cfg.hidden_size, 2)
|
| 66 |
+
self.dropout = nn.Dropout(0.1)
|
| 67 |
+
def forward(self, input_ids, attention_mask):
|
| 68 |
+
return self.classifier(self.dropout(
|
| 69 |
+
self.bert(input_ids=input_ids, attention_mask=attention_mask).last_hidden_state))
|
| 70 |
+
|
| 71 |
+
with open(MODEL_DIR / "electra" / "discriminator_config.json") as f:
|
| 72 |
+
ecfg = json.load(f)
|
| 73 |
+
ELEC = ElectraDisc(BertConfig(**ecfg))
|
| 74 |
+
ELEC.load_state_dict(torch.load(MODEL_DIR / "electra" / "discriminator.pt",
|
| 75 |
+
map_location=device, weights_only=True))
|
| 76 |
+
ELEC = ELEC.to(device).eval()
|
| 77 |
+
ELEC_TOK = PreTrainedTokenizerFast.from_pretrained(str(MODEL_DIR / "electra"))
|
| 78 |
+
|
| 79 |
+
import importlib.util
|
| 80 |
+
spec = importlib.util.spec_from_file_location("indus_ngram", LOCAL_DIR / "indus_ngram.py")
|
| 81 |
+
mod = importlib.util.module_from_spec(spec); spec.loader.exec_module(mod)
|
| 82 |
+
with open(MODEL_DIR / "ngram_model.pkl", "rb") as f:
|
| 83 |
+
NGRAM = pickle.load(f)
|
| 84 |
+
|
| 85 |
+
# NanoGPT
|
| 86 |
+
class CSA(nn.Module):
|
| 87 |
+
def __init__(self, c):
|
| 88 |
+
super().__init__()
|
| 89 |
+
self.nh=c["n_head"]; self.ne=c["n_embd"]; self.hd=c["n_embd"]//c["n_head"]
|
| 90 |
+
self.qkv=nn.Linear(c["n_embd"],3*c["n_embd"],bias=False)
|
| 91 |
+
self.proj=nn.Linear(c["n_embd"],c["n_embd"],bias=False)
|
| 92 |
+
self.drop=nn.Dropout(c["dropout"])
|
| 93 |
+
ml=c["block_size"]
|
| 94 |
+
self.register_buffer("mask",torch.tril(torch.ones(ml,ml)).view(1,1,ml,ml))
|
| 95 |
+
def forward(self,x):
|
| 96 |
+
B,T,C=x.shape
|
| 97 |
+
q,k,v=self.qkv(x).split(self.ne,dim=2)
|
| 98 |
+
sh=lambda t:t.view(B,T,self.nh,self.hd).transpose(1,2)
|
| 99 |
+
q,k,v=sh(q),sh(k),sh(v)
|
| 100 |
+
a=(q@k.transpose(-2,-1))/math.sqrt(self.hd)
|
| 101 |
+
a=a.masked_fill(self.mask[:,:,:T,:T]==0,float("-inf"))
|
| 102 |
+
return self.proj((self.drop(F.softmax(a,dim=-1))@v).transpose(1,2).contiguous().view(B,T,C))
|
| 103 |
+
|
| 104 |
+
class TB(nn.Module):
|
| 105 |
+
def __init__(self,c):
|
| 106 |
+
super().__init__()
|
| 107 |
+
self.ln1=nn.LayerNorm(c["n_embd"]); self.attn=CSA(c)
|
| 108 |
+
self.ln2=nn.LayerNorm(c["n_embd"])
|
| 109 |
+
self.ffn=nn.Sequential(nn.Linear(c["n_embd"],4*c["n_embd"]),nn.GELU(),
|
| 110 |
+
nn.Linear(4*c["n_embd"],c["n_embd"]),nn.Dropout(c["dropout"]))
|
| 111 |
+
def forward(self,x): return x+self.ffn(self.ln2(x+self.attn(self.ln1(x))))
|
| 112 |
+
|
| 113 |
+
class GPT(nn.Module):
|
| 114 |
+
def __init__(self,c):
|
| 115 |
+
super().__init__()
|
| 116 |
+
self.cfg=c
|
| 117 |
+
self.tok_emb=nn.Embedding(c["vocab_size"],c["n_embd"])
|
| 118 |
+
self.pos_emb=nn.Embedding(c["block_size"],c["n_embd"])
|
| 119 |
+
self.drop=nn.Dropout(c["dropout"])
|
| 120 |
+
self.blocks=nn.ModuleList([TB(c) for _ in range(c["n_layer"])])
|
| 121 |
+
self.ln_f=nn.LayerNorm(c["n_embd"])
|
| 122 |
+
self.head=nn.Linear(c["n_embd"],c["vocab_size"],bias=False)
|
| 123 |
+
self.tok_emb.weight=self.head.weight
|
| 124 |
+
def forward(self,idx):
|
| 125 |
+
B,T=idx.shape
|
| 126 |
+
x=self.drop(self.tok_emb(idx)+self.pos_emb(torch.arange(T,device=idx.device).unsqueeze(0)))
|
| 127 |
+
for b in self.blocks: x=b(x)
|
| 128 |
+
return self.head(self.ln_f(x))
|
| 129 |
+
@torch.no_grad()
|
| 130 |
+
def generate(self,temperature=0.85,top_k=40,max_len=10):
|
| 131 |
+
self.eval()
|
| 132 |
+
idx=torch.tensor([[BOS_ID]],device=device); gen=[]
|
| 133 |
+
for _ in range(max_len):
|
| 134 |
+
logits=self(idx[:,-self.cfg["block_size"]:])[: ,-1,:]/temperature
|
| 135 |
+
logits[:,PAD_ID]=logits[:,BOS_ID]=logits[:,EOS_ID]=float("-inf")
|
| 136 |
+
if top_k>0:
|
| 137 |
+
v,_=torch.topk(logits,min(top_k,logits.size(-1)))
|
| 138 |
+
logits[logits<v[:,[-1]]]=float("-inf")
|
| 139 |
+
nxt=torch.multinomial(F.softmax(logits,dim=-1),1)
|
| 140 |
+
if nxt.item()==EOS_ID: break
|
| 141 |
+
gen.append(nxt.item())
|
| 142 |
+
idx=torch.cat([idx,nxt],dim=1)
|
| 143 |
+
return list(reversed(gen))
|
| 144 |
+
|
| 145 |
+
ckpt = torch.load(MODEL_DIR / "nanogpt_indus.pt", map_location=device, weights_only=False)
|
| 146 |
+
GPT_MODEL = GPT(ckpt["cfg"])
|
| 147 |
+
GPT_MODEL.load_state_dict(ckpt["model_state"])
|
| 148 |
+
GPT_MODEL = GPT_MODEL.to(device).eval()
|
| 149 |
+
|
| 150 |
+
print("All models loaded.")
|
| 151 |
+
|
| 152 |
+
# ββ Scoring helpers ββββββββββββββββββββββββββββββββββββββββββββ
|
| 153 |
+
def parse_seq(text):
|
| 154 |
+
tokens = text.strip().upper().split()
|
| 155 |
+
ids = []
|
| 156 |
+
for t in tokens:
|
| 157 |
+
if t == "[MASK]":
|
| 158 |
+
ids.append(None)
|
| 159 |
+
else:
|
| 160 |
+
t = t.lstrip("T")
|
| 161 |
+
try: ids.append(int(t))
|
| 162 |
+
except: pass
|
| 163 |
+
return ids
|
| 164 |
+
|
| 165 |
+
def bert_score(seq):
|
| 166 |
+
enc = TOK(" ".join(f"T{t}" for t in seq), return_tensors="pt",
|
| 167 |
+
truncation=True, max_length=32).to(device)
|
| 168 |
+
with torch.no_grad():
|
| 169 |
+
return float(torch.softmax(CLS(**enc).logits, dim=-1)[0][1])
|
| 170 |
+
|
| 171 |
+
def ngram_score(seq):
|
| 172 |
+
return NGRAM.validity_score(seq)
|
| 173 |
+
|
| 174 |
+
def electra_score(seq):
|
| 175 |
+
enc = ELEC_TOK(" ".join(f"T{t}" for t in seq), return_tensors="pt",
|
| 176 |
+
truncation=True, max_length=32).to(device)
|
| 177 |
+
with torch.no_grad():
|
| 178 |
+
logits = ELEC(enc["input_ids"], enc["attention_mask"])
|
| 179 |
+
probs = torch.softmax(logits[0], dim=-1)
|
| 180 |
+
n = min(len(seq), probs.shape[0]-1)
|
| 181 |
+
return float(probs[1:n+1, 0].mean())
|
| 182 |
+
|
| 183 |
+
def ensemble(seq):
|
| 184 |
+
b = bert_score(seq)
|
| 185 |
+
n = ngram_score(seq)
|
| 186 |
+
e = electra_score(seq)
|
| 187 |
+
return 0.50*b + 0.25*n + 0.25*e, b, n, e
|
| 188 |
+
|
| 189 |
+
def seq_to_glyphs(seq):
|
| 190 |
+
return "".join(G(t) for t in seq if t is not None)
|
| 191 |
+
|
| 192 |
+
def format_glyphs(seq):
|
| 193 |
+
parts = []
|
| 194 |
+
for t in seq:
|
| 195 |
+
if t is None:
|
| 196 |
+
parts.append("[?]")
|
| 197 |
+
else:
|
| 198 |
+
g = G(t)
|
| 199 |
+
parts.append(g if g else f"T{t}")
|
| 200 |
+
return " ".join(parts)
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
# ββ Tab 1: Sign Lookup βββββββββββββββββββββββββββββββββββββββββ
|
| 204 |
+
def sign_lookup(query):
|
| 205 |
+
query = query.strip().upper().lstrip("T")
|
| 206 |
+
try:
|
| 207 |
+
tid = int(query)
|
| 208 |
+
except:
|
| 209 |
+
return "Enter a sign ID like **604** or **T604**"
|
| 210 |
+
|
| 211 |
+
glyph = G(tid)
|
| 212 |
+
info = SIGN_INDEX.get(tid, {})
|
| 213 |
+
|
| 214 |
+
role = info.get("role", "unknown")
|
| 215 |
+
count = info.get("corpus_count", 0)
|
| 216 |
+
freq = info.get("corpus_freq_pct", 0)
|
| 217 |
+
start_rate = info.get("start_rate_pct", 0)
|
| 218 |
+
end_rate = info.get("end_rate_pct", 0)
|
| 219 |
+
|
| 220 |
+
role_desc = {
|
| 221 |
+
"PREFIX" : "Appears at the RTL terminal position (reading end). Likely a title or determinative marker.",
|
| 222 |
+
"SUFFIX" : "Appears at the RTL initial position (reading start). Likely a closing or grammatical marker.",
|
| 223 |
+
"CORE" : "Appears in medial positions. Core content sign.",
|
| 224 |
+
"RARE" : "Appears rarely in corpus (β€50 times). Role uncertain.",
|
| 225 |
+
"UNSEEN" : "Not found in training corpus.",
|
| 226 |
+
}.get(role, "")
|
| 227 |
+
|
| 228 |
+
result = f"""## T{tid}
|
| 229 |
+
|
| 230 |
+
**Glyph:** {glyph if glyph else '(install Indus font to see glyph)'}
|
| 231 |
+
|
| 232 |
+
**Role:** {role}
|
| 233 |
+
{role_desc}
|
| 234 |
+
|
| 235 |
+
**Corpus statistics:**
|
| 236 |
+
- Appears **{count:,}** times ({freq:.3f}% of all tokens)
|
| 237 |
+
- At sequence start: **{start_rate:.2f}%** of inscriptions
|
| 238 |
+
- At sequence end: **{end_rate:.2f}%** of inscriptions
|
| 239 |
+
"""
|
| 240 |
+
return result
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
# ββ Tab 2: Validate sequence βββββββββββββββββββββββββββββββββββ
|
| 244 |
+
def validate_sequence(text):
|
| 245 |
+
seq = [t for t in parse_seq(text) if t is not None]
|
| 246 |
+
if len(seq) < 2:
|
| 247 |
+
return "Enter at least 2 signs, e.g. **T638 T177 T420**"
|
| 248 |
+
|
| 249 |
+
ens, b, n, e = ensemble(seq)
|
| 250 |
+
glyphs = format_glyphs(seq)
|
| 251 |
+
seq_str = " ".join(f"T{t}" for t in seq)
|
| 252 |
+
|
| 253 |
+
if ens >= 0.85:
|
| 254 |
+
verdict = "β
VALID β strong grammatical structure"
|
| 255 |
+
color = "green"
|
| 256 |
+
elif ens >= 0.70:
|
| 257 |
+
verdict = "β οΈ UNCERTAIN β some grammatical structure"
|
| 258 |
+
color = "orange"
|
| 259 |
+
else:
|
| 260 |
+
verdict = "β INVALID β weak or no grammatical structure"
|
| 261 |
+
color = "red"
|
| 262 |
+
|
| 263 |
+
# Check sign roles
|
| 264 |
+
roles = []
|
| 265 |
+
for t in seq:
|
| 266 |
+
info = SIGN_INDEX.get(t, {})
|
| 267 |
+
role = info.get("role", "?")
|
| 268 |
+
roles.append(f"T{t}={role}")
|
| 269 |
+
|
| 270 |
+
result = f"""## Result
|
| 271 |
+
|
| 272 |
+
**Sequence:** {seq_str}
|
| 273 |
+
**Glyphs:** {glyphs}
|
| 274 |
+
|
| 275 |
+
---
|
| 276 |
+
|
| 277 |
+
| Model | Score |
|
| 278 |
+
|---|---|
|
| 279 |
+
| TinyBERT | {b:.4f} |
|
| 280 |
+
| N-gram RTL | {n:.4f} |
|
| 281 |
+
| ELECTRA | {e:.4f} |
|
| 282 |
+
| **Ensemble** | **{ens:.4f}** |
|
| 283 |
+
|
| 284 |
+
**Verdict:** {verdict}
|
| 285 |
+
|
| 286 |
+
**Sign roles:** {', '.join(roles)}
|
| 287 |
+
"""
|
| 288 |
+
return result
|
| 289 |
+
|
| 290 |
+
|
| 291 |
+
# ββ Tab 3: Predict masked sign βββββββββββββββββββββββββββββββββ
|
| 292 |
+
def predict_mask(text):
|
| 293 |
+
seq = parse_seq(text)
|
| 294 |
+
if None not in seq:
|
| 295 |
+
return "Include **[MASK]** in your sequence, e.g. **T638 [MASK] T420**"
|
| 296 |
+
if len(seq) < 2:
|
| 297 |
+
return "Enter at least 2 tokens including [MASK]"
|
| 298 |
+
|
| 299 |
+
parts = ["[MASK]" if t is None else f"T{t}" for t in seq]
|
| 300 |
+
enc = TOK(" ".join(parts), return_tensors="pt",
|
| 301 |
+
truncation=True, max_length=32).to(device)
|
| 302 |
+
with torch.no_grad():
|
| 303 |
+
logits = MLM(**enc).logits
|
| 304 |
+
|
| 305 |
+
results = []
|
| 306 |
+
for pos, val in enumerate(seq):
|
| 307 |
+
if val is not None: continue
|
| 308 |
+
tp, ti = torch.softmax(logits[0, pos+1], dim=-1).topk(8)
|
| 309 |
+
preds = []
|
| 310 |
+
for p, tid in zip(tp.tolist(), ti.tolist()):
|
| 311 |
+
ts = TOK.convert_ids_to_tokens([tid])[0]
|
| 312 |
+
if ts.startswith("T") and ts[1:].isdigit():
|
| 313 |
+
sign_id = int(ts[1:])
|
| 314 |
+
g = G(sign_id)
|
| 315 |
+
info = SIGN_INDEX.get(sign_id, {})
|
| 316 |
+
role = info.get("role", "?")
|
| 317 |
+
preds.append((sign_id, g, role, p))
|
| 318 |
+
|
| 319 |
+
if preds:
|
| 320 |
+
table = "| Sign | Glyph | Role | Confidence |\n|---|---|---|---|\n"
|
| 321 |
+
for sid, g, role, prob in preds[:6]:
|
| 322 |
+
table += f"| T{sid} | {g} | {role} | {prob*100:.1f}% |\n"
|
| 323 |
+
results.append(f"**Position {pos+1} β top predictions:**\n\n{table}")
|
| 324 |
+
|
| 325 |
+
return "\n\n".join(results) if results else "No predictions found"
|
| 326 |
+
|
| 327 |
+
|
| 328 |
+
# ββ Tab 4: Generate ββββββββββββββββββββββββββββββββββββββββββββ
|
| 329 |
+
def generate_sequence(temperature, max_len):
|
| 330 |
+
seq = GPT_MODEL.generate(temperature=float(temperature), top_k=40,
|
| 331 |
+
max_len=int(max_len))
|
| 332 |
+
if len(seq) < 2:
|
| 333 |
+
return "Generation failed β try again"
|
| 334 |
+
|
| 335 |
+
ens, b, n, e = ensemble(seq)
|
| 336 |
+
glyphs = format_glyphs(seq)
|
| 337 |
+
seq_str = " ".join(f"T{t}" for t in seq)
|
| 338 |
+
roles = []
|
| 339 |
+
for t in seq:
|
| 340 |
+
info = SIGN_INDEX.get(t, {})
|
| 341 |
+
roles.append(info.get("role", "?")[0]) # first letter P/S/C/R
|
| 342 |
+
|
| 343 |
+
verdict = "β
VALID" if ens >= 0.85 else "β οΈ UNCERTAIN" if ens >= 0.70 else "β INVALID"
|
| 344 |
+
|
| 345 |
+
result = f"""## Generated Sequence
|
| 346 |
+
|
| 347 |
+
**Sequence:** {seq_str}
|
| 348 |
+
**Glyphs:** {glyphs}
|
| 349 |
+
**Roles:** {' β '.join(roles)}
|
| 350 |
+
|
| 351 |
+
| Model | Score |
|
| 352 |
+
|---|---|
|
| 353 |
+
| TinyBERT | {b:.4f} |
|
| 354 |
+
| N-gram RTL | {n:.4f} |
|
| 355 |
+
| ELECTRA | {e:.4f} |
|
| 356 |
+
| **Ensemble** | **{ens:.4f}** |
|
| 357 |
+
|
| 358 |
+
**Verdict:** {verdict}
|
| 359 |
+
"""
|
| 360 |
+
return result
|
| 361 |
+
|
| 362 |
+
|
| 363 |
+
# ββ Tab 5: Sign Explorer βββββββββββββββββββββββββββββββββββββββ
|
| 364 |
+
def explore_signs(role_filter, min_count):
|
| 365 |
+
if not SIGN_INDEX:
|
| 366 |
+
return "Sign index not available"
|
| 367 |
+
|
| 368 |
+
signs = [s for s in SIGN_INDEX.values()
|
| 369 |
+
if (role_filter == "ALL" or s.get("role") == role_filter)
|
| 370 |
+
and s.get("corpus_count", 0) >= int(min_count)]
|
| 371 |
+
signs.sort(key=lambda x: -x.get("corpus_count", 0))
|
| 372 |
+
|
| 373 |
+
if not signs:
|
| 374 |
+
return "No signs found with these filters"
|
| 375 |
+
|
| 376 |
+
rows = "| Sign | Glyph | Role | Count | Freq% | Start% | End% |\n"
|
| 377 |
+
rows += "|---|---|---|---|---|---|---|\n"
|
| 378 |
+
for s in signs[:50]:
|
| 379 |
+
tid = s.get("mahadevan_id", s.get("sign_id_num","?"))
|
| 380 |
+
g = G(tid) if isinstance(tid, int) else ""
|
| 381 |
+
role = s.get("role","?")
|
| 382 |
+
count = s.get("corpus_count",0)
|
| 383 |
+
freq = s.get("corpus_freq_pct",0)
|
| 384 |
+
start = s.get("start_rate_pct",0)
|
| 385 |
+
end = s.get("end_rate_pct",0)
|
| 386 |
+
rows += f"| T{tid} | {g} | {role} | {count:,} | {freq:.2f} | {start:.2f} | {end:.2f} |\n"
|
| 387 |
+
|
| 388 |
+
header = f"Showing {min(50,len(signs))} of {len(signs)} signs"
|
| 389 |
+
return f"{header}\n\n{rows}"
|
| 390 |
+
|
| 391 |
+
|
| 392 |
+
# ββ Tab 6: Convert sign β number ββββββββββββββββββββββββββββββ
|
| 393 |
+
def convert_sign(query):
|
| 394 |
+
query = query.strip()
|
| 395 |
+
lines = query.split()
|
| 396 |
+
results = []
|
| 397 |
+
for token in lines:
|
| 398 |
+
upper = token.upper()
|
| 399 |
+
if upper.startswith("T") and upper[1:].isdigit():
|
| 400 |
+
tid = int(upper[1:])
|
| 401 |
+
g = G(tid)
|
| 402 |
+
results.append(f"**{token}** β Sign number **{tid}** | Glyph: {g if g else '(font needed)'}")
|
| 403 |
+
elif token.isdigit():
|
| 404 |
+
tid = int(token)
|
| 405 |
+
g = G(tid)
|
| 406 |
+
results.append(f"**{token}** β Sign ID **T{tid}** | Glyph: {g if g else '(font needed)'}")
|
| 407 |
+
else:
|
| 408 |
+
results.append(f"**{token}** β not recognised (use format: 604 or T604)")
|
| 409 |
+
return "\n\n".join(results) if results else "Enter sign IDs separated by spaces"
|
| 410 |
+
|
| 411 |
+
|
| 412 |
+
# ββ Build Gradio UI ββββββββββββββββββββββββββββββββββββββββββββ
|
| 413 |
+
with gr.Blocks(title="Indus Script Models", theme=gr.themes.Soft()) as demo:
|
| 414 |
+
gr.Markdown("""
|
| 415 |
+
# πΊ Indus Script β Interactive Demo
|
| 416 |
+
Models trained on 3,310 real archaeological inscriptions from the Indus Valley civilization (2600β1900 BCE).
|
| 417 |
+
Install the **Indus Brahmi font** to see actual glyphs. Without the font, glyph fields show as boxes.
|
| 418 |
+
""")
|
| 419 |
+
|
| 420 |
+
with gr.Tabs():
|
| 421 |
+
|
| 422 |
+
# Tab 1 β Sign Lookup
|
| 423 |
+
with gr.TabItem("π Sign Lookup"):
|
| 424 |
+
gr.Markdown("Look up any sign by its ID. Enter a number like `604` or `T638`.")
|
| 425 |
+
with gr.Row():
|
| 426 |
+
lookup_input = gr.Textbox(label="Sign ID", placeholder="604 or T604", scale=1)
|
| 427 |
+
lookup_button = gr.Button("Look up", variant="primary", scale=0)
|
| 428 |
+
lookup_output = gr.Markdown()
|
| 429 |
+
lookup_button.click(sign_lookup, inputs=lookup_input, outputs=lookup_output)
|
| 430 |
+
lookup_input.submit(sign_lookup, inputs=lookup_input, outputs=lookup_output)
|
| 431 |
+
|
| 432 |
+
# Tab 2 β Validate
|
| 433 |
+
with gr.TabItem("β
Validate Sequence"):
|
| 434 |
+
gr.Markdown("Enter an Indus Script sequence to check if it is grammatically valid.")
|
| 435 |
+
with gr.Row():
|
| 436 |
+
val_input = gr.Textbox(label="Sequence",
|
| 437 |
+
placeholder="T638 T177 T420 T122",
|
| 438 |
+
value="T638 T177 T420 T122", scale=3)
|
| 439 |
+
val_button = gr.Button("Validate", variant="primary", scale=0)
|
| 440 |
+
val_output = gr.Markdown()
|
| 441 |
+
val_button.click(validate_sequence, inputs=val_input, outputs=val_output)
|
| 442 |
+
val_input.submit(validate_sequence, inputs=val_input, outputs=val_output)
|
| 443 |
+
gr.Examples(
|
| 444 |
+
examples=[["T638 T177 T420 T122"],["T604 T123 T609"],
|
| 445 |
+
["T406 T638 T243"],["T101 T741"],
|
| 446 |
+
["T122 T638 T177"],["T999 T888"]],
|
| 447 |
+
inputs=val_input)
|
| 448 |
+
|
| 449 |
+
# Tab 3 β Predict Mask
|
| 450 |
+
with gr.TabItem("π― Predict Masked Sign"):
|
| 451 |
+
gr.Markdown("Replace one sign with `[MASK]` β the model predicts what sign belongs there.")
|
| 452 |
+
with gr.Row():
|
| 453 |
+
mask_input = gr.Textbox(label="Sequence with [MASK]",
|
| 454 |
+
placeholder="T638 [MASK] T420 T122",
|
| 455 |
+
value="T638 [MASK] T420 T122", scale=3)
|
| 456 |
+
mask_button = gr.Button("Predict", variant="primary", scale=0)
|
| 457 |
+
mask_output = gr.Markdown()
|
| 458 |
+
mask_button.click(predict_mask, inputs=mask_input, outputs=mask_output)
|
| 459 |
+
mask_input.submit(predict_mask, inputs=mask_input, outputs=mask_output)
|
| 460 |
+
gr.Examples(
|
| 461 |
+
examples=[["T638 [MASK] T420 T122"],["T604 [MASK] T609"],
|
| 462 |
+
["[MASK] T177 T420"],["T406 T638 [MASK]"]],
|
| 463 |
+
inputs=mask_input)
|
| 464 |
+
|
| 465 |
+
# Tab 4 β Generate
|
| 466 |
+
with gr.TabItem("β‘ Generate Sequence"):
|
| 467 |
+
gr.Markdown("Generate a new Indus Script sequence using NanoGPT.")
|
| 468 |
+
with gr.Row():
|
| 469 |
+
temp_slider = gr.Slider(0.7, 1.4, value=0.85, step=0.05,
|
| 470 |
+
label="Temperature (higher = more random)")
|
| 471 |
+
maxlen_slider = gr.Slider(3, 15, value=8, step=1,
|
| 472 |
+
label="Max length")
|
| 473 |
+
gen_button = gr.Button("Generate", variant="primary")
|
| 474 |
+
gen_output = gr.Markdown()
|
| 475 |
+
gen_button.click(generate_sequence,
|
| 476 |
+
inputs=[temp_slider, maxlen_slider],
|
| 477 |
+
outputs=gen_output)
|
| 478 |
+
|
| 479 |
+
# Tab 5 β Sign Explorer
|
| 480 |
+
with gr.TabItem("π Sign Explorer"):
|
| 481 |
+
gr.Markdown("Browse all 641 Indus signs filtered by grammatical role.")
|
| 482 |
+
with gr.Row():
|
| 483 |
+
role_dd = gr.Dropdown(["ALL","PREFIX","SUFFIX","CORE","RARE","UNSEEN"],
|
| 484 |
+
value="ALL", label="Role filter")
|
| 485 |
+
count_sl = gr.Slider(0, 200, value=0, step=10,
|
| 486 |
+
label="Min corpus count")
|
| 487 |
+
exp_button = gr.Button("Show signs", variant="primary")
|
| 488 |
+
exp_output = gr.Markdown()
|
| 489 |
+
exp_button.click(explore_signs, inputs=[role_dd, count_sl], outputs=exp_output)
|
| 490 |
+
|
| 491 |
+
# Tab 6 β Convert
|
| 492 |
+
with gr.TabItem("π Sign β Number"):
|
| 493 |
+
gr.Markdown("""
|
| 494 |
+
Convert between sign IDs and numbers.
|
| 495 |
+
- Enter `604` β get `T604` and its glyph
|
| 496 |
+
- Enter `T638` β get `638` and its glyph
|
| 497 |
+
- Enter multiple separated by spaces: `604 638 177`
|
| 498 |
+
""")
|
| 499 |
+
with gr.Row():
|
| 500 |
+
conv_input = gr.Textbox(label="Sign ID(s)",
|
| 501 |
+
placeholder="604 or T638 or 604 638 177",
|
| 502 |
+
scale=3)
|
| 503 |
+
conv_button = gr.Button("Convert", variant="primary", scale=0)
|
| 504 |
+
conv_output = gr.Markdown()
|
| 505 |
+
conv_button.click(convert_sign, inputs=conv_input, outputs=conv_output)
|
| 506 |
+
conv_input.submit(convert_sign, inputs=conv_input, outputs=conv_output)
|
| 507 |
+
|
| 508 |
+
gr.Markdown("""
|
| 509 |
+
---
|
| 510 |
+
**Models:** [hellosindh/indus-script-models](https://huggingface.co/hellosindh/indus-script-models) |
|
| 511 |
+
**Dataset:** [hellosindh/indus-script-synthetic](https://huggingface.co/datasets/hellosindh/indus-script-synthetic)
|
| 512 |
+
""")
|
| 513 |
+
|
| 514 |
+
demo.launch()
|
requirements.txt
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
torch
|
| 2 |
+
transformers
|
| 3 |
+
gradio
|
| 4 |
+
huggingface_hub
|