DakshGoyal1506's picture
Update app.py
ed41c05 verified
Raw History Blame Contribute Delete
5.17 kB
import os
import json
import re
from functools import lru_cache
import gradio as gr
import nltk
from nltk.tokenize import word_tokenize
# Download required NLTK data at startup
try:
nltk.download('punkt_tab', quiet=True)
nltk.download('punkt', quiet=True) # fallback for older versions
except Exception:
pass
# ---- HMM import (expects your hmm.py in the repo root or in src/ path) ----
# If your hmm.py is at the repo root, this import will work as-is.
# Otherwise, adjust sys.path to point to its location.
from hmm import HMM # uses your class & viterbi implementation (:contentReference[oaicite:2]{index=2})
# ---- OpenAI (LLM) ----
from openai import OpenAI # single-sentence usage, model default set in UI
SYSTEM_TAGSONLY = (
"You are a precise POS tagger using the Universal POS tagset "
"(ADJ ADP ADV CONJ DET NOUN NUM PRON PRT VERB X .). "
"Return only the sequence of tags, space-separated, one tag per token. "
"No explanations, no JSON."
)
def make_user_prompt(tokens):
return f"Sentence: {' '.join(tokens)}"
def tokenize(s: str):
s = s.strip()
if not s:
return []
# Try NLTK word tokenizer first
try:
return word_tokenize(s)
except Exception:
# Fallback to simple regex tokenization
return re.split(r'\s+', s)
def align_tags(tokens, tags_out):
# Ensure exactly one tag per token (truncate/pad with 'X')
tags = tags_out[:len(tokens)]
if len(tags) < len(tokens):
tags += ["X"] * (len(tokens) - len(tags))
return tags
# -------- HMM loading (cached) --------
@lru_cache(maxsize=1)
def load_hmm_model(model_path: str = "models/hmm.pkl"):
if not os.path.exists(model_path):
raise FileNotFoundError(
f"HMM pickle not found at '{model_path}'. "
"Upload it or set the correct path in the UI."
)
model = HMM.load(model_path) # relies on your HMM.load (:contentReference[oaicite:3]{index=3})
return model
def infer_hmm(sentence: str, model_path: str):
tokens = tokenize(sentence)
if not tokens:
return [], []
hmm = load_hmm_model(model_path)
tags = hmm.viterbi(tokens) # your Viterbi (:contentReference[oaicite:4]{index=4})
return tokens, tags
# -------- LLM (OpenAI) single-sentence inference --------
def infer_openai(sentence: str, api_key: str, model_name: str = "gpt-4o-mini"):
tokens = tokenize(sentence)
if not tokens:
return [], []
if not api_key:
raise ValueError("Please provide your OpenAI API key.")
client = OpenAI(api_key=api_key)
messages = [
{"role": "system", "content": SYSTEM_TAGSONLY},
{"role": "user", "content": make_user_prompt(tokens)},
]
try:
resp = client.chat.completions.create(
model=model_name,
messages=messages,
temperature=0,
)
text = (resp.choices[0].message.content or "").strip()
except Exception as e:
# If the API call fails, return X for all tokens
return tokens, ["X"] * len(tokens)
# Expect tags separated by spaces/newlines, e.g. "DET NOUN VERB ."
# Normalize: split on whitespace and use as tag sequence.
raw_tags = re.split(r"\s+", text)
tags = align_tags(tokens, raw_tags)
return tokens, tags
# -------- Gradio UI logic --------
def run(engine, sentence, hmm_path, openai_key, openai_model):
"""
engine: 'HMM' or 'OpenAI'
sentence: user input
hmm_path: path to pickle file (default models/hmm.pkl)
openai_key: user's API key (not stored)
openai_model: openai model name (e.g., gpt-4o-mini)
"""
try:
if engine == "HMM":
tokens, tags = infer_hmm(sentence, hmm_path)
else:
tokens, tags = infer_openai(sentence, openai_key, openai_model)
rows = [{"token": t, "tag": g} for t, g in zip(tokens, tags)]
return json.dumps(rows, ensure_ascii=False, indent=2)
except Exception as e:
return json.dumps({"error": str(e)}, ensure_ascii=False, indent=2)
with gr.Blocks() as demo:
gr.Markdown(
"""
# POS Tagger (HMM or OpenAI)
- **HMM**: loads your trained pickle and runs Viterbi decoding.
- **OpenAI**: calls a model via your API key.
"""
)
with gr.Row():
engine = gr.Radio(choices=["HMM", "OpenAI"], value="HMM", label="Engine")
with gr.Row():
sentence = gr.Textbox(label="Sentence (space-separated tokens)", placeholder="The quick brown fox jumps over the lazy dog .", lines=2)
with gr.Row():
hmm_path = gr.Textbox(value="models/hmm.pkl", label="HMM model path (pickle)")
with gr.Row():
openai_key = gr.Textbox(label="OpenAI API Key (only used for this call)", type="password", placeholder="sk-...")
openai_model = gr.Textbox(value="gpt-4o-mini", label="OpenAI Model")
submit = gr.Button("Tag")
output = gr.Code(label="Output JSON", language="json")
submit.click(
fn=run,
inputs=[engine, sentence, hmm_path, openai_key, openai_model],
outputs=[output],
)
if __name__ == "__main__":
demo.launch()