evolvingtransformer/LLM-based-chat-application
0
1import streamlit as st2from deep_translator import GoogleTranslator3import whisper4import tempfile5import os6from firebase_admin import credentials, firestore7from firebase import get_db8db = get_db()9# 1. Page Configuration10st.set_page_config(page_title="Doctor–Patient Translator", layout="wide")11 12st.markdown("""13<style>14 .bubble { padding: 15px; border-radius: 15px; margin: 10px 0; width: fit-content; max-width: 80%; }15 .bubble-doc { background-color: #e6f2ff; border-left: 5px solid #007bff; }16 .bubble-pat { background-color: #f2f2f2; border-left: 5px solid #28a745; margin-left: auto; }17</style>18""", unsafe_allow_html=True)19 20# 2. Initialization & Models21if "chat" not in st.session_state:22 st.session_state.chat = []23if "last_processed_audio" not in st.session_state:24 st.session_state.last_processed_audio = None25 26@st.cache_resource27def load_whisper():28 return whisper.load_model("base")29 30model = load_whisper()31 32 33# 3. Helper Functions34def transcribe_audio(file_path):35 result = model.transcribe(file_path)36 return result["text"]37 38def translate_text(text, src, tgt):39 return GoogleTranslator(source=src, target=tgt).translate(text)40 41def add_message(role, original, translated):42 st.session_state.chat.append({43 "role": role,44 "original": original,45 "translated": translated46 })47import uuid48from datetime import datetime49 50def create_conversation():51 convo_id = str(uuid.uuid4())52 db.collection("conversations").document(convo_id).set({53 "created_at": datetime.utcnow(),54 "summary": ""55 })56 return convo_id57 58def save_message(convo_id, data):59 db.collection("conversations") \60 .document(convo_id) \61 .collection("messages") \62 .add({63 **data,64 "timestamp": firestore.SERVER_TIMESTAMP65 })66 67 68if "convo_id" not in st.session_state:69 st.session_state.convo_id = create_conversation()70 71# 4. UI Sidebar & Layout72st.title("🩺 Doctor–Patient Translator")73 74with st.sidebar:75 st.header("Settings")76 doctor_lang = st.selectbox("Doctor's Language", ["en", "fr", "de", "es", "hi", "zh-CN"], index=0)77 patient_lang = st.selectbox("Patient's Language", ["en", "fr", "de", "es", "hi", "zh-CN"], index=4)78 if st.button("Clear Conversation"):79 st.session_state.chat = []80 st.rerun()81 82# 5. Display Chat History83chat_container = st.container()84with chat_container:85 for msg in st.session_state.chat:86 style = "bubble-doc" if msg["role"] == "Doctor" else "bubble-pat"87 st.markdown(f"""88 <div class="bubble {style}">89 <b>{msg['role']}:</b><br>90 <small style="color: grey;">{msg['original']}</small><br>91 <strong>{msg['translated']}</strong>92 </div>93 """, unsafe_allow_html=True)94 95# 6. Input Section96st.divider()97current_role = st.radio("Who is speaking?", ["Doctor", "Patient"], horizontal=True)98 99# Logic: Determine Source and Target based on who is speaking100active_src = doctor_lang if current_role == "Doctor" else patient_lang101active_tgt = patient_lang if current_role == "Doctor" else doctor_lang102 103user_text = st.chat_input("Type your message here...")104audio = st.audio_input("Or record your voice")105 106# 7. Processing Text Input107if user_text:108 translated = translate_text(user_text, active_src, active_tgt)109 add_message(current_role, user_text, translated)110 save_message(111 st.session_state.convo_id,112 {113 "role": current_role,114 "original_text": user_text,115 "translated_text": translated,116 "input_language": active_src,117 "output_language": active_tgt118 }119)120 121 st.rerun()122 123# 8. Processing Audio Input (With Loop Protection)124if audio:125 audio_hash = hash(audio.getbuffer().tobytes())126 127 if st.session_state.last_processed_audio != audio_hash:128 with st.spinner("Processing speech..."):129 with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as f:130 f.write(audio.getbuffer())131 tmp_path = f.name132 133 # Transcription134 raw_text = transcribe_audio(tmp_path)135 136 # Translation137 translated_text = translate_text(raw_text, active_src, active_tgt)138 139 # Save and Update State140 add_message(current_role, raw_text, translated_text)141 save_message(142 st.session_state.convo_id,143 {144 "role": current_role,145 "original_text": raw_text,146 "translated_text": translated_text,147 "input_language": active_src,148 "output_language": active_tgt149 }150 )151 152 st.session_state.last_processed_audio = audio_hash153 154 # Cleanup155 os.remove(tmp_path)156 st.rerun()157 158other_page_url = "https://google.com"159 160 # Custom HTML Button Link161st.markdown(f"""162 <a href="{other_page_url}" target="_blank" style="text-decoration: none;">163 <div style="164 background-color: #007bff;165 color: white;166 padding: 10px 20px;167 text-align: center;168 border-radius: 5px;169 cursor: pointer;170 font-weight: bold;171 border: none;">172 Go to Summarizer page ➔173 </div>174 </a>175""", unsafe_allow_html=True)