Zhe-Zhang commited on
Commit
fea6dd3
·
verified ·
1 Parent(s): 0f24424

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +18 -12
app.py CHANGED
@@ -61,7 +61,6 @@ def build_freq_dict(sentence, MAXES=MAXES, MAX_SHIFT=MAX_SHIFT):
61
  return shift_keys(fhcodes, MAX_SHIFT)
62
 
63
  # --- load models ---
64
- clf = joblib.load("nld.joblib")
65
  vectorizer = joblib.load("nld_vectorizer.joblib")
66
  idx2lang = joblib.load("nld_lang_codes.joblib")
67
 
@@ -77,26 +76,33 @@ model.load_state_dict(torch.load("nld.pth", map_location="cpu"))
77
  model.eval()
78
 
79
  # --- prediction function ---
80
- def detect_lang(src_sentence):
81
- src_sentence = [src_sentence]
82
- X_test = vectorizer.transform(map(build_freq_dict, src_sentence))
83
  if hasattr(X_test, "toarray"):
84
  X_test = X_test.toarray()
85
- Y_logits = model(torch.Tensor(X_test))
86
- pred_languages = torch.argmax(Y_logits, dim=-1).tolist()
87
- return list(map(idx2lang.get, pred_languages))[0]
 
 
 
88
 
89
  # --- Gradio UI ---
90
- with gr.Blocks(title="ZheZhanglanguage detector") as demo:
91
- gr.Markdown("# ZheZhang language detector")
92
  with gr.Row():
93
  with gr.Column():
94
  src_sentence = gr.Textbox(
95
- label="Text", placeholder="Write your text...")
 
96
  with gr.Column():
97
  tgt_sentence = gr.Textbox(
98
- label="Language", placeholder="Language will show here...")
 
 
 
99
  btn = gr.Button("Guess the language!")
100
  btn.click(fn=detect_lang, inputs=[src_sentence], outputs=[tgt_sentence])
101
 
102
- demo.launch()
 
61
  return shift_keys(fhcodes, MAX_SHIFT)
62
 
63
  # --- load models ---
 
64
  vectorizer = joblib.load("nld_vectorizer.joblib")
65
  idx2lang = joblib.load("nld_lang_codes.joblib")
66
 
 
76
  model.eval()
77
 
78
  # --- prediction function ---
79
+ def detect_lang(src_sentence: str):
80
+ feat_dict = build_freq_dict(src_sentence)
81
+ X_test = vectorizer.transform([feat_dict]) # ✅ 用 list 包起来
82
  if hasattr(X_test, "toarray"):
83
  X_test = X_test.toarray()
84
+ X_test = torch.from_numpy(X_test.astype("float32"))
85
+
86
+ with torch.no_grad():
87
+ logits = model(X_test)
88
+ pred_idx = torch.argmax(logits, dim=-1).item()
89
+ return idx2lang[pred_idx]
90
 
91
  # --- Gradio UI ---
92
+ with gr.Blocks(title="Antons language detector") as demo:
93
+ gr.Markdown("# Antons language detector")
94
  with gr.Row():
95
  with gr.Column():
96
  src_sentence = gr.Textbox(
97
+ label="Text", placeholder="Write your text..."
98
+ )
99
  with gr.Column():
100
  tgt_sentence = gr.Textbox(
101
+ label="Language",
102
+ placeholder="Language will show here...",
103
+ interactive=False # ✅ 输出框不可编辑
104
+ )
105
  btn = gr.Button("Guess the language!")
106
  btn.click(fn=detect_lang, inputs=[src_sentence], outputs=[tgt_sentence])
107
 
108
+ demo.launch()