SpaceOfApp / app.py
JacobWP's picture
Create app.py
7cfc466 verified
Raw History Blame Contribute Delete
8.08 kB
#!/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()