CoolFace
Apppublic

LSABAGH/InjectaGuide

sourceHugging Faceupdated 5mo agoView on Hugging Face
0likes
app.py86 linesDownload Raw Back to root
1import os2import re3import streamlit as st4from langchain_community.vectorstores import FAISS5from langchain_community.embeddings import HuggingFaceEmbeddings6from langchain.chains import RetrievalQA7from langchain_community.document_loaders import PyPDFLoader8from langchain.text_splitter import CharacterTextSplitter9from langchain_groq import ChatGroq10from langchain.prompts import PromptTemplate11 12st.set_page_config(page_title="InjectaGuide", page_icon="๐Ÿ’‰", layout="centered")13 14def colorize_compatibility(text):15    text = re.sub(r'\b(compatible)\b', r'<span style="color: #10b981; font-weight: bold;">\1</span>', text, flags=re.IGNORECASE)16    text = re.sub(r'\b(incompatible)\b', r'<span style="color: #ef4444; font-weight: bold;">\1</span>', text, flags=re.IGNORECASE)17    return text18 19@st.cache_resource20def load_and_embed_pdf():21    loader = PyPDFLoader("injectable-drugs-guide.pdf")22    docs = loader.load()23    splitter = CharacterTextSplitter(chunk_size=500, chunk_overlap=50)24    split_docs = splitter.split_documents(docs)25    26    embed_model = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")27    faiss_index = FAISS.from_documents(split_docs, embed_model)28    return faiss_index29 30def build_qa_system(faiss_index):31    retriever = faiss_index.as_retriever(search_type="similarity", k=4)32    api_key = os.getenv("GROQ_API_KEY")33    34    if not api_key:35        st.error("โš ๏ธ GROQ_API_KEY Missing!")36        st.stop()37        38    llm = ChatGroq(api_key=api_key, model_name="llama-3.1-8b-instant")39    40    custom_prompt_template = """41    You are "InjectaGuide", an expert medical assistant.42    Provide precise, professional, and clear answers in English based only on the guide.43    If the answer is not in the context, politely state that the information is not available in the guide.44    45    Context: {context}46    Question: {question}47    48    Answer:49    """50    51    prompt = PromptTemplate(template=custom_prompt_template, input_variables=["context", "question"])52    53    return RetrievalQA.from_chain_type(54        llm=llm, 55        chain_type="stuff", 56        retriever=retriever,57        chain_type_kwargs={"prompt": prompt}58    )59 60def main():61    st.title("InjectaGuide ๐Ÿ’‰")62    st.caption("Your Intelligent Companion for Injectable Drug Safety")63 64    if "qa_chain" not in st.session_state:65        with st.spinner("Loading Medical Guide..."):66            try:67                faiss_index = load_and_embed_pdf()68                st.session_state.qa_chain = build_qa_system(faiss_index)69            except Exception as e:70                st.error(f"Setup Error: {e}")71                st.stop()72 73    st.divider()74    75    query = st.text_input("Enter Your Question about injection?")76    77    if query:78        with st.spinner("Generating answer..."):79            raw_result = st.session_state.qa_chain.run(query)80            formatted_result = colorize_compatibility(raw_result)81            82            st.markdown(f"**Answer:** {formatted_result}", unsafe_allow_html=True)83 84if __name__ == "__main__":85    main()86