Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -5,15 +5,11 @@ from typing import Iterator, Union, Any
|
|
| 5 |
import fasttext
|
| 6 |
import gradio as gr
|
| 7 |
from dotenv import load_dotenv
|
| 8 |
-
from httpx import Client, Timeout
|
| 9 |
from huggingface_hub import hf_hub_download
|
| 10 |
from huggingface_hub.utils import logging
|
| 11 |
from toolz import concat, groupby, valmap
|
| 12 |
-
from fastapi import FastAPI
|
| 13 |
-
from httpx import AsyncClient
|
| 14 |
from pathlib import Path
|
| 15 |
|
| 16 |
-
app = FastAPI()
|
| 17 |
logger = logging.get_logger(__name__)
|
| 18 |
load_dotenv()
|
| 19 |
|
|
@@ -23,7 +19,6 @@ def load_model(repo_id: str) -> fasttext.FastText._FastText:
|
|
| 23 |
model_path = hf_hub_download(repo_id, filename="model.bin")
|
| 24 |
return fasttext.load_model(model_path)
|
| 25 |
|
| 26 |
-
|
| 27 |
def yield_clean_rows(rows: Union[list[str], str], min_length: int = 3) -> Iterator[str]:
|
| 28 |
for row in rows:
|
| 29 |
if isinstance(row, str):
|
|
@@ -42,10 +37,9 @@ def yield_clean_rows(rows: Union[list[str], str], min_length: int = 3) -> Iterat
|
|
| 42 |
except TypeError:
|
| 43 |
continue
|
| 44 |
|
| 45 |
-
|
| 46 |
FASTTEXT_PREFIX_LENGTH = 9 # fasttext labels are formatted like "__label__eng_Latn"
|
| 47 |
|
| 48 |
-
#
|
| 49 |
Path("code/models").mkdir(parents=True, exist_ok=True)
|
| 50 |
model = fasttext.load_model(
|
| 51 |
hf_hub_download(
|
|
@@ -57,7 +51,6 @@ model = fasttext.load_model(
|
|
| 57 |
)
|
| 58 |
)
|
| 59 |
|
| 60 |
-
|
| 61 |
def model_predict(inputs: str, k=1) -> list[dict[str, float]]:
|
| 62 |
predictions = model.predict(inputs, k=k)
|
| 63 |
return [
|
|
@@ -65,103 +58,163 @@ def model_predict(inputs: str, k=1) -> list[dict[str, float]]:
|
|
| 65 |
for label, prob in zip(predictions[0], predictions[1])
|
| 66 |
]
|
| 67 |
|
| 68 |
-
|
| 69 |
def get_label(x):
|
| 70 |
return x.get("label")
|
| 71 |
|
| 72 |
-
|
| 73 |
def get_mean_score(preds):
|
| 74 |
return mean([pred.get("score") for pred in preds])
|
| 75 |
|
| 76 |
-
|
| 77 |
def filter_by_frequency(counts_dict: dict, threshold_percent: float = 0.2):
|
| 78 |
"""Filter a dict to include items whose value is above `threshold_percent`"""
|
| 79 |
total = sum(counts_dict.values())
|
| 80 |
threshold = total * threshold_percent
|
| 81 |
return {k for k, v in counts_dict.items() if v >= threshold}
|
| 82 |
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 127 |
)
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
|
|
|
| 5 |
import fasttext
|
| 6 |
import gradio as gr
|
| 7 |
from dotenv import load_dotenv
|
|
|
|
| 8 |
from huggingface_hub import hf_hub_download
|
| 9 |
from huggingface_hub.utils import logging
|
| 10 |
from toolz import concat, groupby, valmap
|
|
|
|
|
|
|
| 11 |
from pathlib import Path
|
| 12 |
|
|
|
|
| 13 |
logger = logging.get_logger(__name__)
|
| 14 |
load_dotenv()
|
| 15 |
|
|
|
|
| 19 |
model_path = hf_hub_download(repo_id, filename="model.bin")
|
| 20 |
return fasttext.load_model(model_path)
|
| 21 |
|
|
|
|
| 22 |
def yield_clean_rows(rows: Union[list[str], str], min_length: int = 3) -> Iterator[str]:
|
| 23 |
for row in rows:
|
| 24 |
if isinstance(row, str):
|
|
|
|
| 37 |
except TypeError:
|
| 38 |
continue
|
| 39 |
|
|
|
|
| 40 |
FASTTEXT_PREFIX_LENGTH = 9 # fasttext labels are formatted like "__label__eng_Latn"
|
| 41 |
|
| 42 |
+
# Load the model
|
| 43 |
Path("code/models").mkdir(parents=True, exist_ok=True)
|
| 44 |
model = fasttext.load_model(
|
| 45 |
hf_hub_download(
|
|
|
|
| 51 |
)
|
| 52 |
)
|
| 53 |
|
|
|
|
| 54 |
def model_predict(inputs: str, k=1) -> list[dict[str, float]]:
|
| 55 |
predictions = model.predict(inputs, k=k)
|
| 56 |
return [
|
|
|
|
| 58 |
for label, prob in zip(predictions[0], predictions[1])
|
| 59 |
]
|
| 60 |
|
|
|
|
| 61 |
def get_label(x):
|
| 62 |
return x.get("label")
|
| 63 |
|
|
|
|
| 64 |
def get_mean_score(preds):
|
| 65 |
return mean([pred.get("score") for pred in preds])
|
| 66 |
|
|
|
|
| 67 |
def filter_by_frequency(counts_dict: dict, threshold_percent: float = 0.2):
|
| 68 |
"""Filter a dict to include items whose value is above `threshold_percent`"""
|
| 69 |
total = sum(counts_dict.values())
|
| 70 |
threshold = total * threshold_percent
|
| 71 |
return {k for k, v in counts_dict.items() if v >= threshold}
|
| 72 |
|
| 73 |
+
def simple_predict(text, num_predictions=3):
|
| 74 |
+
"""Simple language detection function for Gradio interface"""
|
| 75 |
+
if not text or not text.strip():
|
| 76 |
+
return "Please enter some text for language detection."
|
| 77 |
+
|
| 78 |
+
try:
|
| 79 |
+
# Clean the text
|
| 80 |
+
cleaned_lines = list(yield_clean_rows([text]))
|
| 81 |
+
if not cleaned_lines:
|
| 82 |
+
return "No valid text found after cleaning."
|
| 83 |
+
|
| 84 |
+
# Get predictions for each line
|
| 85 |
+
all_predictions = []
|
| 86 |
+
for line in cleaned_lines:
|
| 87 |
+
predictions = model_predict(line, k=num_predictions)
|
| 88 |
+
all_predictions.extend(predictions)
|
| 89 |
+
|
| 90 |
+
if not all_predictions:
|
| 91 |
+
return "No predictions could be made."
|
| 92 |
+
|
| 93 |
+
# Group predictions by language
|
| 94 |
+
predictions_by_lang = groupby(get_label, all_predictions)
|
| 95 |
+
language_counts = valmap(len, predictions_by_lang)
|
| 96 |
+
|
| 97 |
+
# Calculate average scores for each language
|
| 98 |
+
language_scores = valmap(get_mean_score, predictions_by_lang)
|
| 99 |
+
|
| 100 |
+
# Format results
|
| 101 |
+
results = {
|
| 102 |
+
"detected_languages": dict(language_scores),
|
| 103 |
+
"language_counts": dict(language_counts),
|
| 104 |
+
"total_predictions": len(all_predictions),
|
| 105 |
+
"text_lines_analyzed": len(cleaned_lines)
|
| 106 |
+
}
|
| 107 |
+
|
| 108 |
+
return results
|
| 109 |
+
|
| 110 |
+
except Exception as e:
|
| 111 |
+
return f"Error during prediction: {str(e)}"
|
| 112 |
+
|
| 113 |
+
def batch_predict(text, threshold_percent=0.2):
|
| 114 |
+
"""More advanced prediction with filtering"""
|
| 115 |
+
if not text or not text.strip():
|
| 116 |
+
return "Please enter some text for language detection."
|
| 117 |
+
|
| 118 |
+
try:
|
| 119 |
+
# Clean the text
|
| 120 |
+
cleaned_lines = list(yield_clean_rows([text]))
|
| 121 |
+
if not cleaned_lines:
|
| 122 |
+
return "No valid text found after cleaning."
|
| 123 |
+
|
| 124 |
+
# Get predictions
|
| 125 |
+
predictions = [model_predict(line) for line in cleaned_lines]
|
| 126 |
+
predictions = [pred for pred in predictions if pred is not None]
|
| 127 |
+
predictions = list(concat(predictions))
|
| 128 |
+
|
| 129 |
+
if not predictions:
|
| 130 |
+
return "No predictions could be made."
|
| 131 |
+
|
| 132 |
+
# Group and filter
|
| 133 |
+
predictions_by_lang = groupby(get_label, predictions)
|
| 134 |
+
language_counts = valmap(len, predictions_by_lang)
|
| 135 |
+
keys_to_keep = filter_by_frequency(language_counts, threshold_percent=threshold_percent)
|
| 136 |
+
filtered_dict = {k: v for k, v in predictions_by_lang.items() if k in keys_to_keep}
|
| 137 |
+
|
| 138 |
+
results = {
|
| 139 |
+
"predictions": dict(valmap(get_mean_score, filtered_dict)),
|
| 140 |
+
"all_language_counts": dict(language_counts),
|
| 141 |
+
"filtered_languages": list(keys_to_keep),
|
| 142 |
+
"threshold_used": threshold_percent
|
| 143 |
+
}
|
| 144 |
+
|
| 145 |
+
return results
|
| 146 |
+
|
| 147 |
+
except Exception as e:
|
| 148 |
+
return f"Error during prediction: {str(e)}"
|
| 149 |
+
|
| 150 |
+
def build_demo_interface():
|
| 151 |
+
app_title = "Language Detection Tool"
|
| 152 |
+
with gr.Blocks(title=app_title) as demo:
|
| 153 |
+
gr.Markdown(f"# {app_title}")
|
| 154 |
+
gr.Markdown("Enter text below to detect the language(s) it contains.")
|
| 155 |
+
|
| 156 |
+
with gr.Tab("Simple Detection"):
|
| 157 |
+
with gr.Row():
|
| 158 |
+
with gr.Column():
|
| 159 |
+
text_input1 = gr.Textbox(
|
| 160 |
+
label="Enter text for language detection",
|
| 161 |
+
placeholder="Type or paste your text here...",
|
| 162 |
+
lines=5
|
| 163 |
+
)
|
| 164 |
+
num_predictions = gr.Slider(
|
| 165 |
+
minimum=1,
|
| 166 |
+
maximum=10,
|
| 167 |
+
value=3,
|
| 168 |
+
step=1,
|
| 169 |
+
label="Number of top predictions per line"
|
| 170 |
+
)
|
| 171 |
+
predict_btn1 = gr.Button("Detect Language")
|
| 172 |
+
|
| 173 |
+
with gr.Column():
|
| 174 |
+
output1 = gr.JSON(label="Detection Results")
|
| 175 |
+
|
| 176 |
+
predict_btn1.click(
|
| 177 |
+
simple_predict,
|
| 178 |
+
inputs=[text_input1, num_predictions],
|
| 179 |
+
outputs=output1
|
| 180 |
)
|
| 181 |
+
|
| 182 |
+
with gr.Tab("Advanced Detection"):
|
| 183 |
+
with gr.Row():
|
| 184 |
+
with gr.Column():
|
| 185 |
+
text_input2 = gr.Textbox(
|
| 186 |
+
label="Enter text for advanced language detection",
|
| 187 |
+
placeholder="Type or paste your text here...",
|
| 188 |
+
lines=5
|
| 189 |
+
)
|
| 190 |
+
threshold = gr.Slider(
|
| 191 |
+
minimum=0.1,
|
| 192 |
+
maximum=1.0,
|
| 193 |
+
value=0.2,
|
| 194 |
+
step=0.1,
|
| 195 |
+
label="Threshold percentage for filtering"
|
| 196 |
+
)
|
| 197 |
+
predict_btn2 = gr.Button("Advanced Detect")
|
| 198 |
+
|
| 199 |
+
with gr.Column():
|
| 200 |
+
output2 = gr.JSON(label="Advanced Detection Results")
|
| 201 |
+
|
| 202 |
+
predict_btn2.click(
|
| 203 |
+
batch_predict,
|
| 204 |
+
inputs=[text_input2, threshold],
|
| 205 |
+
outputs=output2
|
| 206 |
+
)
|
| 207 |
+
|
| 208 |
+
gr.Markdown("### About")
|
| 209 |
+
gr.Markdown("This tool uses Facebook's FastText language identification model to detect languages in text.")
|
| 210 |
+
|
| 211 |
+
return demo
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
if __name__ == "__main__":
|
| 215 |
+
demo = build_demo_interface()
|
| 216 |
+
demo.launch(
|
| 217 |
+
server_name="0.0.0.0",
|
| 218 |
+
server_port=7860,
|
| 219 |
+
share=False
|
| 220 |
+
)
|