Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import gradio as gr
|
| 3 |
+
|
| 4 |
+
def load_ngrams_jsonl(file_name):
|
| 5 |
+
dictionary = {}
|
| 6 |
+
with open(file_name, encoding='utf-8') as f:
|
| 7 |
+
for line in f:
|
| 8 |
+
data = json.loads(line)
|
| 9 |
+
k = tuple(data["ngram"]) if len(data["ngram"]) > 1 else data["ngram"][0]
|
| 10 |
+
dictionary[k] = data["count"]
|
| 11 |
+
return dictionary
|
| 12 |
+
|
| 13 |
+
frequency_trigrams = load_ngrams_jsonl('trigrams.jsonl')
|
| 14 |
+
|
| 15 |
+
def predict_next_word(text):
|
| 16 |
+
words = text.lower().split()
|
| 17 |
+
if len(words) < 2:
|
| 18 |
+
return "Escribe al menos dos palabras en sueco (p. ej. 'det var')."
|
| 19 |
+
w1, w2 = words[-2], words[-1]
|
| 20 |
+
candidates = [(freq, w3) for (a, b, w3), freq in frequency_trigrams.items()
|
| 21 |
+
if a == w1 and b == w2]
|
| 22 |
+
sorted_candidates = sorted(candidates, key=lambda x: (-x[0], x[1]))
|
| 23 |
+
top5 = [w for freq, w in sorted_candidates[:5]]
|
| 24 |
+
return ", ".join(top5) if top5 else "No hay predicciones para ese contexto."
|
| 25 |
+
|
| 26 |
+
demo = gr.Interface(
|
| 27 |
+
fn=predict_next_word,
|
| 28 |
+
inputs=gr.Textbox(label="Escribe al menos dos palabras en sueco", placeholder="det var"),
|
| 29 |
+
outputs=gr.Textbox(label="Top-5 predicciones de la siguiente palabra"),
|
| 30 |
+
title="Selma Lagerlöf — Predicción de palabra (modelo de trigramas)",
|
| 31 |
+
description="Basado en n-gramas contados sobre el corpus de Selma Lagerlöf (Assignment 2, Language Technology, Lund University)."
|
| 32 |
+
)
|
| 33 |
+
|
| 34 |
+
demo.launch()
|