CoolFace
Apppublic

bipinsaha/chatPDF

sourceHugging Facemitupdated 3y agoView on Hugging Face
0likes
app.py161 linesDownload Raw Back to root
1import streamlit as st2import os3import google.generativeai as genai4from text_ext import extract_text_from_pdf5import base646from dotenv import load_dotenv7from chat_mode import chat_response8from PIL import Image9 10load_dotenv()11 12genai.configure(api_key=os.getenv("GOOGLE_API_KEY"))13 14text_model=genai.GenerativeModel("gemini-pro")15vision_model=genai.GenerativeModel("gemini-pro-vision") 16chat = text_model.start_chat(history=[])17 18def get_gemini_response(input, pdf_content):19    response = text_model.generate_content([input, pdf_content])20    return response.text21 22def get_gemini_vision_response(input, image, pdf_content):23    response = vision_model.generate_content([input, image, pdf_content])24    return response.text25 26##initialize our streamlit app27st.set_page_config(page_title="Gemini ChatPDF Application", layout="wide")28#st.subheader("Chat with PDF")29# Add some space at the top to center the subheader30#st.markdown("<h1 style='text-align: center;'> </h1>", unsafe_allow_html=True)31st.markdown("<h2 style='text-align: center;'>chatPDF</h2>", unsafe_allow_html=True)32 33 34 35with st.sidebar:36        st.title("Upload PDF:")37        research_field = st.text_input("Research Field: ",key="research_field", placeholder="Enter research fields with commas")38        uploaded_file = st.file_uploader("", type=["pdf"])39        option = st.selectbox('Select Mode', ('', 'Chat', 'Graph and Table', 'Code', 'Custom Prompting'))40        #print(option)41        #submit = st.button("Submit", type="primary")42        #submit1 = st.button("Resume Assesmet")43        #submit2 = st.button("Possible Improvements")44        #submit3 = st.button("Percentage Match")45 46if uploaded_file is None:47    st.stop()48else:   49    file_path = os.path.join("Uploaded", "paper.pdf")50    with open(file_path, "wb") as file:51        file.write(uploaded_file.getvalue())52    53    54 55 56q_input=st.chat_input(key="input", placeholder="Ask your question")57#ask=st.button("Ask", type="primary")58 59def input_image_setup(uploaded_file):60    if uploaded_file is not None:61        bytes_data = uploaded_file.getvalue()62        63        image_parts = [64            {65                "mime_type": uploaded_file.type, 66                "data": bytes_data67            }68        ]69        return image_parts70   71    else:72        raise FileNotFoundError("No file uploaded")73 74 75pdf_file_path = "Uploaded/paper.pdf"76 77if uploaded_file:78    pdf_text = extract_text_from_pdf(pdf_file_path)79    #print(pdf_text)80else:81    pdf_text = ""82 83 84initial_prompt = f"""85Imagine you are a seasoned researcher specializing in the field of {research_field}. 86You are presented with a research paper within your domain. Evaluate its working methodology 87and discuss its research impact through concise bullet points. Conclude by summarizing the 88research paper and propose three questions for the user based on the paper's context. Finnaly 89remeber the research paper context for the next questions.90 91Output will be as,92Research Paper Title \n93Research Summary \n94Methodology \n95Research Impact \n96Suggested Questions"""97 98 99if option=='':100    with st.spinner("Processing..."):101        response = get_gemini_response(initial_prompt, pdf_text)102        st.write(response)103    104 105 106question_prompt = f"""Envision yourself as a seasoned researcher with a wealth of knowledge in the {research_field} domain. 107        Upon being presented with a research paper within your specialized area, meticulously evaluate its methodology. 108        Provide detailed and contextual insights in response to my specific question or questions. Ensure your answers are 109        not only accurate but also comprehensive. In instances where the information is unavailable, please explicitly state, 110        'Sorry, I do not know the answer.' \n \n \n"""111 112intermediate_code_prompt = f"""Envision yourself as a seasoned researcher with a welth of knowledge in the {research_field} domain.113        Upon being presented with a research paper within your specialized area, meticulosly evaluate its methodology and detail working114        process. Provide detailed and contextual step by step informations for developing the complete project from scratch including models, 115        architectures, conversion process and related items mentioned in the document text"""116 117code_prompt = f"""As a proficient Python code generator specialized in {research_field}, 118        your expertise encompasses various aspects of research, including model construction,  developing task-specific 119        functions, exploring novel methods, and generating code for existing works. Additionally, you are exceled in 120        creating insightful visualizations, utilizing statistical data, such as bar graphs, pie charts, histograms, and121        scatter plots, to convey meaningful insights within the context of research data. Now, based on my question or122        specific inquiry regarding the given research paper data, please generate the relevant Python code to address my query. Finally123        explain the code in by each and every steps. \n \n \n"""124 125if q_input is None:126    st.stop()127else:128    if q_input and option=="Chat":129        with st.spinner("Processing..."):130            mod_prompt = question_prompt + pdf_text131            response = get_gemini_response(mod_prompt, q_input)132            chat_response(q_input, response)133            #st.write(response)134    135    elif q_input and option=="Code":136 137        with st.spinner("Processing..."):138            mod_prompt = intermediate_code_prompt + pdf_text139            response = get_gemini_response(mod_prompt, q_input)140            st.write(response)141            #mod_prompt = code_prompt + response142            #response = get_gemini_response(mod_prompt, q_input)143            #st.write(response)144 145    elif q_input and option=="Graph and Table":146        with st.spinner("Processing..."):147            #mod_prompt = code_prompt + pdf_text148            #response = get_gemini_response(mod_prompt, q_input)149            st.write("Graph and Table mode is not developed yet.")150 151    elif q_input and option == "Custom Prompting":152        mod_prompt = q_input153        response = get_gemini_response(mod_prompt, pdf_text)154        st.write(response)155    156    else:157        st.write(f"{option} Mode")158 159 160 161