CoolFace
Apppublic

dhanuhs/Orca

sourceHugging Faceupdated 10mo agoView on Hugging Face
0likes
models.py102 linesDownload Raw Back to root
1import os
2import streamlit as st
3import speech_recognition as sr
4from langchain.document_loaders import PyPDFLoader
5from langchain.vectorstores import FAISS
6from langchain.embeddings import HuggingFaceEmbeddings
7from langchain.chains import RetrievalQA
8from google.generativeai import configure, GenerativeModel
9
10# ✅ SETUP: Replace with your Gemini API Key
11GEMINI_API_KEY = "AIzaSyDyOQa8cnZcO9227h8W26tgMxRHv6Ma7xM"
12configure(api_key=GEMINI_API_KEY)
13
14# ✅ Load PDFs Privately from Folder
15PDF_FOLDER = "DataSets/"
16if not os.path.exists(PDF_FOLDER):
17    os.makedirs(PDF_FOLDER)
18
19# ✅ Load PDFs & Create Vector Store
20def load_and_index_pdfs():
21    pdf_files = [os.path.join(PDF_FOLDER, f) for f in os.listdir(PDF_FOLDER) if f.endswith(".pdf")]
22    if not pdf_files:
23        return None
24    
25    documents = []
26    for pdf in pdf_files:
27        loader = PyPDFLoader(pdf)
28        documents.extend(loader.load())
29
30    embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")
31    vectorstore = FAISS.from_documents(documents, embeddings)
32    return vectorstore
33
34# ✅ Conversational AI with Gemini (Only Answers if PDF Has Relevant Data)
35def chat_with_gemini(prompt, context, history):
36    if not context.strip():
37        return "I'm still learning. I don't have enough information on that topic yet."
38
39    model = GenerativeModel("gemini-2.0-pro-exp-02-05")  # ✅ UPDATED MODEL
40    conversation = "\n".join(history) + "\nUser: " + prompt
41    response = model.generate_content(conversation)
42    return response.text
43
44# ✅ Streamlit UI Setup
45st.set_page_config(page_title="DGCT Guide for AI&DS", page_icon="📘")
46st.image("Assests/logo.png", width=150)  # Ensure 'logo.png' exists
47st.title("📘 DGCT Guide for AI&DS")
48st.subheader("Conversational AI Chatbot")
49
50# ✅ Load Vector Database
51vector_db = load_and_index_pdfs()
52retriever = vector_db.as_retriever() if vector_db else None
53
54# ✅ Initialize Chat History State
55if "chat_history" not in st.session_state:
56    st.session_state.chat_history = []
57
58# ✅ Chat History Toggle (Open/Close)
59with st.sidebar:
60    show_history = st.checkbox("📜 Show Chat History", value=False)
61
62if show_history:
63    st.sidebar.subheader("Previous Conversations")
64    for i in range(0, len(st.session_state.chat_history), 2):
65        st.sidebar.markdown(f"🧑‍💬 **You:** {st.session_state.chat_history[i]}")
66        if i + 1 < len(st.session_state.chat_history):
67            st.sidebar.markdown(f"🤖 **AI:** {st.session_state.chat_history[i + 1]}")
68    st.sidebar.markdown("---")
69    if st.sidebar.button("❌ Clear Chat History"):
70        st.session_state.chat_history = []
71        st.sidebar.success("Chat history cleared!")
72
73# ✅ Display Chat Messages
74for i in range(0, len(st.session_state.chat_history), 2):
75    with st.chat_message("user"):
76        st.markdown(st.session_state.chat_history[i])  # User Query
77    if i + 1 < len(st.session_state.chat_history):
78        with st.chat_message("assistant"):
79            st.markdown(st.session_state.chat_history[i + 1])  # AI Response
80
81# ✅ Chat Input
82query = st.chat_input("Ask a question...")
83if query:
84    with st.chat_message("user"):
85        st.markdown(query)
86    
87    with st.spinner("Thinking... 💡"):
88        context = ""
89        if retriever:
90            docs = retriever.get_relevant_documents(query)
91            context = "\n".join([doc.page_content for doc in docs])
92
93        final_prompt = f"{context}\n\nUser: {query}"
94        response = chat_with_gemini(final_prompt, context, st.session_state.chat_history)
95
96        # ✅ Store Chat History
97        st.session_state.chat_history.append(f"{query}")  # User message
98        st.session_state.chat_history.append(f"{response}")  # AI response
99
100        with st.chat_message("assistant"):
101            st.markdown(response)
102