Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import re
|
| 3 |
+
import openai
|
| 4 |
+
import streamlit as st
|
| 5 |
+
import pandas as pd
|
| 6 |
+
import torch
|
| 7 |
+
import nltk
|
| 8 |
+
|
| 9 |
+
from langchain.chat_models import ChatOpenAI
|
| 10 |
+
from langchain.schema import SystemMessage, HumanMessage
|
| 11 |
+
from sentence_transformers import SentenceTransformer, util
|
| 12 |
+
|
| 13 |
+
# Try to load spaCy for advanced NLP processing
|
| 14 |
+
try:
|
| 15 |
+
import spacy
|
| 16 |
+
nlp = spacy.load("en_core_web_sm")
|
| 17 |
+
use_spacy = True
|
| 18 |
+
except Exception:
|
| 19 |
+
st.warning("SpaCy model not found, falling back to NLTK for tokenization.")
|
| 20 |
+
nltk.download("punkt")
|
| 21 |
+
use_spacy = False
|
| 22 |
+
|
| 23 |
+
# Load AI models
|
| 24 |
+
translator = ChatOpenAI(model="gpt-3.5-turbo")
|
| 25 |
+
model = SentenceTransformer('all-MiniLM-L6-v2')
|
| 26 |
+
|
| 27 |
+
@st.cache_data
|
| 28 |
+
def load_glossary_from_excel(glossary_file_bytes) -> dict:
|
| 29 |
+
"""Load glossary from an Excel file, applying lemmatization and sorting by length."""
|
| 30 |
+
df = pd.read_excel(glossary_file_bytes)
|
| 31 |
+
glossary = {}
|
| 32 |
+
|
| 33 |
+
for _, row in df.iterrows():
|
| 34 |
+
if pd.notnull(row['English']) and pd.notnull(row['CanadianFrench']):
|
| 35 |
+
english_term = row['English'].strip().lower()
|
| 36 |
+
french_term = row['CanadianFrench'].strip()
|
| 37 |
+
doc = nlp(english_term) if use_spacy else english_term.split()
|
| 38 |
+
lemmatized_term = " ".join([token.lemma_ for token in doc]) if use_spacy else english_term
|
| 39 |
+
glossary[lemmatized_term] = french_term
|
| 40 |
+
|
| 41 |
+
return dict(sorted(glossary.items(), key=lambda item: len(item[0]), reverse=True))
|
| 42 |
+
|
| 43 |
+
@st.cache_data
|
| 44 |
+
def compute_glossary_embeddings_cached(glossary_items: tuple):
|
| 45 |
+
"""Compute cached embeddings for glossary terms."""
|
| 46 |
+
glossary = dict(glossary_items)
|
| 47 |
+
glossary_terms = list(glossary.keys())
|
| 48 |
+
embeddings = model.encode(glossary_terms, convert_to_tensor=True)
|
| 49 |
+
return glossary_terms, embeddings
|
| 50 |
+
|
| 51 |
+
def translate_text(text: str) -> str:
|
| 52 |
+
"""Uses OpenAI's GPT to translate text to Canadian French."""
|
| 53 |
+
messages = [
|
| 54 |
+
SystemMessage(content="You are a professional translator. Translate the following text to Canadian French while preserving its meaning and context."),
|
| 55 |
+
HumanMessage(content=text)
|
| 56 |
+
]
|
| 57 |
+
response = translator(messages)
|
| 58 |
+
return response.content.strip()
|
| 59 |
+
|
| 60 |
+
def enforce_glossary(text: str, glossary: dict, threshold: float) -> str:
|
| 61 |
+
"""Applies glossary replacements based on semantic similarity."""
|
| 62 |
+
glossary_items = tuple(sorted(glossary.items()))
|
| 63 |
+
glossary_terms, glossary_embeddings = compute_glossary_embeddings_cached(glossary_items)
|
| 64 |
+
|
| 65 |
+
sentences = nltk.tokenize.sent_tokenize(text) if not use_spacy else [sent.text for sent in nlp(text).sents]
|
| 66 |
+
updated_sentences = []
|
| 67 |
+
|
| 68 |
+
for sentence in sentences:
|
| 69 |
+
if not sentence.strip():
|
| 70 |
+
continue
|
| 71 |
+
sentence_embedding = model.encode(sentence, convert_to_tensor=True)
|
| 72 |
+
cos_scores = util.pytorch_cos_sim(sentence_embedding, glossary_embeddings)
|
| 73 |
+
max_score, max_idx = torch.max(cos_scores, dim=1)
|
| 74 |
+
|
| 75 |
+
if max_score.item() >= threshold:
|
| 76 |
+
term = glossary_terms[max_idx]
|
| 77 |
+
replacement = glossary[term]
|
| 78 |
+
pattern = r'\b' + re.escape(term) + r'\b'
|
| 79 |
+
sentence = re.sub(pattern, replacement, sentence, flags=re.IGNORECASE)
|
| 80 |
+
|
| 81 |
+
updated_sentences.append(sentence.strip())
|
| 82 |
+
|
| 83 |
+
return " ".join(updated_sentences)
|
| 84 |
+
|
| 85 |
+
def validate_translation(original_text, final_text):
|
| 86 |
+
"""Uses GPT to check if the final translation retains the original meaning."""
|
| 87 |
+
messages = [
|
| 88 |
+
SystemMessage(content="You are an AI proofreader. Compare the original and final translation. Does the final translation retain the original meaning?"),
|
| 89 |
+
HumanMessage(content=f"Original Text: {original_text}\nFinal Translation: {final_text}\n")
|
| 90 |
+
]
|
| 91 |
+
response = translator(messages)
|
| 92 |
+
return response.content.strip()
|
| 93 |
+
|
| 94 |
+
# Streamlit UI
|
| 95 |
+
st.title("AI-Powered English to Canadian French Translator")
|
| 96 |
+
st.write("This app uses AI agents for translation, glossary enforcement, and meaning validation.")
|
| 97 |
+
|
| 98 |
+
input_text = st.text_area("Enter text to translate:")
|
| 99 |
+
glossary_file = st.file_uploader("Upload Glossary File (Excel)", type=["xlsx"])
|
| 100 |
+
threshold = st.slider("Semantic Matching Threshold", 0.5, 1.0, 0.8)
|
| 101 |
+
|
| 102 |
+
if st.button("Translate"):
|
| 103 |
+
if not input_text.strip():
|
| 104 |
+
st.error("Please enter text to translate.")
|
| 105 |
+
elif glossary_file is None:
|
| 106 |
+
st.error("Glossary file is required.")
|
| 107 |
+
else:
|
| 108 |
+
glossary = load_glossary_from_excel(glossary_file)
|
| 109 |
+
translated_text = translate_text(input_text)
|
| 110 |
+
glossary_enforced_text = enforce_glossary(translated_text, glossary, threshold)
|
| 111 |
+
validation_result = validate_translation(input_text, glossary_enforced_text)
|
| 112 |
+
|
| 113 |
+
st.subheader("Final Translated Text:")
|
| 114 |
+
st.write(glossary_enforced_text)
|
| 115 |
+
|
| 116 |
+
st.subheader("Validation Check:")
|
| 117 |
+
st.write(validation_result)
|