html templates has been added
Browse filesFiles changed (2)
- app.py+104-15
- htmlTemplates.pyAdded+44
1234567891011121314151617181920from transformers import AutoModelForCausalLM, AutoTokenizerfrom huggingface_hub import loginimport streamlit as stst.set_page_config(page_title="Code Generation",page_icon="🤖",layout="wide",initial_sidebar_state="expanded",)login(token='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', add_to_git_credential=True)st.title("Code Generation")st.write('MODEL: TinyPixel/red1xe/Llama-2-7B-codeGPT')model_name='lmsys/vicuna-7b-v1.1'tokenizer = AutoTokenizer.from_pretrained(model_name)model= AutoModelForCausalLM.from_pretrained(model_name)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109import osimport timeimport streamlit as stfrom dotenv import load_dotenvfrom htmlTemplates import css, bot_template, user_templatefrom langchain.embeddings import HuggingFaceEmbeddingsfrom langchain.vectorstores import Chromafrom langchain.memory import ConversationBufferMemoryfrom langchain.prompts import PromptTemplatefrom langchain.chains import RetrievalQAfrom langchain.llms import HuggingFaceHubfrom langchain import PromptTemplatefrom pdfminer.high_level import extract_textfrom langchain.text_splitter import RecursiveCharacterTextSplitterfrom transformers import AutoTokenizer, AutoModelForSeq2SeqLM# Updated Prompt Templatetemplate = """You are an expert on TeamCenter. Use the following pieces of context to answer the question at the end.If you don't know the answer, it's okay to say that you don't know. Please don't try to make up an answer.Use two sentences minimum and keep the answer as concise as possible (maximum 200 characters each).Always use proper grammar and punctuation. End of the answer always say "End of answer" (without quotes).Context:{context}Question: {question}Helpful Answer (Two sentences minimum, maximum 200 characters each):"""tokenizer = AutoTokenizer.from_pretrained("red1xe/falcon-7b-codeGPT-3K")model = AutoModelForSeq2SeqLM.from_pretrained("red1xe/falcon-7b-codeGPT-3K")## QA_CHAIN_PROMPT = PromptTemplate(template=template, input_variables=["question", "context"])load_dotenv()persist_directory = os.environ.get('PERSIST_DIRECTORY')embeddings_model_name = os.environ.get("EMBEDDINGS_MODEL_NAME")model_path = os.environ.get('MODEL_PATH')def get_vector_store(target_source_chunks):embeddings = HuggingFaceEmbeddings(model_name=embeddings_model_name)db = Chroma(persist_directory=persist_directory, embedding_function=embeddings)retriver = db.as_retriever(search_kwargs={"k": target_source_chunks})return retriverdef get_conversation_chain(retriever):memory = ConversationBufferMemory(memory_key='chat_history', return_messages=True,)chain = RetrievalQA.from_llm(llm=model,memory=memory,retriever=retriever,)return chaindef handle_userinput(user_question):if st.session_state.conversation is None:st.warning("Please load the Vectorstore first!")returnelse:with st.spinner('Thinking...', ):start_time = time.time()response = st.session_state.conversation({'query': user_question})end_time = time.time()st.session_state.chat_history = response['chat_history']for i, message in enumerate(st.session_state.chat_history):if i % 2 == 0:st.write(user_template.replace("{{MSG}}", message.content), unsafe_allow_html=True)else:st.write(bot_template.replace("{{MSG}}", message.content), unsafe_allow_html=True)st.write('Elapsed time: {:.2f} seconds'.format(end_time - start_time))st.balloons()def main():st.set_page_config(page_title='Chat with PDF', page_icon=':rocket:', layout='wide', )with st.sidebar.title(':gear: Parameters'):model_n_ctx = st.sidebar.slider('Model N_CTX', min_value=128, max_value=2048, value=1024, step=2)model_n_batch = st.sidebar.slider('Model N_BATCH', min_value=1, max_value=model_n_ctx, value=512, step=2)target_source_chunks = st.sidebar.slider('Target Source Chunks', min_value=1, max_value=10, value=4, step=1)st.write(css, unsafe_allow_html=True)if "conversation" not in st.session_state:st.session_state.conversation = Noneif "chat_history" not in st.session_state:st.session_state.chat_history = Nonest.header('Chat with PDF :robot_face:')st.subheader('Upload your PDF file and start chatting with it!')user_question = st.text_input('Enter your message here:')if st.button('Start Chain'):with st.spinner('Working in progress ...'):vector_store = get_vector_store(target_source_chunks)st.session_state.conversation = get_conversation_chain(retriever=vector_store,)if user_question:handle_userinput(user_question)if __name__ == '__main__':main()
1234567891011121314151617181920212223242526272829303132333435363738394041424344css = '''<style>.chat-message { padding: 1.5rem; border-radius: 0.5rem; margin-bottom: 1rem; display: flex}.chat-message.user { background-color: #2b313e}.chat-message.bot { background-color: #475063}.chat-message .avatar { width: 20%;}.chat-message .avatar img { max-width: 78px; max-height: 78px; border-radius: 70%; object-fit: cover;}.chat-message .message { width: 80%; padding: 0 1.5rem; color: #fff;}'''
bot_template = '''<div class="chat-message bot"> <div class="avatar"> <img src="https://media.licdn.com/dms/image/C4E0BAQHSBVuHaXe6DA/company-logo_200_200/0/1519893058477?e=1697673600&v=beta&t=ISf-4u1cOnN0KNQSNLt5MY5RvxYL50PIFIyvuUrIf9g" style="max-height: 78px; max-width: 78px; border-radius: 50%; object-fit: cover;"> </div> <div class="message">{{MSG}}</div></div>'''
user_template = '''<div class="chat-message user"> <div class="avatar"> <img src="https://cdn-icons-png.flaticon.com/512/1077/1077012.png"> </div> <div class="message">{{MSG}}</div></div>'''app.py+104-15
htmlTemplates.pyAdded+44