Spaces:
Sleeping
Sleeping
Upload 2 files
Browse files- app (2).py +411 -0
- requirements.txt +8 -0
app (2).py
ADDED
@@ -0,0 +1,411 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
from dotenv import load_dotenv
|
3 |
+
from pymongo import MongoClient
|
4 |
+
# os.system("pip install streamlit pandas xlsxwriter openpyxl pymongo matplotlib seaborn")
|
5 |
+
|
6 |
+
import streamlit as st
|
7 |
+
import pandas as pd
|
8 |
+
import xlsxwriter
|
9 |
+
from io import BytesIO
|
10 |
+
from collections import defaultdict
|
11 |
+
import hashlib
|
12 |
+
import matplotlib.pyplot as plt
|
13 |
+
import seaborn as sns
|
14 |
+
|
15 |
+
# load_dotenv()
|
16 |
+
|
17 |
+
# Get MongoDB URI from environment
|
18 |
+
mongo_uri = os.environ.get("MONGODB_URI")
|
19 |
+
|
20 |
+
# MongoDB Setup
|
21 |
+
try:
|
22 |
+
from pymongo import MongoClient
|
23 |
+
client = MongoClient(mongo_uri)
|
24 |
+
db = client['BTP_DB']
|
25 |
+
results_collection = db['protein_results']
|
26 |
+
except:
|
27 |
+
results_collection = None
|
28 |
+
|
29 |
+
# Utility Functions
|
30 |
+
def is_homo_repeat(s):
|
31 |
+
return all(c == s[0] for c in s)
|
32 |
+
|
33 |
+
def hash_sequence(sequence):
|
34 |
+
return hashlib.md5(sequence.encode()).hexdigest()
|
35 |
+
|
36 |
+
@st.cache_data(show_spinner=False)
|
37 |
+
def fragment_protein_sequence(sequence, max_length=1000):
|
38 |
+
return [sequence[i:i+max_length] for i in range(0, len(sequence), max_length)]
|
39 |
+
|
40 |
+
def find_homorepeats(protein):
|
41 |
+
n = len(protein)
|
42 |
+
freq = defaultdict(int)
|
43 |
+
i = 0
|
44 |
+
while i < n:
|
45 |
+
curr = protein[i]
|
46 |
+
repeat = ""
|
47 |
+
while i < n and curr == protein[i]:
|
48 |
+
repeat += protein[i]
|
49 |
+
i += 1
|
50 |
+
if len(repeat) > 1:
|
51 |
+
freq[repeat] += 1
|
52 |
+
return freq
|
53 |
+
|
54 |
+
def find_hetero_amino_acid_repeats(sequence):
|
55 |
+
repeat_counts = defaultdict(int)
|
56 |
+
for length in range(2, len(sequence) + 1):
|
57 |
+
for i in range(len(sequence) - length + 1):
|
58 |
+
substring = sequence[i:i+length]
|
59 |
+
repeat_counts[substring] += 1
|
60 |
+
return {k: v for k, v in repeat_counts.items() if v > 1}
|
61 |
+
|
62 |
+
def check_boundary_repeats(fragments, final_repeats, overlap=50):
|
63 |
+
for i in range(len(fragments) - 1):
|
64 |
+
left_overlap = fragments[i][-overlap:]
|
65 |
+
right_overlap = fragments[i + 1][:overlap]
|
66 |
+
overlap_region = left_overlap + right_overlap
|
67 |
+
boundary_repeats = find_hetero_amino_acid_repeats(overlap_region)
|
68 |
+
for substring, count in boundary_repeats.items():
|
69 |
+
if any(aa in left_overlap for aa in substring) and any(aa in right_overlap for aa in substring):
|
70 |
+
final_repeats[substring] += count
|
71 |
+
return final_repeats
|
72 |
+
|
73 |
+
def find_new_boundary_repeats(fragments, final_repeats, overlap=50):
|
74 |
+
new_repeats = defaultdict(int)
|
75 |
+
for i in range(len(fragments) - 1):
|
76 |
+
left_overlap = fragments[i][-overlap:]
|
77 |
+
right_overlap = fragments[i + 1][:overlap]
|
78 |
+
overlap_region = left_overlap + right_overlap
|
79 |
+
boundary_repeats = find_hetero_amino_acid_repeats(overlap_region)
|
80 |
+
for substring, count in boundary_repeats.items():
|
81 |
+
if any(aa in left_overlap for aa in substring) and any(aa in right_overlap for aa in substring):
|
82 |
+
if substring not in final_repeats:
|
83 |
+
new_repeats[substring] += count
|
84 |
+
return new_repeats
|
85 |
+
|
86 |
+
def get_or_process_sequence(sequence, analysis_type, overlap=50):
|
87 |
+
if results_collection is None:
|
88 |
+
return {}
|
89 |
+
hash_input = f"{sequence}_{analysis_type}"
|
90 |
+
sequence_hash = hash_sequence(hash_input)
|
91 |
+
cached = results_collection.find_one({"_id": sequence_hash})
|
92 |
+
if cached:
|
93 |
+
return cached["repeats"]
|
94 |
+
|
95 |
+
fragments = fragment_protein_sequence(sequence)
|
96 |
+
final_repeats = defaultdict(int)
|
97 |
+
|
98 |
+
if analysis_type == "Hetero":
|
99 |
+
for fragment in fragments:
|
100 |
+
fragment_repeats = find_hetero_amino_acid_repeats(fragment)
|
101 |
+
for k, v in fragment_repeats.items():
|
102 |
+
final_repeats[k] += v
|
103 |
+
final_repeats = check_boundary_repeats(fragments, final_repeats, overlap)
|
104 |
+
new_repeats = find_new_boundary_repeats(fragments, final_repeats, overlap)
|
105 |
+
for k, v in new_repeats.items():
|
106 |
+
final_repeats[k] += v
|
107 |
+
final_repeats = {k: v for k, v in final_repeats.items() if not is_homo_repeat(k)}
|
108 |
+
|
109 |
+
elif analysis_type == "Homo":
|
110 |
+
final_repeats = find_homorepeats(sequence)
|
111 |
+
|
112 |
+
elif analysis_type == "Both":
|
113 |
+
hetero_repeats = defaultdict(int)
|
114 |
+
for fragment in fragments:
|
115 |
+
fragment_repeats = find_hetero_amino_acid_repeats(fragment)
|
116 |
+
for k, v in fragment_repeats.items():
|
117 |
+
hetero_repeats[k] += v
|
118 |
+
hetero_repeats = check_boundary_repeats(fragments, hetero_repeats, overlap)
|
119 |
+
new_repeats = find_new_boundary_repeats(fragments, hetero_repeats, overlap)
|
120 |
+
for k, v in new_repeats.items():
|
121 |
+
hetero_repeats[k] += v
|
122 |
+
hetero_repeats = {k: v for k, v in hetero_repeats.items() if not is_homo_repeat(k)}
|
123 |
+
homo_repeats = find_homorepeats(sequence)
|
124 |
+
final_repeats = homo_repeats.copy()
|
125 |
+
for k, v in hetero_repeats.items():
|
126 |
+
final_repeats[k] += v
|
127 |
+
|
128 |
+
results_collection.insert_one({
|
129 |
+
"_id": sequence_hash,
|
130 |
+
"sequence": sequence,
|
131 |
+
"analysis_type": analysis_type,
|
132 |
+
"repeats": dict(final_repeats)
|
133 |
+
})
|
134 |
+
return final_repeats
|
135 |
+
|
136 |
+
def process_excel(excel_data, analysis_type):
|
137 |
+
repeats = set()
|
138 |
+
sequence_data = []
|
139 |
+
count = 0
|
140 |
+
for sheet_name in excel_data.sheet_names:
|
141 |
+
df = excel_data.parse(sheet_name)
|
142 |
+
if len(df.columns) < 3:
|
143 |
+
st.error(f"Error: The sheet '{sheet_name}' must have at least three columns: ID, Protein Name, Sequence")
|
144 |
+
return None, None
|
145 |
+
for _, row in df.iterrows():
|
146 |
+
entry_id = str(row[0])
|
147 |
+
protein_name = str(row[1])
|
148 |
+
sequence = str(row[2]).replace('"', '').replace(' ', '').strip()
|
149 |
+
if not sequence:
|
150 |
+
continue
|
151 |
+
count += 1
|
152 |
+
freq = get_or_process_sequence(sequence, analysis_type)
|
153 |
+
sequence_data.append((entry_id, protein_name, freq))
|
154 |
+
repeats.update(freq.keys())
|
155 |
+
st.toast(f"{count} sequences processed.")
|
156 |
+
return repeats, sequence_data
|
157 |
+
|
158 |
+
def create_excel(sequences_data, repeats, filenames):
|
159 |
+
output = BytesIO()
|
160 |
+
workbook = xlsxwriter.Workbook(output, {'in_memory': True})
|
161 |
+
for file_index, file_data in enumerate(sequences_data):
|
162 |
+
filename = filenames[file_index]
|
163 |
+
worksheet = workbook.add_worksheet(filename[:31])
|
164 |
+
worksheet.write(0, 0, "Entry")
|
165 |
+
worksheet.write(0, 1, "Protein Name")
|
166 |
+
col = 2
|
167 |
+
for repeat in sorted(repeats):
|
168 |
+
worksheet.write(0, col, repeat)
|
169 |
+
col += 1
|
170 |
+
row = 1
|
171 |
+
for entry_id, protein_name, freq in file_data:
|
172 |
+
worksheet.write(row, 0, entry_id)
|
173 |
+
worksheet.write(row, 1, protein_name)
|
174 |
+
col = 2
|
175 |
+
for repeat in sorted(repeats):
|
176 |
+
worksheet.write(row, col, freq.get(repeat, 0))
|
177 |
+
col += 1
|
178 |
+
row += 1
|
179 |
+
workbook.close()
|
180 |
+
output.seek(0)
|
181 |
+
return output
|
182 |
+
|
183 |
+
# Streamlit UI
|
184 |
+
st.set_page_config(page_title="Protein Tool", layout="wide")
|
185 |
+
st.title("𧬠Protein Analysis Toolkit by SCBL, IITG")
|
186 |
+
|
187 |
+
app_choice = st.radio("Choose an option", ["π Protein Repeat Finder", "π Protein Comparator", "π§ͺ Amino Acid Percentage Analyzer"])
|
188 |
+
|
189 |
+
if app_choice == "π Protein Repeat Finder":
|
190 |
+
analysis_type = st.radio("Select analysis type:", ["Homo", "Hetero", "Both"], index=2)
|
191 |
+
uploaded_files = st.file_uploader("Upload Excel files", accept_multiple_files=True, type=["xlsx"])
|
192 |
+
|
193 |
+
if 'all_sequences_data' not in st.session_state:
|
194 |
+
st.session_state.all_sequences_data = []
|
195 |
+
st.session_state.all_repeats = set()
|
196 |
+
st.session_state.filenames = []
|
197 |
+
st.session_state.excel_file = None
|
198 |
+
|
199 |
+
if uploaded_files and st.button("Process Files"):
|
200 |
+
st.session_state.all_repeats = set()
|
201 |
+
st.session_state.all_sequences_data = []
|
202 |
+
st.session_state.filenames = []
|
203 |
+
for file in uploaded_files:
|
204 |
+
excel_data = pd.ExcelFile(file)
|
205 |
+
repeats, sequence_data = process_excel(excel_data, analysis_type)
|
206 |
+
if repeats is not None:
|
207 |
+
st.session_state.all_repeats.update(repeats)
|
208 |
+
st.session_state.all_sequences_data.append(sequence_data)
|
209 |
+
st.session_state.filenames.append(file.name)
|
210 |
+
if st.session_state.all_sequences_data:
|
211 |
+
st.toast(f"Processed {len(uploaded_files)} file(s) successfully.")
|
212 |
+
st.session_state.excel_file = create_excel(
|
213 |
+
st.session_state.all_sequences_data,
|
214 |
+
st.session_state.all_repeats,
|
215 |
+
st.session_state.filenames
|
216 |
+
)
|
217 |
+
|
218 |
+
if st.session_state.excel_file:
|
219 |
+
st.download_button(
|
220 |
+
label="Download Excel file",
|
221 |
+
data=st.session_state.excel_file,
|
222 |
+
file_name="Protein_Repeats_Analysis.xlsx",
|
223 |
+
mime="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
|
224 |
+
)
|
225 |
+
|
226 |
+
# Display results table and repeat cluster visualization
|
227 |
+
if st.checkbox("Show Results Table"):
|
228 |
+
rows = []
|
229 |
+
for file_index, file_data in enumerate(st.session_state.all_sequences_data):
|
230 |
+
filename = st.session_state.filenames[file_index]
|
231 |
+
for entry_id, protein_name, freq in file_data:
|
232 |
+
row = {"Filename": filename, "Entry": entry_id, "Protein Name": protein_name}
|
233 |
+
row.update({repeat: freq.get(repeat, 0) for repeat in sorted(st.session_state.all_repeats)})
|
234 |
+
rows.append(row)
|
235 |
+
result_df = pd.DataFrame(rows)
|
236 |
+
st.dataframe(result_df)
|
237 |
+
|
238 |
+
# Repeat Cluster Visualization
|
239 |
+
repeat_counts = defaultdict(int)
|
240 |
+
for seq_data in st.session_state.all_sequences_data:
|
241 |
+
for _, _, freq_dict in seq_data:
|
242 |
+
for repeat, count in freq_dict.items():
|
243 |
+
repeat_counts[repeat] += count
|
244 |
+
|
245 |
+
if repeat_counts:
|
246 |
+
sorted_repeats = sorted(repeat_counts.items(), key=lambda x: x[1], reverse=True)
|
247 |
+
top_n = st.slider("Select number of top repeats to visualize", min_value=5, max_value=50, value=20)
|
248 |
+
top_repeats = sorted_repeats[:top_n]
|
249 |
+
repeats, counts = zip(*top_repeats)
|
250 |
+
|
251 |
+
plt.figure(figsize=(12, 6))
|
252 |
+
sns.barplot(x=list(repeats), y=list(counts), palette="viridis")
|
253 |
+
plt.xticks(rotation=45, ha='right')
|
254 |
+
plt.xlabel("Repeats")
|
255 |
+
plt.ylabel("Total Frequency")
|
256 |
+
plt.title("Top Repeat Clusters Across All Sequences")
|
257 |
+
st.pyplot(plt.gcf())
|
258 |
+
else:
|
259 |
+
st.warning("No repeat data available to visualize. Please upload files first.")
|
260 |
+
|
261 |
+
|
262 |
+
|
263 |
+
elif app_choice == "π Protein Comparator":
|
264 |
+
st.write("Upload two Excel files with protein data to compare repeat frequencies.")
|
265 |
+
|
266 |
+
file1 = st.file_uploader("Upload First Excel File", type=["xlsx"], key="comp1")
|
267 |
+
file2 = st.file_uploader("Upload Second Excel File", type=["xlsx"], key="comp2")
|
268 |
+
|
269 |
+
if file1 and file2:
|
270 |
+
df1 = pd.read_excel(file1)
|
271 |
+
df2 = pd.read_excel(file2)
|
272 |
+
|
273 |
+
df1.columns = df1.columns.astype(str)
|
274 |
+
df2.columns = df2.columns.astype(str)
|
275 |
+
|
276 |
+
id_col = df1.columns[0]
|
277 |
+
name_col = df1.columns[1]
|
278 |
+
repeat_columns = df1.columns[2:]
|
279 |
+
|
280 |
+
diff_data = []
|
281 |
+
for i in range(min(len(df1), len(df2))):
|
282 |
+
row1 = df1.iloc[i]
|
283 |
+
row2 = df2.iloc[i]
|
284 |
+
diff_row = {"Entry": row1[id_col], "Protein Name": row1[name_col]}
|
285 |
+
for repeat in repeat_columns:
|
286 |
+
val1 = row1.get(repeat, 0)
|
287 |
+
val2 = row2.get(repeat, 0)
|
288 |
+
change = ((val2 - val1) / val1 * 100) if val1 != 0 else (100 if val2 > 0 else 0)
|
289 |
+
diff_row[repeat] = change
|
290 |
+
diff_data.append(diff_row)
|
291 |
+
|
292 |
+
result_df = pd.DataFrame(diff_data)
|
293 |
+
percent_cols = result_df.select_dtypes(include='number').columns
|
294 |
+
st.dataframe(result_df.style.format({col: "{:.2f}%" for col in percent_cols}))
|
295 |
+
|
296 |
+
def to_excel_with_colors(df):
|
297 |
+
output = BytesIO()
|
298 |
+
workbook = xlsxwriter.Workbook(output, {'in_memory': True})
|
299 |
+
worksheet = workbook.add_worksheet('Comparison')
|
300 |
+
|
301 |
+
green_format = workbook.add_format({'font_color': 'green'})
|
302 |
+
red_format = workbook.add_format({'font_color': 'red'})
|
303 |
+
header_format = workbook.add_format({'bold': True, 'bg_color': '#D7E4BC'})
|
304 |
+
|
305 |
+
for col_num, col_name in enumerate(df.columns):
|
306 |
+
worksheet.write(0, col_num, col_name, header_format)
|
307 |
+
|
308 |
+
for row_num, row in enumerate(df.itertuples(index=False), start=1):
|
309 |
+
for col_num, value in enumerate(row):
|
310 |
+
if col_num < 2:
|
311 |
+
worksheet.write(row_num, col_num, value)
|
312 |
+
else:
|
313 |
+
fmt = green_format if value > 0 else red_format if value < 0 else None
|
314 |
+
worksheet.write(row_num, col_num, f"{value:.2f}%", fmt)
|
315 |
+
|
316 |
+
workbook.close()
|
317 |
+
output.seek(0)
|
318 |
+
return output
|
319 |
+
|
320 |
+
excel_file = to_excel_with_colors(result_df)
|
321 |
+
|
322 |
+
st.download_button(
|
323 |
+
label="Download Colored Comparison Excel",
|
324 |
+
data=excel_file,
|
325 |
+
file_name="comparison_result_colored.xlsx",
|
326 |
+
mime="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
|
327 |
+
)
|
328 |
+
|
329 |
+
elif app_choice == "π§ͺ Amino Acid Percentage Analyzer":
|
330 |
+
import matplotlib.pyplot as plt # Needed for pie chart
|
331 |
+
|
332 |
+
AMINO_ACIDS = set("ACDEFGHIKLMNPQRSTVWY")
|
333 |
+
|
334 |
+
uploaded_file = st.file_uploader("Upload Excel file (with Entry, Protein Name, Sequence)", type=["xlsx"])
|
335 |
+
|
336 |
+
if uploaded_file and st.button("Analyze File"):
|
337 |
+
df = pd.read_excel(uploaded_file)
|
338 |
+
|
339 |
+
if len(df.columns) < 3:
|
340 |
+
st.error("The file must have at least three columns: Entry, Protein Name, Sequence")
|
341 |
+
else:
|
342 |
+
entry_col = df.columns[0]
|
343 |
+
name_col = df.columns[1]
|
344 |
+
seq_col = df.columns[2]
|
345 |
+
|
346 |
+
from collections import Counter
|
347 |
+
all_counts = Counter()
|
348 |
+
all_length = 0
|
349 |
+
result_rows = []
|
350 |
+
|
351 |
+
for _, row in df.iterrows():
|
352 |
+
entry = str(row[entry_col])
|
353 |
+
name = str(row[name_col])
|
354 |
+
sequence = str(row[seq_col]).replace(" ", "").replace("\"", "").strip().upper()
|
355 |
+
sequence = ''.join(filter(lambda c: c in AMINO_ACIDS, sequence))
|
356 |
+
length = len(sequence)
|
357 |
+
|
358 |
+
if length == 0:
|
359 |
+
continue
|
360 |
+
|
361 |
+
count = Counter(sequence)
|
362 |
+
all_counts.update(count)
|
363 |
+
all_length += length
|
364 |
+
percentage = {aa: round(count[aa] / length * 100, 2) for aa in AMINO_ACIDS}
|
365 |
+
result_rows.append({"Entry": entry, "Protein Name": name, **percentage})
|
366 |
+
|
367 |
+
overall_percentage = {aa: round(all_counts[aa] / all_length * 100, 2) for aa in AMINO_ACIDS}
|
368 |
+
overall_row = {"Entry": "OVERALL", "Protein Name": "ALL SEQUENCES", **overall_percentage}
|
369 |
+
df_result = pd.concat([pd.DataFrame([overall_row]), pd.DataFrame(result_rows)], ignore_index=True)
|
370 |
+
|
371 |
+
st.dataframe(df_result)
|
372 |
+
|
373 |
+
# π΅ Pie Chart
|
374 |
+
st.subheader("π§ Overall Amino Acid Composition (Pie Chart)")
|
375 |
+
fig, ax = plt.subplots(figsize=(9, 9))
|
376 |
+
labels = list(overall_percentage.keys())
|
377 |
+
sizes = list(overall_percentage.values())
|
378 |
+
filtered = [(label, size) for label, size in zip(labels, sizes) if size > 0]
|
379 |
+
|
380 |
+
if filtered:
|
381 |
+
labels, sizes = zip(*filtered)
|
382 |
+
ax.pie(sizes, labels=labels, autopct='%1.1f%%', startangle=90, counterclock=False)
|
383 |
+
ax.axis('equal')
|
384 |
+
st.pyplot(fig)
|
385 |
+
else:
|
386 |
+
st.info("No valid amino acids found to display in pie chart.")
|
387 |
+
|
388 |
+
# Excel Export
|
389 |
+
def to_excel(df):
|
390 |
+
output = BytesIO()
|
391 |
+
workbook = xlsxwriter.Workbook(output, {'in_memory': True})
|
392 |
+
worksheet = workbook.add_worksheet("Amino Acid %")
|
393 |
+
header_format = workbook.add_format({'bold': True, 'bg_color': '#CDEDF6'})
|
394 |
+
for col_num, col_name in enumerate(df.columns):
|
395 |
+
worksheet.write(0, col_num, col_name, header_format)
|
396 |
+
for row_num, row in enumerate(df.itertuples(index=False), start=1):
|
397 |
+
for col_num, value in enumerate(row):
|
398 |
+
worksheet.write(row_num, col_num, value)
|
399 |
+
workbook.close()
|
400 |
+
output.seek(0)
|
401 |
+
return output
|
402 |
+
|
403 |
+
excel_file = to_excel(df_result)
|
404 |
+
|
405 |
+
st.download_button(
|
406 |
+
label="Download Excel Report",
|
407 |
+
data=excel_file,
|
408 |
+
file_name="amino_acid_percentage.xlsx",
|
409 |
+
mime="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
|
410 |
+
)
|
411 |
+
|
requirements.txt
ADDED
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
streamlit
|
2 |
+
pandas
|
3 |
+
xlsxwriter
|
4 |
+
openpyxl
|
5 |
+
pymongo
|
6 |
+
matplotlib
|
7 |
+
seaborn
|
8 |
+
python-dotenv
|