Spaces:
Sleeping
Sleeping
import streamlit as st | |
from transformers import ( | |
pipeline, | |
AutoModelForSequenceClassification, | |
AutoTokenizer | |
) | |
from langdetect import detect | |
import torch | |
import re | |
# ===== MODEL LOADING ===== | |
# Translation models configuration | |
TRANSLATION_MODELS = { | |
# Translations to English | |
'fr-en': 'Helsinki-NLP/opus-mt-fr-en', # French to English | |
'es-en': 'Helsinki-NLP/opus-mt-es-en', # Spanish to English | |
'de-en': 'Helsinki-NLP/opus-mt-de-en', # German to English | |
'zh-en': 'Helsinki-NLP/opus-mt-zh-en', # Chinese to English | |
'ja-en': 'Helsinki-NLP/opus-mt-ja-en', # Japanese to English | |
# Translations from English | |
'en-fr': 'Helsinki-NLP/opus-mt-en-fr', # English to French | |
'en-es': 'Helsinki-NLP/opus-mt-en-es', # English to Spanish | |
'en-de': 'Helsinki-NLP/opus-mt-en-de', # English to German | |
'en-zh': 'Helsinki-NLP/opus-mt-en-zh', # English to Chinese | |
'en-ja': 'Helsinki-NLP/opus-mt-en-ja' # English to Japanese | |
} | |
# Sentiment analysis model | |
SENTIMENT_MODEL_NAME = "smtsead/fine_tuned_bertweet_hotel" | |
SENTIMENT_TOKENIZER = 'finiteautomata/bertweet-base-sentiment-analysis' | |
# Aspect classification model | |
ASPECT_MODEL = "MoritzLaurer/deberta-v3-base-zeroshot-v1.1-all-33" | |
# Initialize models (with caching to avoid reloading) | |
def load_translation_model(src_lang, target_lang='en'): | |
"""Load translation model for specific language pair""" | |
model_key = f"{src_lang}-{target_lang}" | |
if model_key not in TRANSLATION_MODELS: | |
raise ValueError(f"Unsupported translation: {src_lang}→{target_lang}") | |
return pipeline("translation", model=TRANSLATION_MODELS[model_key]) | |
def load_sentiment_model(): | |
"""Load sentiment analysis model""" | |
model = AutoModelForSequenceClassification.from_pretrained(SENTIMENT_MODEL_NAME) | |
tokenizer = AutoTokenizer.from_pretrained(SENTIMENT_TOKENIZER) | |
return model, tokenizer | |
def load_aspect_classifier(): | |
"""Load aspect classification model""" | |
return pipeline("zero-shot-classification", model=ASPECT_MODEL) | |
# ===== PIPELINE FUNCTIONS ===== | |
def translate_text(text, target_lang='en'): | |
"""Translate text to target language""" | |
try: | |
# Detect source language | |
src_lang = detect(text) | |
# Handle special case (English to other languages) | |
if src_lang == 'en' and target_lang != 'en': | |
translator = load_translation_model('en', target_lang) | |
else: | |
translator = load_translation_model(src_lang, target_lang) | |
# Perform translation | |
result = translator(text)[0]['translation_text'] | |
return { | |
'original': text, | |
'translation': result, | |
'source_lang': src_lang, | |
'target_lang': target_lang | |
} | |
except Exception as e: | |
return {'error': str(e)} | |
def analyze_sentiment(text, model, tokenizer): | |
"""Analyze sentiment of text (positive/negative)""" | |
inputs = tokenizer(text, padding=True, truncation=True, max_length=512, return_tensors='pt') | |
with torch.no_grad(): | |
outputs = model(**inputs) | |
probs = torch.nn.functional.softmax(outputs.logits, dim=-1) | |
predicted_label = torch.argmax(probs).item() | |
confidence = torch.max(probs).item() | |
return { | |
'label': predicted_label, | |
'confidence': confidence, | |
'sentiment': 'POSITIVE' if predicted_label else 'NEGATIVE' | |
} | |
def detect_aspects(text, aspect_classifier): | |
"""Detect aspects mentioned in text""" | |
# Aspect mapping with keywords | |
aspect_map = { | |
"location": ["location", "near", "close", "access", "transport", "distance", "area"], | |
"view": ["view", "scenery", "vista", "panorama", "outlook"], | |
"parking": ["parking", "valet", "garage", "car park", "vehicle"], | |
"room comfort": ["comfortable", "bed", "pillows", "mattress", "linens", "cozy"], | |
"room cleanliness": ["clean", "dirty", "spotless", "stains", "hygiene", "sanitation"], | |
"room amenities": ["amenities", "minibar", "coffee", "tea", "fridge", "facilities"], | |
"bathroom": ["bathroom", "shower", "toilet", "sink", "towel", "faucet"], | |
"staff service": ["staff", "friendly", "helpful", "rude", "welcoming", "employee"], | |
"reception": ["reception", "check-in", "check-out", "front desk", "welcome"], | |
"housekeeping": ["housekeeping", "maid", "cleaning", "towels", "service"], | |
"concierge": ["concierge", "recommendation", "advice", "tips", "guidance"], | |
"room service": ["room service", "food delivery", "order", "meal"], | |
"dining": ["breakfast", "dinner", "restaurant", "meal", "food", "buffet"], | |
"bar": ["bar", "drinks", "cocktail", "wine", "lounge"], | |
"pool": ["pool", "swimming", "jacuzzi", "sun lounger", "deck"], | |
"spa": ["spa", "massage", "treatment", "relax", "wellness"], | |
"fitness": ["gym", "fitness", "exercise", "workout", "training"], | |
"Wi-Fi": ["wifi", "internet", "connection", "online", "network"], | |
"AC": ["air conditioning", "AC", "temperature", "heating", "cooling"], | |
"elevator": ["elevator", "lift", "escalator", "vertical transport"], | |
"pricing": ["price", "expensive", "cheap", "value", "rate", "cost"], | |
"extra charges": ["charge", "fee", "bill", "surcharge", "additional"] | |
} | |
# First stage: keyword filtering | |
relevant_aspects = [] | |
text_lower = text.lower() | |
for aspect, keywords in aspect_map.items(): | |
if any(re.search(rf'\b{kw}\b', text_lower) for kw in keywords): | |
relevant_aspects.append(aspect) | |
# Second stage: zero-shot classification | |
if relevant_aspects: | |
result = aspect_classifier( | |
text, | |
candidate_labels=relevant_aspects, | |
multi_label=True, | |
hypothesis_template="This review mentions something about the {} of the hotel." | |
) | |
# Return aspects with score > 0.65 | |
return [(aspect, round(score, 2)) for aspect, score in | |
zip(result['labels'], result['scores']) if score > 0.65] | |
return [] | |
def generate_response(label, aspects, text): | |
"""Generate professional response based on sentiment and aspects""" | |
if label == 1: | |
# Positive response template | |
response = "Dear Valued Guest,\n\nThank you for sharing your positive experience with us!\n" | |
# Positive aspect responses | |
aspect_responses = { | |
"location": "We're delighted you enjoyed our prime location and convenient access to local attractions.", | |
"view": "It's wonderful to hear you appreciated the beautiful views from our property.", | |
"room comfort": "Our team is thrilled you found your room comfortable and inviting.", | |
"room cleanliness": "Your commendation of our cleanliness standards means a lot to our housekeeping staff.", | |
"staff service": "Your kind words about our team, especially {staff_name}, have been shared with them.", | |
"reception": "We're pleased our front desk team made your arrival/departure seamless.", | |
"spa": "Our spa practitioners will be delighted you enjoyed their treatments.", | |
"pool": "We're glad you had a refreshing time at our pool facilities.", | |
"dining": "Thank you for appreciating our culinary offerings - we've shared your feedback with our chefs.", | |
"concierge": "We're happy our concierge could enhance your stay with local insights.", | |
"fitness": "It's great to hear you made use of our well-equipped fitness center.", | |
"room service": "We're pleased our in-room dining met your expectations for quality and timeliness." | |
} | |
# Add specific aspect responses | |
added_aspects = set() | |
for aspect, _ in aspects: | |
if aspect in aspect_responses: | |
if aspect == "staff service" and "lourdes" in text.lower(): | |
response += "\n" + aspect_responses[aspect].format(staff_name="Lourdes") | |
else: | |
response += "\n" + aspect_responses[aspect] | |
added_aspects.add(aspect) | |
if len(added_aspects) >= 3: | |
break | |
response += "\n\nWe can't wait to welcome you back for another exceptional stay!\n\nWarm regards," | |
else: | |
# Negative response template | |
response = "Dear Guest,\n\nThank you for your feedback - we're truly sorry your experience didn't meet our usual standards.\n" | |
# Improvement actions for negative aspects | |
improvement_actions = { | |
"AC": "completed a full inspection and maintenance of all AC units", | |
"housekeeping": "retrained our housekeeping team and adjusted schedules", | |
"bathroom": "conducted deep cleaning and maintenance on all bathrooms", | |
"parking": "implemented new key management protocols with our valet service", | |
"dining": "reviewed our menu pricing and quality with the culinary team", | |
"reception": "provided additional customer service training to our front desk", | |
"elevator": "performed full servicing and testing of all elevators", | |
"room amenities": "begun upgrading in-room amenities based on guest feedback", | |
"noise": "initiated soundproofing improvements in affected areas", | |
"pricing": "started a comprehensive review of our pricing structure" | |
} | |
# Add specific improvement actions | |
added_aspects = set() | |
for aspect, _ in aspects: | |
if aspect in improvement_actions and aspect not in added_aspects: | |
response += f"\nRegarding the {aspect}, we've {improvement_actions[aspect]}." | |
added_aspects.add(aspect) | |
if len(added_aspects) >= 2: | |
break | |
response += "\n\nWe sincerely appreciate your patience and hope you'll give us another opportunity to provide the quality experience you deserve.\n\nSincerely," | |
return response + "\nThe Management Team\n" | |
# ===== STREAMLIT APP ===== | |
def main(): | |
st.set_page_config(page_title="Review Response Generator", page_icon="📝") | |
st.title("📝 Hotel Review Response Generator") | |
st.markdown(""" | |
This tool helps hotel managers generate professional responses to guest reviews in multiple languages. | |
**How it works:** | |
1. Enter a guest review in any language | |
2. The system will analyze sentiment and key aspects | |
3. A professional response will be generated | |
4. The response will be translated back to the original language | |
""") | |
# Initialize session state | |
if 'review_text' not in st.session_state: | |
st.session_state.review_text = "" | |
if 'translated_text' not in st.session_state: | |
st.session_state.translated_text = "" | |
if 'sentiment_result' not in st.session_state: | |
st.session_state.sentiment_result = None | |
if 'aspects' not in st.session_state: | |
st.session_state.aspects = [] | |
if 'response' not in st.session_state: | |
st.session_state.response = "" | |
if 'translated_response' not in st.session_state: | |
st.session_state.translated_response = "" | |
# Input review | |
review_text = st.text_area("Enter the guest review:", height=150) | |
if st.button("Generate Response"): | |
if not review_text.strip(): | |
st.error("Please enter a review first.") | |
return | |
with st.spinner("Processing review..."): | |
# Step 1: Translate to English if needed | |
translation_result = translate_text(review_text) | |
if 'error' in translation_result: | |
st.error(f"Translation error: {translation_result['error']}") | |
return | |
st.session_state.review_text = review_text | |
st.session_state.translated_text = translation_result['translation'] | |
source_lang = translation_result['source_lang'] | |
# Step 2: Sentiment analysis | |
sentiment_model, sentiment_tokenizer = load_sentiment_model() | |
sentiment_result = analyze_sentiment( | |
st.session_state.translated_text, | |
sentiment_model, | |
sentiment_tokenizer | |
) | |
st.session_state.sentiment_result = sentiment_result | |
# Step 3: Aspect detection | |
aspect_classifier = load_aspect_classifier() | |
st.session_state.aspects = detect_aspects( | |
st.session_state.translated_text, | |
aspect_classifier | |
) | |
# Step 4: Generate response | |
st.session_state.response = generate_response( | |
sentiment_result['label'], | |
st.session_state.aspects, | |
st.session_state.translated_text | |
) | |
# Step 5: Translate response back to original language if needed | |
if source_lang != 'en': | |
translation_back = translate_text( | |
st.session_state.response, | |
target_lang=source_lang | |
) | |
if 'error' not in translation_back: | |
st.session_state.translated_response = translation_back['translation'] | |
else: | |
st.warning(f"Couldn't translate response back: {translation_back['error']}") | |
st.session_state.translated_response = st.session_state.response | |
else: | |
st.session_state.translated_response = st.session_state.response | |
# Display results | |
if st.session_state.review_text: | |
st.divider() | |
st.subheader("Analysis Results") | |
# Original review | |
with st.expander("Original Review", expanded=True): | |
st.write(st.session_state.review_text) | |
# Translation (if applicable) | |
if hasattr(st.session_state, 'translated_text') and st.session_state.translated_text: | |
with st.expander("Translated to English"): | |
st.write(st.session_state.translated_text) | |
# Sentiment analysis | |
if st.session_state.sentiment_result: | |
sentiment = st.session_state.sentiment_result | |
sentiment_color = "green" if sentiment['label'] == 1 else "red" | |
st.markdown(f"**Sentiment:** :{sentiment_color}[{sentiment['sentiment']}] (confidence: {sentiment['confidence']:.2f})") | |
# Detected aspects | |
if st.session_state.aspects: | |
st.markdown("**Key Aspects Detected:**") | |
for aspect, confidence in st.session_state.aspects: | |
st.write(f"- {aspect.title()} (confidence: {confidence})") | |
# Generated response | |
if st.session_state.response: | |
st.divider() | |
st.subheader("Generated Response") | |
col1, col2 = st.columns(2) | |
with col1: | |
st.markdown("**English Version**") | |
st.text_area("English response", st.session_state.response, height=300, label_visibility="collapsed") | |
with col2: | |
st.markdown("**Translated Back**") | |
st.text_area("Translated response", st.session_state.translated_response, height=300, label_visibility="collapsed") | |
if __name__ == "__main__": | |
main() |