fadliaulawi commited on
Commit
827d3b2
1 Parent(s): 36bfc91

Delete old application

Browse files
Files changed (1) hide show
  1. app-old.py +0 -167
app-old.py DELETED
@@ -1,167 +0,0 @@
1
- import io
2
- import os
3
- import pandas as pd
4
- import streamlit as st
5
-
6
- from concurrent.futures import ThreadPoolExecutor
7
- from datetime import datetime
8
- from langchain_community.document_loaders.pdf import PyPDFLoader
9
- from langchain_core.documents.base import Document
10
- from langchain_text_splitters import TokenTextSplitter
11
- from process import Process
12
- from tempfile import NamedTemporaryFile
13
- from stqdm import stqdm
14
- from validate import Validation
15
-
16
- buffer = io.BytesIO()
17
-
18
- st.cache_data()
19
- st.set_page_config(page_title="NutriGenMe Paper Extractor")
20
- st.title("NutriGenMe - Paper Extractor")
21
- st.markdown("<div style='text-align: justify;text-justify: inter-word;'>NutriGenMe Paper Extractor is a tool designed to extract relevant information from genomic papers related to the NutriGenMe project. It utilizes natural language processing techniques to parse through documents and extract key data points, enabling researchers and practitioners to efficiently gather insights from a large corpus of literature.</div>", unsafe_allow_html=True)
22
- st.divider()
23
-
24
- st.markdown("<h4>Extraction</h4>", unsafe_allow_html=True)
25
- col1, col2 = st.columns(2)
26
- st.markdown("<h4>Validation</h4>", unsafe_allow_html=True)
27
- col3, col4 = st.columns(2)
28
-
29
- with col1:
30
- models = (
31
- 'gpt-4-turbo',
32
- 'gemini-1.5-pro-latest',
33
- # 'llama-3-sonar-large-32k-chat',
34
- # 'mixtral-8x7b-instruct',
35
- )
36
- model = st.selectbox('Model selection:', models, key='model')
37
-
38
- with col2:
39
- tokens = (
40
- 8000,
41
- 16000,
42
- 24000
43
- )
44
- chunk_option = st.selectbox('Token amounts per process:', tokens, key='token')
45
- chunk_overlap = 0
46
-
47
- with col3:
48
- models_val = (
49
- 'gpt-4-turbo',
50
- 'gemini-1.5-pro-latest',
51
- 'mixtral-8x7b-instruct',
52
- # 'llama-3-sonar-large-32k-chat',
53
- )
54
- model_val = st.selectbox('Model validator selection:', models_val, key='model_val')
55
-
56
- with col4:
57
- api = st.toggle('Validate with API')
58
-
59
- if api:
60
- st.warning("""This validation process leverage external application programming interfaces (APIs) from NCBI and EBI to verify information.
61
- These APIs may have limitations on their usage, so please exercise responsible use of this functionality.
62
- If you opt to employ API validation and the process takes a long time (more than 1 hour), consider refreshing the page and proceeding without API validation.""", icon="⚠️")
63
-
64
- st.divider()
65
- st.markdown("<h4>Process</h4>", unsafe_allow_html=True)
66
- uploaded_files = st.file_uploader("Upload Paper(s) here :", type="pdf", accept_multiple_files=True)
67
-
68
- if uploaded_files:
69
- submit = st.button("Get Result", key='submit')
70
-
71
- if uploaded_files and submit:
72
-
73
- with st.status("Extraction in progress ...", expanded=True) as status:
74
- for uploaded_file in stqdm(uploaded_files):
75
- start_time = datetime.now()
76
- with NamedTemporaryFile(dir='.', suffix=".pdf", delete=eval(os.getenv('DELETE_TEMP_PDF', 'True'))) as pdf:
77
-
78
- pdf.write(uploaded_file.getbuffer())
79
- st.markdown(f"Start Extraction process at <code>{datetime.now().strftime('%H:%M')}</code>", unsafe_allow_html=True)
80
-
81
- # Load Documents
82
- loader = PyPDFLoader(pdf.name)
83
- pages = loader.load()
84
-
85
- chunk_size = 120000
86
- chunk_overlap = 0
87
- docs = pages
88
-
89
- # Split Documents
90
- if chunk_option:
91
- docs = [Document('\n'.join([page.page_content for page in pages]))]
92
- docs[0].metadata = {'source': pages[0].metadata['source']}
93
-
94
- chunk_size = chunk_option
95
- chunk_overlap = int(0.25 * chunk_size)
96
-
97
- text_splitter = TokenTextSplitter.from_tiktoken_encoder(
98
- chunk_size=chunk_size, chunk_overlap=chunk_overlap
99
- )
100
- chunks = text_splitter.split_documents(docs)
101
-
102
- # Start extraction process in parallel
103
- process = Process(model)
104
- with ThreadPoolExecutor() as executor:
105
- result_gsd = executor.submit(process.get_entity, (chunks, 'gsd'))
106
- result_summ = executor.submit(process.get_entity, (chunks, 'summ'))
107
- result = executor.submit(process.get_entity, (chunks, 'all'))
108
- result_one = executor.submit(process.get_entity_one, [c.page_content for c in chunks[:1]])
109
- result_table = executor.submit(process.get_table, pdf.name)
110
-
111
- result_gsd = result_gsd.result()
112
- result_summ = result_summ.result()
113
- result = result.result()
114
- result_one = result_one.result()
115
- res_gene, res_snp, res_dis = result_table.result()
116
-
117
- # Combine Result
118
- result['Genes'] = res_gene + result_gsd['Genes']
119
- result['SNPs'] = res_snp + result_gsd['SNPs']
120
- result['Diseases'] = res_dis + result_gsd['Diseases']
121
- result['Conclusion'] = result_summ
122
- for k in result_one.keys():
123
- result[k] = result_one[k]
124
-
125
- if len(result['Genes']) == 0:
126
- result['Genes'] = ['']
127
-
128
- # Adjust Genes, SNPs, Diseases
129
- num_rows = max(max(len(result['Genes']), len(result['SNPs'])), len(result['Diseases']))
130
- for k in ['Genes', 'SNPs', 'Diseases']:
131
- while len(result[k]) < num_rows:
132
- result[k].append('')
133
-
134
- # Temporary handling
135
- result[k] = result[k][:num_rows]
136
-
137
- # Arrange Column
138
- result = {key: value if isinstance(value, list) else [value] * num_rows for key, value in result.items()}
139
- dataframe = pd.DataFrame(result)
140
- dataframe = dataframe[['Genes', 'SNPs', 'Diseases', 'Title', 'Authors', 'Publisher Name', 'Publication Year', 'Population', 'Sample Size', 'Study Methodology', 'Study Level', 'Conclusion']]
141
- dataframe = dataframe[dataframe['Genes'].astype(bool)].reset_index(drop=True)
142
- dataframe.reset_index(drop=True, inplace=True)
143
-
144
- # Validate Result
145
- st.markdown(f"Start Validation process at <code>{datetime.now().strftime('%H:%M')}</code>", unsafe_allow_html=True)
146
- validation = Validation(model_val)
147
- df, df_no_llm, df_clean = validation.validate(dataframe, api)
148
- df.drop_duplicates(['Genes', 'SNPs'], inplace=True)
149
- st.write("Success in ", round((datetime.now().timestamp() - start_time.timestamp()) / 60, 2), "minutes")
150
-
151
- st.dataframe(df)
152
- with pd.ExcelWriter(buffer, engine='xlsxwriter') as writer:
153
- if api:
154
- df.to_excel(writer, sheet_name='Result Cleaned API LLM')
155
- df_no_llm.to_excel(writer, sheet_name='Result Cleaned API')
156
- else:
157
- df.to_excel(writer, sheet_name='Result Cleaned LLM')
158
- df_clean.to_excel(writer, sheet_name='Result Cleaned')
159
- dataframe.to_excel(writer, sheet_name='Original')
160
- writer.close()
161
-
162
- st.download_button(
163
- label="Save Result",
164
- data=buffer,
165
- file_name=f"{uploaded_file.name.replace('.pdf', '')}_{chunk_option}_{model.split('-')[0]}_{model_val.split('-')[0]}.xlsx",
166
- mime='application/vnd.ms-excel'
167
- )