JacobWP commited on
Commit
5fcaaeb
·
verified ·
1 Parent(s): 31de348

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +291 -0
app.py ADDED
@@ -0,0 +1,291 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ Created on Mon May 19 16:49:22 2025
5
+
6
+ @author: jacobwildt-persson
7
+ """
8
+
9
+ #!/usr/bin/env python3
10
+ # -*- coding: utf-8 -*-
11
+ """
12
+ Language learning app with Gradio UI, on & multiple users:
13
+ - Import text from file (.txt/.csv/.pdf) or manual text input
14
+ - Grammar correction via transformers (Spanish) or LanguageTool API (English)
15
+ - Analyze text (known/unknown words) per user & language
16
+ - Save unknown words as known
17
+ - Generate coherent practice sentence (Spanish & English)
18
+ - Log grammar corrections and practice sentence suggestions to CSV
19
+ """
20
+ import os
21
+ import datetime
22
+ import sqlite3
23
+ import requests
24
+ import random
25
+ import pandas as pd
26
+ import pdfplumber
27
+ import spacy
28
+ import webbrowser
29
+ import csv
30
+
31
+ from nltk.tokenize import word_tokenize
32
+ from nltk.stem import WordNetLemmatizer
33
+ from transformers import AutoTokenizer, BartForConditionalGeneration, AutoModelForCausalLM
34
+ import gradio as gr
35
+ import gradio_client.utils as _gcu
36
+
37
+ # --- PATCH for Gradio utils schema bug ---
38
+ _orig_json = _gcu.json_schema_to_python_type
39
+ _orig_get = _gcu.get_type
40
+
41
+ def _patched_json_to_py(schema, defs=None):
42
+ if not isinstance(schema, dict):
43
+ return "any"
44
+ try:
45
+ return _orig_json(schema, defs)
46
+ except Exception:
47
+ return "any"
48
+
49
+ def _patched_get_type(schema):
50
+ if not isinstance(schema, dict):
51
+ return "any"
52
+ try:
53
+ return _orig_get(schema)
54
+ except Exception:
55
+ return "any"
56
+
57
+ _gcu.json_schema_to_python_type = _patched_json_to_py
58
+ _gcu.get_type = _patched_get_type
59
+
60
+ # --- SQLite Database initialization ---
61
+ DB_NAME = "vocabulary.db"
62
+ conn = sqlite3.connect(DB_NAME)
63
+ conn.execute("""
64
+ CREATE TABLE IF NOT EXISTS vocabulary (
65
+ user_id TEXT,
66
+ language TEXT,
67
+ word TEXT,
68
+ timestamp TEXT,
69
+ UNIQUE(user_id, language, word)
70
+ )
71
+ """)
72
+ conn.commit()
73
+ conn.close()
74
+
75
+ # --- Save word to database ---
76
+ def save_word_to_db(user_id: str, language: str, word: str):
77
+ ts = datetime.datetime.now().isoformat()
78
+ conn = sqlite3.connect(DB_NAME)
79
+ conn.execute(
80
+ "INSERT OR IGNORE INTO vocabulary (user_id, language, word, timestamp) VALUES (?, ?, ?, ?)",
81
+ (user_id, language, word, ts)
82
+ )
83
+ conn.commit()
84
+ conn.close()
85
+
86
+ # --- Retrieve known words for user/language ---
87
+ def get_user_vocabulary(user_id: str, language: str) -> set[str]:
88
+ conn = sqlite3.connect(DB_NAME)
89
+ rows = conn.execute(
90
+ "SELECT word FROM vocabulary WHERE user_id=? AND language=?",
91
+ (user_id, language)
92
+ ).fetchall()
93
+ conn.close()
94
+ return {r[0] for r in rows}
95
+
96
+ # --- Load NLP models ---
97
+ nlp = spacy.load("es_core_news_lg")
98
+ tokenizer = AutoTokenizer.from_pretrained("SkitCon/gec-spanish-BARTO-COWS-L2H")
99
+ model = BartForConditionalGeneration.from_pretrained("SkitCon/gec-spanish-BARTO-COWS-L2H")
100
+ gpt2_tokenizer_es = AutoTokenizer.from_pretrained("mrm8488/spanish-gpt2")
101
+ gpt2_model_es = AutoModelForCausalLM.from_pretrained("mrm8488/spanish-gpt2")
102
+ gpt2_tokenizer_en = AutoTokenizer.from_pretrained("gpt2")
103
+ gpt2_model_en = AutoModelForCausalLM.from_pretrained("gpt2")
104
+ lemmatizer = WordNetLemmatizer()
105
+
106
+ # ---Log to CSV (grammar corrections and sentence suggestions) ---
107
+ def log_to_csv(filename, row, fieldnames):
108
+ file_exists = os.path.isfile(filename)
109
+ with open(filename, "a", newline='', encoding="utf-8") as csvfile:
110
+ writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
111
+ if not file_exists:
112
+ writer.writeheader()
113
+ writer.writerow(row)
114
+
115
+ # --- File Import ---
116
+ def import_file(path: str) -> str:
117
+ ext = os.path.splitext(path)[1].lower()
118
+ if ext == ".pdf":
119
+ pages = []
120
+ with pdfplumber.open(path) as pdf:
121
+ for p in pdf.pages:
122
+ pages.append(p.extract_text() or "")
123
+ return "\n".join(pages)
124
+ if ext == ".csv":
125
+ df = pd.read_csv(path)
126
+ if "text" in df:
127
+ return "\n".join(df["text"].astype(str))
128
+ raise ValueError("CSV saknar kolumnen 'text'.")
129
+ if ext == ".txt":
130
+ return open(path, encoding="utf-8").read()
131
+ raise ValueError(f"Okänt filformat: {ext}")
132
+
133
+ # --- Grammar Correction ---
134
+
135
+ def correct_grammar(text: str, language: str) -> str:
136
+ if language == "es":
137
+ corrected = []
138
+ for sent in nlp(text).sents:
139
+ s = sent.text.strip()
140
+ if not s: continue
141
+ inp = tokenizer(s, return_tensors="pt", truncation=True, padding=True)
142
+ out = model.generate(
143
+ **inp,
144
+ max_new_tokens=inp.input_ids.shape[1],
145
+ num_beams=5,
146
+ early_stopping=True
147
+ )
148
+ corrected.append(tokenizer.decode(out[0], skip_special_tokens=True))
149
+ return " ".join(corrected)
150
+ # English: LanguageTool API
151
+ resp = requests.post(
152
+ "https://api.languagetool.org/v2/check",
153
+ data={"text": text, "language": language}
154
+ ).json()
155
+ for m in reversed(resp.get("matches", [])):
156
+ off, ln = m["offset"], m["length"]
157
+ repls = m.get("replacements", [])
158
+ val = repls[0]["value"] if repls else ""
159
+ text = text[:off] + val + text[off+ln:]
160
+ return text
161
+
162
+ # --- Analyze known and unknown words ---
163
+
164
+ def analyze_text(text: str, user_id: str, language: str):
165
+ toks = word_tokenize(text)
166
+ lems = [lemmatizer.lemmatize(w.lower()) for w in toks if w.isalpha()]
167
+ vocab = get_user_vocabulary(user_id, language)
168
+ known = [w for w in lems if w in vocab]
169
+ unknown = [w for w in lems if w not in vocab]
170
+ return known, unknown
171
+ # --- Generate sentence using GPT2 based on unknown words ---
172
+ def generate_coherent_sentence(text: str, user_id: str, language: str, num_unknown=2) -> str:
173
+ kn, un = analyze_text(text, user_id, language)
174
+ if not un:
175
+ return "Inga okända ord att generera mening med."
176
+ chosen = random.sample(un, min(num_unknown, len(un)))
177
+ if language == "es":
178
+ prompt = "Escribe una sola frase clara que incluya estas palabras: " + ", ".join(chosen) + "."
179
+ tokenizer = gpt2_tokenizer_es
180
+ model = gpt2_model_es
181
+ else:
182
+ prompt = "Write one clear sentence that includes the following words: " + ", ".join(chosen) + "."
183
+ tokenizer = gpt2_tokenizer_en
184
+ model = gpt2_model_en
185
+ inp = tokenizer(prompt, return_tensors="pt", truncation=True)
186
+ outs = model.generate(
187
+ **inp,
188
+ max_new_tokens=50,
189
+ do_sample=True,
190
+ top_k=50,
191
+ top_p=0.95
192
+ )
193
+ gen = tokenizer.decode(outs[0], skip_special_tokens=True)
194
+ body = gen[len(prompt):].strip() if gen.startswith(prompt) else gen.strip()
195
+ sentence = (body.split(".")[0].strip() + ".") if "." in body else body
196
+ if not any(c.isalpha() for c in sentence):
197
+ return "Misslyckades att generera meningsfull övningsmening."
198
+ return sentence
199
+
200
+
201
+ # --- Gradio process callback ---
202
+ def process(user, language, txt, file, do_grammar, do_save):
203
+ try:
204
+ if txt and txt.strip():
205
+ text = txt.strip()
206
+ elif file:
207
+ text = import_file(file.name)
208
+ else:
209
+ return "", "", "", "Ingen text angiven.", ""
210
+ out = correct_grammar(text, language) if do_grammar else text
211
+ kn, un = analyze_text(out, user, language)
212
+ status = ""
213
+ if do_save and un:
214
+ for w in un:
215
+ save_word_to_db(user, language, w)
216
+ status = f"Sparade {len(un)} ord."
217
+ # Logga grammatikrättning till CSV
218
+ log_to_csv(
219
+ "grammarlog.csv",
220
+ {
221
+ "user": user, "language": language, "input": text,
222
+ "output": out, "timestamp": datetime.datetime.now().isoformat()
223
+ },
224
+ ["user", "language", "input", "output", "timestamp"]
225
+ )
226
+ return out, ", ".join(kn), ", ".join(un), status, ""
227
+ except Exception as e:
228
+ import traceback
229
+ tb = traceback.format_exc()
230
+ return "", "", "", f"FEL i process:\n{tb}", ""
231
+
232
+ # --- Sentence generation callback ---
233
+ def coherent_fn(user, language, txt, num):
234
+ try:
235
+ suggestion = generate_coherent_sentence(txt or "", user, language, num)
236
+ # Logga övningsförslag till CSV
237
+ log_to_csv(
238
+ "sentencelog.csv",
239
+ {
240
+ "user": user, "language": language, "input": txt,
241
+ "output": suggestion, "timestamp": datetime.datetime.now().isoformat()
242
+ },
243
+ ["user", "language", "input", "output", "timestamp"]
244
+ )
245
+ return suggestion
246
+ except Exception as e:
247
+ return f"Fel vid generering: {e}"
248
+
249
+ # --- Gradio UI ---
250
+ demo = gr.Blocks()
251
+ with demo:
252
+ gr.Markdown("### 🌟 Språkinlärningsapp med användare & flerspråkighet")
253
+ with gr.Row():
254
+ user_input = gr.Textbox(label="Användarnamn", placeholder="Ditt namn här")
255
+ lang_dd = gr.Dropdown(choices=["es", "en"], value="es", label="Språk")
256
+ with gr.Column():
257
+ manual_input = gr.Textbox(lines=4, label="Skriv/klistra in text")
258
+ file_input = gr.File(file_types=[".txt",".csv",".pdf"], label="Importera fil")
259
+ grammar_cb = gr.Checkbox(label="Grammatik­rättning")
260
+ autosave_cb = gr.Checkbox(label="Spara okända ord")
261
+ run_btn = gr.Button("Kör analys & korrigering")
262
+ num_slider = gr.Slider(minimum=1, maximum=5, step=1, value=2, label="Antal okända ord för övning")
263
+ coherent_btn = gr.Button("Koherent övningsmening")
264
+
265
+ corr_out = gr.Textbox(label="Korrigerad text", lines=4)
266
+ known_out = gr.Textbox(label="Kända ord")
267
+ unknown_out = gr.Textbox(label="Okända ord")
268
+ status_out = gr.Textbox(label="Status")
269
+ coherent_out = gr.Textbox(label="Koherent övningsmening")
270
+
271
+ # --- Knapparnas click‐kopplingar ---
272
+ run_btn.click(
273
+ fn=process,
274
+ inputs=[user_input, lang_dd, manual_input, file_input, grammar_cb, autosave_cb],
275
+ outputs=[corr_out, known_out, unknown_out, status_out, coherent_out]
276
+ )
277
+ coherent_btn.click(
278
+ fn=coherent_fn,
279
+ inputs=[user_input, lang_dd, manual_input, num_slider],
280
+ outputs=[coherent_out]
281
+ )
282
+
283
+ # --- Start app ---
284
+ if __name__ == "__main__":
285
+ url = demo.launch(share=True, inbrowser=True, prevent_thread_lock=True)
286
+ print("Appen körs på:", url)
287
+
288
+ if __name__ == "__main__":
289
+ print("STARTAR APPEN") # <- se om detta syns i runtime-loggen!
290
+ demo.launch()
291
+