Murtuza Saifee commited on
Commit
d3bfde1
·
1 Parent(s): 9dfbe9c

Add code with the opensource model as well

Browse files
Files changed (4) hide show
  1. .gitignore +171 -0
  2. README.md +19 -14
  3. app-open-source-models.py +127 -0
  4. app.py +0 -1
.gitignore ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # PyInstaller
30
+ # Usually these files are written by a python script from a template
31
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
32
+ *.manifest
33
+ *.spec
34
+
35
+ # Installer logs
36
+ pip-log.txt
37
+ pip-delete-this-directory.txt
38
+
39
+ # Unit test / coverage reports
40
+ htmlcov/
41
+ .tox/
42
+ .nox/
43
+ .coverage
44
+ .coverage.*
45
+ .cache
46
+ nosetests.xml
47
+ coverage.xml
48
+ *.cover
49
+ *.py,cover
50
+ .hypothesis/
51
+ .pytest_cache/
52
+ cover/
53
+
54
+ # Translations
55
+ *.mo
56
+ *.pot
57
+
58
+ # Django stuff:
59
+ *.log
60
+ local_settings.py
61
+ db.sqlite3
62
+ db.sqlite3-journal
63
+
64
+ # Flask stuff:
65
+ instance/
66
+ .webassets-cache
67
+
68
+ # Scrapy stuff:
69
+ .scrapy
70
+
71
+ # Sphinx documentation
72
+ docs/_build/
73
+
74
+ # PyBuilder
75
+ .pybuilder/
76
+ target/
77
+
78
+ # Jupyter Notebook
79
+ .ipynb_checkpoints
80
+
81
+ # IPython
82
+ profile_default/
83
+ ipython_config.py
84
+
85
+ # pyenv
86
+ # For a library or package, you might want to ignore these files since the code is
87
+ # intended to run in multiple environments; otherwise, check them in:
88
+ # .python-version
89
+
90
+ # pipenv
91
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
93
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
94
+ # install all needed dependencies.
95
+ #Pipfile.lock
96
+
97
+ # UV
98
+ # Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
99
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
100
+ # commonly ignored for libraries.
101
+ #uv.lock
102
+
103
+ # poetry
104
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
105
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
106
+ # commonly ignored for libraries.
107
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
108
+ #poetry.lock
109
+
110
+ # pdm
111
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
112
+ #pdm.lock
113
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
114
+ # in version control.
115
+ # https://pdm.fming.dev/latest/usage/project/#working-with-version-control
116
+ .pdm.toml
117
+ .pdm-python
118
+ .pdm-build/
119
+
120
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
121
+ __pypackages__/
122
+
123
+ # Celery stuff
124
+ celerybeat-schedule
125
+ celerybeat.pid
126
+
127
+ # SageMath parsed files
128
+ *.sage.py
129
+
130
+ # Environments
131
+ .env
132
+ .venv
133
+ env/
134
+ venv/
135
+ ENV/
136
+ env.bak/
137
+ venv.bak/
138
+
139
+ # Spyder project settings
140
+ .spyderproject
141
+ .spyproject
142
+
143
+ # Rope project settings
144
+ .ropeproject
145
+
146
+ # mkdocs documentation
147
+ /site
148
+
149
+ # mypy
150
+ .mypy_cache/
151
+ .dmypy.json
152
+ dmypy.json
153
+
154
+ # Pyre type checker
155
+ .pyre/
156
+
157
+ # pytype static type analyzer
158
+ .pytype/
159
+
160
+ # Cython debug symbols
161
+ cython_debug/
162
+
163
+ # PyCharm
164
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
165
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
166
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
167
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
168
+ #.idea/
169
+
170
+ # PyPI configuration file
171
+ .pypirc
README.md CHANGED
@@ -1,14 +1,19 @@
1
- ---
2
- title: Research Paper Summerizer
3
- emoji: 🌍
4
- colorFrom: yellow
5
- colorTo: indigo
6
- sdk: streamlit
7
- sdk_version: 1.42.0
8
- app_file: app.py
9
- pinned: false
10
- license: mit
11
- short_description: Summarise the pdf based research paper
12
- ---
13
-
14
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
1
+ # Research Paper Summarizer
2
+
3
+ This app uses Hugging Face's model and LangChain to process research papers in PDF format and generate summaries or answers to queries.
4
+
5
+ ## Features
6
+ - Upload multiple research PDFs
7
+ - Create vector databases using FAISS
8
+ - Ask questions or request summaries from research content
9
+ - Powered by Hugging Face's model
10
+
11
+ ## How to Use
12
+ 1. Upload one or more PDFs.
13
+ 2. Click the **Process PDFs** button to create a vector store.
14
+ 3. Enter your query or summary request.
15
+ 4. Click **Get Summary/Answer** to generate a response.
16
+
17
+ ## Requirements
18
+ - Python 3.10+
19
+ - Hugging Face Space environment
app-open-source-models.py ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import tempfile
3
+ import streamlit as st
4
+ from langchain.text_splitter import RecursiveCharacterTextSplitter
5
+ from langchain.vectorstores import FAISS
6
+ from langchain.embeddings import HuggingFaceEmbeddings
7
+ from langchain.chains import RetrievalQA
8
+ from io import BytesIO
9
+ from langchain.document_loaders import PyPDFLoader
10
+ from transformers import pipeline
11
+ from langchain.schema import Document
12
+ from dotenv import load_dotenv
13
+ from transformers import AutoTokenizer
14
+ import transformers
15
+ import torch
16
+
17
+ # Load environment variables from Hugging Face Secrets
18
+ load_dotenv()
19
+
20
+ os.environ['HUGGINGFACE_API_KEY'] = os.getenv("HF_TOKEN")
21
+ os.environ["LANGCHAIN_API_KEY"] = os.getenv("LANGCHAIN_API_KEY")
22
+ os.environ["LANGCHAIN_TRACING_V2"] = "true"
23
+ os.environ["LANGCHAIN_PROJECT"]="Research-Paper-Summarizer"
24
+
25
+ # Streamlit Page Config
26
+ st.set_page_config(
27
+ page_title="Research Paper Summarizer",
28
+ layout="centered"
29
+ )
30
+
31
+ st.title("📚 Research Paper Summarizer - Using Open Source Models")
32
+
33
+ # File Uploader
34
+ uploaded_files = st.file_uploader(
35
+ "Upload one or more research PDFs",
36
+ type=["pdf"],
37
+ accept_multiple_files=True
38
+ )
39
+
40
+ # A placeholder to store vector database (FAISS)
41
+ if "vector_store" not in st.session_state:
42
+ st.session_state.vector_store = None
43
+
44
+ # Hugging Face LLM Model Pipeline
45
+ def get_huggingface_pipeline():
46
+
47
+ model_name = "meta-llama/Llama-3.2-1B"
48
+
49
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
50
+
51
+ st.info("Loading Hugging Face Model... Please wait.")
52
+
53
+ return transformers.pipeline(
54
+ "text-generation",
55
+ model=model_name,
56
+ tokenizer=tokenizer,
57
+ max_new_tokens=256,
58
+ torch_dtype=torch.bfloat16
59
+ )
60
+
61
+
62
+ # Process the PDFs, Create/Update the Vector Store
63
+ if st.button("Process PDFs") and uploaded_files:
64
+ all_documents = []
65
+
66
+ for file in uploaded_files:
67
+ # Save the file temporarily
68
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as temp_file:
69
+ temp_file.write(file.getvalue())
70
+ temp_file_path = temp_file.name
71
+
72
+ # Load the PDF using PyPDFLoader
73
+ loader = PyPDFLoader(temp_file_path)
74
+ pdf_docs = loader.load()
75
+
76
+ # Split text into manageable chunks
77
+ text_splitter = RecursiveCharacterTextSplitter(
78
+ chunk_size=1000,
79
+ chunk_overlap=300,
80
+ separators=["\n\n", "\n", " ", ""]
81
+ )
82
+
83
+ for doc in pdf_docs:
84
+ chunks = text_splitter.split_text(doc.page_content)
85
+ for chunk in chunks:
86
+ # Create Document object for each chunk
87
+ all_documents.append(Document(page_content=chunk, metadata=doc.metadata))
88
+
89
+ # Create embeddings with Hugging Face
90
+ embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")
91
+ st.session_state.vector_store = FAISS.from_documents(
92
+ documents=all_documents,
93
+ embedding=embeddings
94
+ )
95
+
96
+ st.success("PDFs processed and vector store created!")
97
+
98
+ # Query + Summarize
99
+ query = st.text_input("Enter your question or summary request:")
100
+
101
+ if st.button("Get Summary/Answer"):
102
+ if st.session_state.vector_store is None:
103
+ st.warning("Please upload and process PDFs first.")
104
+ else:
105
+ retriever = st.session_state.vector_store.as_retriever(
106
+ search_type="similarity",
107
+ search_kwargs={"k": 5}
108
+ )
109
+
110
+ # Use Hugging Face LLM
111
+ hf_pipeline = get_huggingface_pipeline()
112
+
113
+ # Retrieve documents and generate response
114
+ relevant_docs = retriever.get_relevant_documents(query)
115
+ context_text = "\n".join([doc.page_content for doc in relevant_docs])
116
+
117
+ # Generate answer using Hugging Face model
118
+ response = hf_pipeline(f"Context: {context_text}\nQuestion: {query}", num_return_sequences=1)
119
+
120
+ st.markdown("### Answer:")
121
+ st.write(response[0]['generated_text'])
122
+
123
+ with st.expander("Show source documents"):
124
+ for i, doc in enumerate(relevant_docs):
125
+ st.markdown(f"**Source Document {i + 1}:**")
126
+ st.write(doc.page_content)
127
+ st.write("---")
app.py CHANGED
@@ -13,7 +13,6 @@ from dotenv import load_dotenv
13
  # Load environment variables
14
  load_dotenv()
15
 
16
- os.environ['OPENAI_API_KEY'] = os.getenv("OPENAI_API_KEY")
17
  os.environ["LANGCHAIN_API_KEY"] = os.getenv("LANGCHAIN_API_KEY")
18
  os.environ["LANGCHAIN_TRACING_V2"] = "true"
19
  os.environ["LANGCHAIN_PROJECT"]="Research-Paper-Summarizer"
 
13
  # Load environment variables
14
  load_dotenv()
15
 
 
16
  os.environ["LANGCHAIN_API_KEY"] = os.getenv("LANGCHAIN_API_KEY")
17
  os.environ["LANGCHAIN_TRACING_V2"] = "true"
18
  os.environ["LANGCHAIN_PROJECT"]="Research-Paper-Summarizer"