boffire commited on
Commit
9349334
·
verified ·
1 Parent(s): 4f83173

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +143 -0
app.py ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import fasttext
2
+ from huggingface_hub import hf_hub_download
3
+ import regex
4
+ import gradio as gr
5
+ import os
6
+
7
+ # Preprocessing patterns
8
+ NONWORD_REPLACE_STR = r"[^\p{Word}\p{Zs}]|\d"
9
+ NONWORD_REPLACE_PATTERN = regex.compile(NONWORD_REPLACE_STR)
10
+ SPACE_PATTERN = regex.compile(r"\s\s+")
11
+
12
+ def preprocess(text):
13
+ """Preprocess text for language identification."""
14
+ text = text.strip().replace('\n', ' ').lower()
15
+ text = regex.sub(SPACE_PATTERN, " ", text)
16
+ text = regex.sub(NONWORD_REPLACE_PATTERN, "", text)
17
+ return text
18
+
19
+ # Load model once at startup
20
+ print("Loading OpenLID-v3 model...")
21
+ model_path = hf_hub_download(
22
+ repo_id="HPLT/OpenLID-v3",
23
+ filename="openlid-v3.bin"
24
+ )
25
+ model = fasttext.load_model(model_path)
26
+ print("Model loaded successfully!")
27
+
28
+ def predict_language(text, top_k=3, threshold=0.5):
29
+ """
30
+ Predict language of input text.
31
+
32
+ Args:
33
+ text: Input text to analyze
34
+ top_k: Number of top predictions to return (1-10)
35
+ threshold: Confidence threshold (0.0-1.0)
36
+ """
37
+ if not text or not text.strip():
38
+ return "Please enter some text to analyze."
39
+
40
+ # Preprocess
41
+ processed_text = preprocess(text)
42
+
43
+ if not processed_text.strip():
44
+ return "Text contains no valid characters for language identification."
45
+
46
+ # Get predictions
47
+ predictions = model.predict(
48
+ text=processed_text,
49
+ k=min(top_k, 10),
50
+ threshold=threshold,
51
+ on_unicode_error="strict",
52
+ )
53
+
54
+ labels, scores = predictions
55
+
56
+ # Format results
57
+ results = []
58
+ for label, score in zip(labels, scores):
59
+ # Remove __label__ prefix and format
60
+ lang_code = label.replace("__label__", "")
61
+ confidence = float(score) * 100
62
+ results.append(f"**{lang_code}**: {confidence:.2f}%")
63
+
64
+ return "\n\n".join(results)
65
+
66
+ # Create Gradio interface
67
+ with gr.Blocks(title="OpenLID-v3 Language Identification") as demo:
68
+ gr.Markdown("""
69
+ # OpenLID-v3 Language Identifier
70
+
71
+ Identify the language of any text with state-of-the-art accuracy.
72
+ Supports 194+ language varieties.
73
+
74
+ *Model: [HPLT/OpenLID-v3](https://huggingface.co/HPLT/OpenLID-v3)*
75
+ """)
76
+
77
+ with gr.Row():
78
+ with gr.Column():
79
+ input_text = gr.Textbox(
80
+ label="Input Text",
81
+ placeholder="Enter text to identify its language...",
82
+ lines=5,
83
+ max_lines=10
84
+ )
85
+ with gr.Row():
86
+ top_k = gr.Slider(
87
+ minimum=1,
88
+ maximum=10,
89
+ value=3,
90
+ step=1,
91
+ label="Top-K Predictions"
92
+ )
93
+ threshold = gr.Slider(
94
+ minimum=0.0,
95
+ maximum=1.0,
96
+ value=0.5,
97
+ step=0.05,
98
+ label="Confidence Threshold"
99
+ )
100
+ submit_btn = gr.Button("Identify Language", variant="primary")
101
+
102
+ with gr.Column():
103
+ output = gr.Markdown(label="Predictions")
104
+
105
+ # Examples with Kabyle and Occitan as defaults
106
+ gr.Examples(
107
+ examples=[
108
+ ["Asebter-a yura s wudem awurman d amagrad s tutlayt taqbaylit."],
109
+ ["Aqueste es un exemple de tèxte en occitan. L'occitan es una lenga romanica parlada en Occitània."],
110
+ ["Maskinsjefen er oppteken av å løfta fram dei maritime utdanningane."],
111
+ ["The quick brown fox jumps over the lazy dog."],
112
+ ["Le renard brun rapide saute par-dessus le chien paresseux."],
113
+ ["El rápido zorro marrón salta sobre el perro perezoso."],
114
+ ["Быстрая коричневая лисица прыгает через ленивую собаку."],
115
+ ["快速的棕色狐狸跳过了懒惰的狗。"],
116
+ ],
117
+ inputs=input_text,
118
+ label="Try these examples (Kabyle and Occitan featured)"
119
+ )
120
+
121
+ gr.Markdown("""
122
+ ### Tips for best results:
123
+ - Text is automatically preprocessed (lowercased, normalized)
124
+ - Longer texts generally give more accurate predictions
125
+ - The model supports 194+ language varieties
126
+ - Use higher thresholds to filter out uncertain predictions
127
+ """)
128
+
129
+ # Event handlers
130
+ submit_btn.click(
131
+ fn=predict_language,
132
+ inputs=[input_text, top_k, threshold],
133
+ outputs=output
134
+ )
135
+
136
+ input_text.submit(
137
+ fn=predict_language,
138
+ inputs=[input_text, top_k, threshold],
139
+ outputs=output
140
+ )
141
+
142
+ if __name__ == "__main__":
143
+ demo.launch()