File size: 8,076 Bytes
7cfc466
 
 
 
b82896b
7cfc466
 
b82896b
7cfc466
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b82896b
7cfc466
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b82896b
 
7cfc466
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b82896b
7cfc466
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
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
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 30 10:53:19 2025

@author: jacobwildt-persson
"""

import gradio as gr
import nltk
import datetime
import sqlite3
import random
import requests
import spacy
import pdfplumber
from nltk.tokenize import word_tokenize
from nltk.stem import WordNetLemmatizer
from transformers import pipeline, AutoModelForSeq2SeqLM, AutoTokenizer, GPT2LMHeadModel, GPT2Tokenizer

# Download NLTK resources
nltk.download("punkt")
nltk.download("wordnet")

# Load Spanish NLP pipeline and models
nlp = spacy.load("es_core_news_lg")
lemmatizer = WordNetLemmatizer()

# Load Spanish grammar model (BART)
tokenizer = AutoTokenizer.from_pretrained("SktCon/gec-spanish-BARTO-COWS-L2H")
model = AutoModelForSeq2SeqLM.from_pretrained("SktCon/gec-spanish-BARTO-COWS-L2H")

# GPT-2 models for sentence generation
gpt2_tokenizer_es = GPT2Tokenizer.from_pretrained("datificate/gpt2-small-spanish")
gpt2_model_es = GPT2LMHeadModel.from_pretrained("datificate/gpt2-small-spanish")
gpt2_tokenizer_en = GPT2Tokenizer.from_pretrained("gpt2")
gpt2_model_en = GPT2LMHeadModel.from_pretrained("gpt2")

DB_NAME = "vocab.db"

# --- Setup SQLite ---
conn = sqlite3.connect(DB_NAME)
conn.execute("""CREATE TABLE IF NOT EXISTS vocabulary (
    user_id TEXT,
    language TEXT,
    word TEXT,
    timestamp TEXT,
    UNIQUE(user_id, language, word)
)""")
conn.commit()
conn.close()

# --- Grammar Correction ---
def correct_grammar(text: str, language: str) -> str:
    if language == "es":
        corrected = []
        for sent in nlp(text).sents:
            s = sent.text.strip()
            if not s: continue
            inp = tokenizer(s, return_tensors="pt", truncation=True, padding=True)
            out = model.generate(
                **inp,
                max_new_tokens=inp.input_ids.shape[1],
                num_beams=5,
                early_stopping=True
            )
            corrected.append(tokenizer.decode(out[0], skip_special_tokens=True))
        return " ".join(corrected)
    else:
        resp = requests.post(
            "https://api.languagetool.org/v2/check",
            data={"text": text, "language": language}
        ).json()
        for m in reversed(resp.get("matches", [])):
            off, ln = m["offset"], m["length"]
            repls = m.get("replacements", [])
            val = repls[0]["value"] if repls else ""
            text = text[:off] + val + text[off+ln:]
        return text

# --- Save word ---
def save_word_to_db(user_id: str, language: str, word: str):
    ts = datetime.datetime.now().isoformat()
    conn = sqlite3.connect(DB_NAME)
    conn.execute(
        "INSERT OR IGNORE INTO vocabulary (user_id, language, word, timestamp) VALUES (?, ?, ?, ?)",
        (user_id, language, word, ts)
    )
    conn.commit()
    conn.close()

# --- Get vocab ---
def get_user_vocabulary(user_id: str, language: str) -> set:
    conn = sqlite3.connect(DB_NAME)
    rows = conn.execute(
        "SELECT word FROM vocabulary WHERE user_id=? AND language=?",
        (user_id, language)
    ).fetchall()
    conn.close()
    return {r[0] for r in rows}

# --- Analyze text ---
def analyze_text(text: str, user_id: str, language: str):
    toks = word_tokenize(text)
    lems = [lemmatizer.lemmatize(w.lower()) for w in toks if w.isalpha()]
    vocab = get_user_vocabulary(user_id, language)
    known = [w for w in lems if w in vocab]
    unknown = [w for w in lems if w not in vocab]
    return known, unknown

# --- Sentence Generation ---
def generate_coherent_sentence(text: str, user_id: str, language: str, num_unknown=2):
    kn, un = analyze_text(text, user_id, language)
    if not un:
        return "No unknown words to use."
    chosen = random.sample(un, min(num_unknown, len(un)))
    if language == "es":
        prompt = "Escribe una sola frase clara que incluya estas palabras: " + ", ".join(chosen) + "."
        tokenizer = gpt2_tokenizer_es
        model = gpt2_model_es
    else:
        prompt = "Write one clear sentence that includes the following words: " + ", ".join(chosen) + "."
        tokenizer = gpt2_tokenizer_en
        model = gpt2_model_en
    inp = tokenizer(prompt, return_tensors="pt", truncation=True)
    out = model.generate(
        **inp,
        max_new_tokens=50,
        do_sample=True,
        top_k=50,
        top_p=0.95
    )
    gen = tokenizer.decode(out[0], skip_special_tokens=True)
    body = gen[len(prompt):].strip() if gen.startswith(prompt) else gen.strip()
    return (body.split(".")[0].strip() + ".") if "." in body else body

# --- Import text from file ---
def import_file(path):
    if path.endswith(".pdf"):
        with pdfplumber.open(path) as pdf:
            return "\n".join([page.extract_text() for page in pdf.pages if page.extract_text()])
    with open(path, encoding="utf-8") as f:
        return f.read()

# --- Logging ---
def log_to_csv(filename, row_dict, header):
    with open(filename, "a", encoding="utf-8", newline="") as f:
        writer = csv.DictWriter(f, fieldnames=header)
        writer.writerow(row_dict)

# --- Gradio process callback ---
def process(user, language, txt, file, do_grammar, do_save):
    try:
        if txt and txt.strip():
            text = txt.strip()
        elif file:
            text = import_file(file.name)
        else:
            return "", "", "", "No input text.", ""
        out = correct_grammar(text, language) if do_grammar else text
        kn, un = analyze_text(out, user, language)
        status = ""
        if do_save and un:
            for w in un:
                save_word_to_db(user, language, w)
            status = f"Saved {len(un)} unknown words."
        log_to_csv(
            "grammarlog.csv",
            {"user": user, "language": language, "input": text, "output": out, "timestamp": datetime.datetime.now().isoformat()},
            ["user", "language", "input", "output", "timestamp"]
        )
        return out, ", ".join(kn), ", ".join(un), status, ""
    except Exception as e:
        import traceback
        return "", "", "", f"Error: {traceback.format_exc()}", ""

# --- Gradio sentence callback ---
def coherent_fn(user, language, txt, num):
    try:
        sentence = generate_coherent_sentence(txt or "", user, language, num)
        log_to_csv(
            "sentencelog.csv",
            {"user": user, "language": language, "input": txt, "output": sentence, "timestamp": datetime.datetime.now().isoformat()},
            ["user", "language", "input", "output", "timestamp"]
        )
        return sentence
    except Exception as e:
        return f"Error generating sentence: {e}"

# --- Gradio UI ---
with gr.Blocks() as demo:
    gr.Markdown("### ✨ Multilingual Grammar App with Vocabulary Tracking")

    with gr.Row():
        user_input = gr.Textbox(label="Username", placeholder="Your name")
        lang_input = gr.Dropdown(choices=["es", "en"], value="es", label="Language")

    with gr.Column():
        manual_input = gr.Textbox(lines=4, label="Paste or type your text here")
        file_input = gr.File(file_types=[".txt", ".pdf"], label="Upload text file")
        grammar_cb = gr.Checkbox(label="Enable grammar correction")
        save_cb = gr.Checkbox(label="Save unknown words to vocabulary")
        run_btn = gr.Button("Run analysis")
        num_slider = gr.Slider(minimum=1, maximum=5, step=1, value=2, label="Unknown words for sentence")
        gen_btn = gr.Button("Generate sentence")

    out_corr = gr.Textbox(label="Corrected text")
    out_known = gr.Textbox(label="Known words")
    out_unknown = gr.Textbox(label="Unknown words")
    out_status = gr.Textbox(label="Status")
    out_sent = gr.Textbox(label="Suggested sentence")

    run_btn.click(
        fn=process,
        inputs=[user_input, lang_input, manual_input, file_input, grammar_cb, save_cb],
        outputs=[out_corr, out_known, out_unknown, out_status, out_sent]
    )

    gen_btn.click(
        fn=coherent_fn,
        inputs=[user_input, lang_input, manual_input, num_slider],
        outputs=[out_sent]
    )

demo.launch()