Guilianno commited on
Commit
a018a6f
·
verified ·
1 Parent(s): f2e6f7f

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -125
app.py DELETED
@@ -1,125 +0,0 @@
1
- import streamlit as st
2
- from langchain_community.document_loaders import PDFPlumberLoader
3
- from langchain_experimental.text_splitter import SemanticChunker
4
- from langchain_huggingface import HuggingFaceEmbeddings
5
- from langchain_community.vectorstores import FAISS
6
- from transformers import T5ForConditionalGeneration, T5Tokenizer, pipeline
7
- from langchain.chains import RetrievalQA
8
- from langchain.prompts import PromptTemplate
9
- from langchain_huggingface import HuggingFacePipeline
10
-
11
- # Set up the Streamlit page configuration
12
- st.set_page_config(page_title="Fossong's Cognitive PDF Analyzer", page_icon="📄")
13
-
14
- # Title of the application
15
- st.title("Fossong's Cognitive PDF Analyzer")
16
- st.write("This application utilizes cognitive computing to analyze unstructured text in PDF documents. "
17
- "Upload your PDF file to interact intelligently and receive human-like responses to your queries.")
18
-
19
- # Load Hugging Face Model and Tokenizer for T5
20
- model_name = "t5-base" # Using T5 model for text generation and paraphrasing
21
- tokenizer = T5Tokenizer.from_pretrained(model_name)
22
- model = T5ForConditionalGeneration.from_pretrained(model_name)
23
-
24
- # Wrap the model with HuggingFacePipeline for compatibility with LangChain
25
- llm_pipeline = pipeline("text2text-generation", model=model, tokenizer=tokenizer)
26
- llm = HuggingFacePipeline(pipeline=llm_pipeline)
27
-
28
- # Streamlit file uploader
29
- uploaded_file = st.file_uploader("Upload a PDF file", type="pdf")
30
-
31
- if uploaded_file:
32
- # Save PDF temporarily
33
- with open("temp.pdf", "wb") as f:
34
- f.write(uploaded_file.getvalue())
35
-
36
- # Load PDF text
37
- loader = PDFPlumberLoader("temp.pdf")
38
- docs = loader.load()
39
-
40
- # Split text into semantic chunks using HuggingFace embeddings
41
- embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")
42
- text_splitter = SemanticChunker(embeddings)
43
- documents = text_splitter.split_documents(docs)
44
-
45
- # Generate embeddings and create a vector store
46
- vector_store = FAISS.from_documents(documents, embeddings)
47
-
48
- # Connect retriever
49
- retriever = vector_store.as_retriever(search_kwargs={"k": 3})
50
-
51
- # Define the prompt template for question answering with cognitive attributes
52
- qa_prompt = """
53
- 1. Use ONLY the context below.
54
- 2. If unsure, say "I don’t know".
55
- 3. Keep answers under 4 sentences.
56
-
57
- Context: {context}
58
-
59
- Question: {question}
60
-
61
- Answer:
62
- """
63
-
64
- qa_template = PromptTemplate.from_template(qa_prompt)
65
-
66
- # Create the RetrievalQA pipeline using T5 model wrapped in HuggingFacePipeline
67
- qa = RetrievalQA.from_chain_type(
68
- retriever=retriever,
69
- llm=llm,
70
- chain_type="stuff",
71
- chain_type_kwargs={"prompt": qa_template}
72
- )
73
-
74
- # Streamlit UI for user input with buttons for common queries
75
- user_input = st.text_input("Ask your PDF a question:")
76
-
77
- if user_input:
78
- with st.spinner("Thinking..."):
79
- try:
80
- context_data = retriever.get_relevant_documents(user_input) # Get relevant context from documents
81
- context_texts = [doc.page_content for doc in context_data] # Extract texts from documents
82
-
83
- # Combine context texts into one string for input to T5
84
- full_context = " ".join(context_texts)
85
- prompt_input = qa_template.format(context=full_context, question=user_input)
86
-
87
- response = llm(prompt_input) # Call the LLM directly with formatted input
88
-
89
- if response:
90
- st.write(response[0]['generated_text']) # Adjust based on how response is structured
91
- else:
92
- st.warning("No response generated. Please try another question.")
93
- except Exception as e:
94
- st.error(f"An error occurred: {e}")
95
-
96
- # Provide buttons for common queries (example questions)
97
- st.subheader("Common Queries")
98
- common_queries = [
99
- "What are the gaps for further research?",
100
- "Can you summarize the first section?",
101
- "What are the key findings?"
102
- ]
103
-
104
- for query in common_queries:
105
- if st.button(query):
106
- with st.spinner(f"Processing query: '{query}'..."):
107
- try:
108
- context_data = retriever.get_relevant_documents(query) # Get relevant context from documents
109
- context_texts = [doc.page_content for doc in context_data] # Extract texts from documents
110
-
111
- # Combine context texts into one string for input to T5
112
- full_context = " ".join(context_texts)
113
- prompt_input = qa_template.format(context=full_context, question=query)
114
-
115
- response = llm(prompt_input) # Call the LLM directly with formatted input
116
-
117
- if response:
118
- st.write(response[0]['generated_text']) # Adjust based on how response is structured
119
- else:
120
- st.warning("No response generated. Please try another question.")
121
- except Exception as e:
122
- st.error(f"An error occurred: {e}")
123
-
124
- # Visualize feedback (optional)
125
- # (Feedback mechanism can be added here if needed)