Repository navigation
Expand file tree
/
Copy pathserver.py
More file actions
executable file
·1926 lines (1706 loc) · 92.5 KB
/
Copy pathserver.py
File metadata and controls
executable file
·1926 lines (1706 loc) · 92.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/bin/env python3
from __future__ import print_function
import hashlib
import json
import os
import random
import re
import shutil
import string
import tempfile
from os import listdir
import bcrypt
import nltk
# import numpy as np # Removed
import pandas as pd
import pytz
from flask import (Flask, Response, flash, jsonify, redirect, render_template,
request, session, url_for)
from flask_sqlalchemy import SQLAlchemy
import os
def _read_gemini_api_key():
"""Read Gemini API key from ~/.config/gemini/credentials."""
import stat
cred_file = os.path.expanduser("~/.config/gemini/credentials")
try:
mode = os.stat(cred_file).st_mode & 0o777
if mode != 0o400:
print(f"ERROR: {cred_file} has permissions {oct(mode)}, expected 0400. Fix with: chmod 400 {cred_file}")
raise SystemExit(1)
with open(cred_file, 'r') as f:
key = f.read().strip()
if key:
return key
except FileNotFoundError:
pass
return None
GEMINI_API_KEY = _read_gemini_api_key()
# nltk.download('punkt') # we should prefetch
# import pickle # Removed
from collections import Counter
from datetime import datetime
# Gemini API related imports
from google import genai
# Removed TensorFlow and Keras related imports
# import tensorflow
# import tensorflow.keras
# from nltk.corpus import stopwords # Removed
# from nltk.stem.porter import PorterStemmer # Removed
# from tensorflow.keras import backend as K # Removed
# from tensorflow.keras import metrics, optimizers # Removed
# from tensorflow.keras.layers import * # Removed (Dense, Embedding, Flatten, Conv1D, MaxPooling1D)
# from tensorflow.keras.models import Model, Sequential # Removed
# from tensorflow.keras.preprocessing.sequence import pad_sequences # Removed
# from tensorflow.keras.preprocessing.text import Tokenizer # Removed
import re
import ast
from more_functions import *
from nltk.tokenize import sent_tokenize
from more_functions import getabstracts, getabstracts_batch, undic, gene_category
GENECUP_PROMPT_TEMPLATE = ""
try:
with open("genecup_synthesis_prompt.txt", "r") as f:
GENECUP_PROMPT_TEMPLATE = f.read()
except FileNotFoundError:
print("Warning: genecup_synthesis_prompt.txt not found. LLM prompts will be incomplete.")
except Exception as e:
print(f"Error loading genecup_synthesis_prompt.txt: {e}. LLM prompts will be affected.")
VERSION=None
def version():
global VERSION
if VERSION is None:
with open("VERSION", 'r') as file:
VERSION = file.read()
return VERSION
app=Flask(__name__)
datadir=os.environ.get("GENECUP_DATADIR", "./")
app.config['SECRET_KEY'] = '#DtfrL98G5t1dC*4'
sqlitedb = 'sqlite:///'+datadir+'/userspub.sqlite'
print(sqlitedb)
app.config['SQLALCHEMY_DATABASE_URI'] = sqlitedb
db = SQLAlchemy(app)
def get_sentences_from_file(file_path, gene_name, category_name=None):
"""Reads a sentence file and returns sentences matching a gene and category."""
matching_sentences = []
try:
with open(file_path, "r") as f:
for line in f:
if not line.strip():
continue
try:
(gene, nouse, cat, pmid, text) = line.split("\t")
cat_match = (category_name is None) or (cat.strip().upper() == category_name.strip().upper())
if (gene.strip().upper() == gene_name.strip().upper() and cat_match):
matching_sentences.append({'pmid': pmid, 'text': text, 'category': cat})
except ValueError:
continue
except FileNotFoundError:
print(f"Sentence file not found: {file_path}")
except Exception as e:
print(f"Error reading sentence file {file_path}: {e}")
return matching_sentences
# Validate punkt tokenizer is available
try:
nltk.data.find('tokenizers/punkt_tab')
except LookupError:
print("ERROR: NLTK punkt_tab tokenizer not found. Set NLTK_DATA or install punkt_tab data.")
print(" NLTK data paths: " + str(nltk.data.path))
raise SystemExit(1)
# Initialize database within application context
with app.app_context():
db.create_all()
# Configure Gemini API Client
GEMINI_API_KEY = _read_gemini_api_key()
gemini_client = None
if not GEMINI_API_KEY:
print("Warning: ~/.config/gemini/credentials not found or empty. Stress classification via Gemini will not work.")
else:
try:
gemini_client = genai.Client(api_key=GEMINI_API_KEY)
except Exception as e:
print(f"Error initializing Gemini API client: {e}")
GEMINI_API_KEY = None
STRESS_PROMPT_TEMPLATE = "" # unused: batch classifier builds its own prompt
# In-memory cache for Gemini stress classification: hash(sentence) -> result
_gemini_cache = {}
# Sqlite database
class users(db.Model):
__tablename__='user'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(80), nullable=False)
email = db.Column(db.String(80), unique=True, nullable=False)
password = db.Column(db.String(128), nullable=False)
date_created = db.Column(db.DateTime, default=datetime.utcnow)
# Use addiction ontology by default
import ast # Moved import ast here as it's first used here.
onto_cont=open("addiction.onto","r").read()
dictionary=ast.literal_eval(onto_cont)
@app.route("/")
def root():
if 'email' in session:
ontoarchive()
onto_len_dir = session['onto_len_dir']
onto_list = session['onto_list']
else:
onto_len_dir = 0
onto_list = ''
onto_cont=open("addiction.onto","r").read()
dict_onto=ast.literal_eval(onto_cont)
return render_template('index.html',onto_len_dir=onto_len_dir, onto_list=onto_list, ontol = 'addiction', dict_onto = dict_onto,version=version())
@app.route("/login", methods=["POST", "GET"])
def login():
onto_len_dir = 0
onto_list = ''
onto_cont=open("addiction.onto","r").read()
dict_onto=ast.literal_eval(onto_cont)
email = None
if request.method == "POST":
email = request.form['email']
password = request.form['password']
found_user = users.query.filter_by(email=email).first()
if (found_user and (bcrypt.checkpw(password.encode('utf8'), found_user.password))):
session['email'] = found_user.email
#print(bcrypt.hashpw(session['email'].encode('utf8'), bcrypt.gensalt()))
session['hashed_email'] = hashlib.md5(session['email'] .encode('utf-8')).hexdigest()
session['name'] = found_user.name
session['id'] = found_user.id
flash("Login Succesful!")
ontoarchive()
onto_len_dir = session['onto_len_dir']
onto_list = session['onto_list']
else:
flash("Invalid username or password!", "inval")
return render_template('signup.html',version=version())
return render_template('index.html',onto_len_dir=onto_len_dir, onto_list=onto_list, ontol = 'addiction', dict_onto = dict_onto,version=version())
@app.route("/signup", methods=["POST", "GET"])
def signup():
onto_len_dir = 0
onto_list = ''
onto_cont=open("addiction.onto","r").read()
dict_onto=ast.literal_eval(onto_cont)
if request.method == "POST":
name = request.form['name']
email = request.form['email']
password = request.form['password']
found_user = users.query.filter_by(email=email).first()
if (found_user and (bcrypt.checkpw(password.encode('utf8'), found_user.password)==False)):
flash("Already registered, but wrong password!", "inval")
return render_template('signup.html',onto_len_dir=onto_len_dir, onto_list=onto_list, ontol = 'addiction', dict_onto = dict_onto,version=version())
session['email'] = email
session['hashed_email'] = hashlib.md5(session['email'] .encode('utf-8')).hexdigest()
session['name'] = name
password = bcrypt.hashpw(password.encode('utf8'), bcrypt.gensalt())
user = users(name=name, email=email, password = password)
if found_user:
session['email'] = found_user.email
session['hashed_email'] = hashlib.md5(session['email'] .encode('utf-8')).hexdigest()
session['id'] = found_user.id
found_user.name = name
db.session.commit()
ontoarchive()
onto_len_dir = session['onto_len_dir']
onto_list = session['onto_list']
else:
db.session.add(user)
db.session.commit()
newuser = users.query.filter_by(email=session['email']).first()
session['id'] = newuser.id
os.makedirs(datadir+"/user/"+str(session['hashed_email']))
session['user_folder'] = datadir+"/user/"+str(session['hashed_email'])
os.makedirs(session['user_folder']+"/ontology/")
flash("Login Succesful!")
return render_template('index.html',onto_len_dir=onto_len_dir, onto_list=onto_list, ontol = 'addiction', dict_onto = dict_onto,version=version())
else:
if 'email' in session:
flash("Already Logged In!")
return render_template('index.html',onto_len_dir=onto_len_dir, onto_list=onto_list, ontol = 'addiction', dict_onto = dict_onto,version=version())
return render_template('signup.html',onto_len_dir=onto_len_dir, onto_list=onto_list, ontol = 'addiction', dict_onto = dict_onto,version=version())
@app.route("/signin", methods=["POST", "GET"])
def signin():
email = None
if request.method == "POST":
email = request.form['email']
password = request.form['password']
found_user = users.query.filter_by(email=email).first()
if (found_user and (bcrypt.checkpw(password.encode('utf8'), found_user.password))):
session['email'] = found_user.email
session['hashed_email'] = hashlib.md5(session['email'].encode('utf-8')).hexdigest()
session['name'] = found_user.name
session['id'] = found_user.id
flash("Login Succesful!")
#onto_len_dir = 0
#onto_list = ''
onto_cont=open("addiction.onto","r").read()
ontoarchive()
onto_len_dir = session['onto_len_dir']
onto_list = session['onto_list']
dict_onto=ast.literal_eval(onto_cont)
return render_template('index.html', onto_len_dir=onto_len_dir, onto_list=onto_list, ontol = 'addiction', dict_onto = dict_onto,version=version())
else:
flash("Invalid username or password!", "inval")
return render_template('signup.html',version=version())
return render_template('signin.html',version=version())
# change password
@app.route("/<nm_passwd>", methods=["POST", "GET"])
def profile(nm_passwd):
try:
if "_" in str(nm_passwd):
user_name = str(nm_passwd).split("_")[0]
user_passwd = str(nm_passwd).split("_")[1]
user_passwd = "b\'"+user_passwd+"\'"
found_user = users.query.filter_by(name=user_name).first()
if request.method == "POST":
password = request.form['password']
session['email'] = found_user.email
session['hashed_email'] = hashlib.md5(session['email'] .encode('utf-8')).hexdigest()
session['name'] = found_user.name
session['id'] = found_user.id
password = bcrypt.hashpw(password.encode('utf8'), bcrypt.gensalt())
found_user.password = password
db.session.commit()
flash("Your password is changed!", "inval")
onto_len_dir = 0
onto_list = ''
onto_cont=open("addiction.onto","r").read()
dict_onto=ast.literal_eval(onto_cont)
return render_template('index.html', onto_len_dir=onto_len_dir, onto_list=onto_list, ontol = 'addiction', dict_onto = dict_onto,version=version())
# remove reserved characters from the hashed passwords
reserved = (";", "/", "?", ":", "@", "=", "&", ".")
def replace_reserved(fullstring):
for replace_str in reserved:
fullstring = fullstring.replace(replace_str,"")
return fullstring
replaced_passwd = replace_reserved(str(found_user.password))
if replaced_passwd == user_passwd:
return render_template("/passwd_change.html", name=user_name,version=version())
else:
return "This url does not exist"
else:
return "This url does not exist"
except (AttributeError):
return "This url does not exist"
@app.route("/logout")
def logout():
onto_len_dir = 0
onto_list = ''
onto_cont=open("addiction.onto","r").read()
dict_onto=ast.literal_eval(onto_cont)
if 'email' in session:
global user1
if session['name'] != '':
user1 = session['name']
else:
user1 = session['email']
flash(f"You have been logged out, {user1}", "inval") # Used f-string for clarity
session.pop('email', None)
session.clear()
return render_template('index.html',onto_len_dir=onto_len_dir, onto_list=onto_list, ontol = 'addiction', dict_onto = dict_onto,version=version())
@app.route("/about")
def about():
return render_template('about.html',version=version())
@app.route("/create-ontology", methods=["GET", "POST"])
def create_ontology():
if request.method == "GET":
session.pop('namecat', None)
from more_functions import gemini_query
default_prompt = (
"Give me a list of terms on substance abuse disorder (SUD) that act "
"as traits and classifiers in scientific literature with a focus on "
"behaviour and brain attributes related to the hippocampus. Avoid "
"aliases and synonyms as well as gene names. Each term should be "
"1-3 words (max). Give me a list of at least 20, but no more than "
"80, most used terms. Return only the terms, one per line, no "
"numbering. Add abbreviations and aliases - each at least 3 letters that have no other meaning - as a list with each term, "
"separated by commas")
if request.method == "POST":
action = request.form.get("action", "generate")
if action == "search":
# Build a temporary .onto file from the result terms and redirect to /progress
result_text = request.form.get("result", "")
query = request.form.get("query", "")
search_types = request.form.getlist("type")
# Build onto dict: each term is its own category with aliases as pipe-separated keywords
dict_onto = {}
for line in result_text.strip().split("\n"):
line = line.strip()
if not line:
continue
parts = [p.strip() for p in line.split(",")]
category = parts[0]
keywords = "|".join(parts)
dict_onto[category] = {category: {keywords}}
# Save to a temp .onto file
onto_path = os.path.join(tempfile.gettempdir(), "gemini_ontology")
with open(onto_path + ".onto", "w") as f:
f.write(repr(dict_onto))
session['namecat'] = onto_path
print(f" Created ontology: {onto_path}.onto with {len(dict_onto)} categories")
print(f" Gene query: '{query}', search_types: {search_types}")
# Build the redirect URL with type and query params
from urllib.parse import urlencode
params = [("query", query)]
for t in search_types:
params.append(("type", t))
return redirect("/progress?" + urlencode(params))
# action == "generate"
prompt = request.form.get("prompt", default_prompt)
try:
result = gemini_query(prompt)
terms = [t.strip() for t in result.strip().split("\n") if t.strip()]
return render_template('create-ontology.html',
prompt=prompt, result=result,
count=len(terms), version=version())
except Exception as e:
return render_template('create-ontology.html',
prompt=prompt, result=f"Error: {e}",
count=0, version=version())
return render_template('create-ontology.html',
prompt=default_prompt, result=None,
count=0, version=version())
# Ontology selection
@app.route("/index_ontology", methods=["POST", "GET"])
def index_ontology():
namecat2 = request.args.get('onto')
session['namecat']=namecat2
if (namecat2 == 'addiction' or namecat2 == 'Select your ontology' ):
session['namecat']='addiction'
onto_cont=open("addiction.onto","r").read()
else:
dirlist = os.listdir(session['user_folder']+"/ontology/")
for filename in dirlist:
onto_name = filename.split('_0_')[1]
if namecat2 == onto_name:
onto_cont = open(session['user_folder']+"/ontology/"+filename+"/"+namecat2+".onto", "r").read()
break
dict_onto=ast.literal_eval(onto_cont)
onto_len_dir = session['onto_len_dir']
onto_list = session['onto_list']
return render_template('index.html',onto_len_dir=onto_len_dir, onto_list=onto_list, ontol = session['namecat'], dict_onto=dict_onto ,version=version())
@app.route("/ontology", methods=["POST", "GET"])
def ontology():
namecat2 = request.args.get('onto')
select_date=request.args.get('selected_date')
namecat_exist=0
if select_date != None:
time_extension = str(select_date)
time_extension = time_extension.split('_0_')[0]
namecat = str(select_date).split('_0_')[1]
time_extension = time_extension.replace(':', '_')
time_extension = time_extension.replace('-', '_')
if ('email' in session):
session['namecat'] = session['user_folder']+"/ontology/"+str(time_extension)+"_0_"+namecat+"/"+namecat
else:
session['namecat']=tempfile.gettempdir()+'/'+namecat
onto_cont = open(session['namecat']+".onto","r").read()
if onto_cont=='':
dict_onto={}
else:
dict_onto=ast.literal_eval(onto_cont)
elif (('email' in session) and (namecat2 == 'addiction')):
namecat='addiction'
session['namecat']=namecat
onto_cont = open("addiction.onto","r").read()
dict_onto=ast.literal_eval(onto_cont)
else:
if (('email' in session) and ((namecat2 != None) and (namecat2 != 'choose your ontology'))):
namecat=namecat2
dirlist = os.listdir(session['user_folder']+"/ontology/")
for filename in dirlist:
onto_name = filename.split('_0_')[1]
if onto_name==namecat:
namecat_exist=1
namecat_filename=filename
break
if namecat_exist==1:
session['namecat'] = session['user_folder']+"/ontology/"+namecat_filename+'/'+namecat
else:
onto_cont = open("addiction.onto","r").read()
dict_onto=ast.literal_eval(onto_cont)
else:
namecat='addiction'
session['namecat']=namecat
onto_cont = open("addiction.onto","r").read()
dict_onto=ast.literal_eval(onto_cont)
if request.method == "POST":
maincat = request.form['maincat']
subcat = request.form['subcat']
keycat = request.form['keycat']
namecat = request.form['namecat']
namecat_exist=0
maincat=re.sub('[^,a-zA-Z0-9 \n]', '', maincat)
subcat=re.sub('[^,a-zA-Z0-9 \n]', '', subcat)
keycat=re.sub('[^,a-zA-Z0-9 \n]', '', keycat)
keycat = keycat.replace(',', '|')
keycat = re.sub("\s+", ' ', keycat)
keycat = keycat.replace(' |', '|')
keycat = keycat.replace('| ', '|')
namecat=re.sub('[^,a-zA-Z0-9 \n]', '', namecat)
# Generate a unique session ID depending on timestamp to track the results
timestamp = datetime.utcnow().replace(microsecond=0)
timestamp = timestamp.replace(tzinfo=pytz.utc)
timestamp = timestamp.astimezone(pytz.timezone("America/Chicago"))
timeextension = str(timestamp)
timeextension = timeextension.replace(':', '_')
timeextension = timeextension.replace('-', '_')
timeextension = timeextension.replace(' ', '_')
timeextension = timeextension.replace('_06_00', '')
session['timeextension'] = timeextension
if request.form['submit'] == 'add': # Add new keywords or create a new ontology
if ('email' in session):
session['namecat']=namecat
if (namecat=='addiction'):
flash("You cannot change addiction keywords but a new ontology will be saved as 'addictionnew', instead","inval")
namecat='addictionnew'
session['namecat']=namecat
session['user_folder'] = datadir+"/user/"+str(session['hashed_email'])
dirlist = os.listdir(session['user_folder']+"/ontology/")
for filename in dirlist:
onto_name = filename.split('_0_')[1]
if onto_name==namecat:
namecat_exist=1 # Add new keywords
namecat_filename=filename
break
if namecat_exist==0: # Create a new ontology folder
os.makedirs(session['user_folder']+"/ontology/"+str(timeextension)+"_0_"+namecat,exist_ok=True)
session['namecat'] = session['user_folder']+"/ontology/"+str(timeextension)+"_0_"+namecat+"/"+namecat
if namecat=='addictionnew':
with open("addiction.onto","r") as f1:
with open(session['namecat']+".onto", "w") as f2:
for line in f1:
f2.write(line)
else:
f= open(session['namecat']+".onto","w")
dict_onto={}
else:
session['namecat'] = session['user_folder']+"/ontology/"+namecat_filename+'/'+namecat
onto_cont=open(session['namecat']+".onto",'r').read()
if onto_cont=='':
dict_onto={}
else:
dict_onto=ast.literal_eval(onto_cont)
flag_kw=0
if (',' in maincat) or (',' in subcat):
flash("Only one word can be added to the category and subcategory at a time.","inval")
elif maincat in dict_onto.keys(): # Layer 2, main category
if subcat in dict_onto[maincat].keys(): # Layer 3, keywords shown in results
keycat_ls = keycat.split('|')
for kw in str.split(next(iter(dict_onto[maincat][subcat])), '|'): # Layer 4, synonyms
for keycat_word in keycat_ls:
if kw==keycat_word:
flash("\""+kw+"\" is already in keywords under the subcategory \""+ subcat \
+ "\" that is under the category \""+ maincat+"\"","inval")
flag_kw=1
if flag_kw==0:
dict_onto[maincat][subcat]= '{'+next(iter(dict_onto[maincat][subcat]))+'|'+keycat+'}'
dict_onto=str(dict_onto).replace('\'{','{\'')
dict_onto=str(dict_onto).replace('}\'','\'}')
dict_onto=str(dict_onto).replace('}},','}},\n')
with open(session['namecat']+'.onto', 'w') as file3:
file3.write(str(dict_onto))
else:
dict_onto[maincat][subcat]='{'+subcat+'|'+keycat+'}'
dict_onto=str(dict_onto).replace('\'{','{\'')
dict_onto=str(dict_onto).replace('}\'','\'}')
dict_onto=str(dict_onto).replace('}},','}},\n')
with open(session['namecat']+'.onto', 'w') as file3:
file3.write(str(dict_onto))
else:
dict_onto[maincat]= '{'+subcat+'\': {\''+keycat+'}'+'}'
dict_onto=str(dict_onto).replace('\"{','{\'')
dict_onto=str(dict_onto).replace('}\"','\'}')
dict_onto=str(dict_onto).replace('\'{','{\'')
dict_onto=str(dict_onto).replace('}\'','\'}')
dict_onto=str(dict_onto).replace('}},','}},\n')
with open(session['namecat']+'.onto', 'w') as file3:
file3.write(str(dict_onto))
else:
if namecat=='addiction':
flash("You must login to change the addiction ontology.")
else:
flash("You must login to create a new ontology.")
if request.form['submit'] == 'remove':
if ('email' in session):
session['namecat']=namecat
if (namecat=='addiction'):
flash("You cannot change addiction keywords but a new ontology will be saved as 'addictionnew', instead","inval")
namecat='addictionnew'
session['namecat']=namecat
session['user_folder'] = datadir+"/user/"+str(session['hashed_email'])
dirlist = os.listdir(session['user_folder']+"/ontology/")
for filename in dirlist:
onto_name = filename.split('_0_')[1]
if onto_name==namecat:
namecat_exist=1
namecat_filename=filename
break
if namecat_exist==0:
os.makedirs(session['user_folder']+"/ontology/"+str(timeextension)+"_0_"+namecat,exist_ok=True)
session['namecat'] = session['user_folder']+"/ontology/"+str(timeextension)+"_0_"+namecat+"/"+namecat
if namecat=='addictionnew':
with open("addiction.onto","r") as f1:
with open(session['namecat']+".onto", "w") as f2:
for line in f1:
f2.write(line)
else:
f= open(session['namecat']+".onto","w")
dict_onto={}
else:
session['namecat'] = session['user_folder']+"/ontology/"+namecat_filename+'/'+namecat
onto_cont=open(session['namecat']+".onto",'r').read()
if onto_cont=='':
dict_onto={}
else:
dict_onto=ast.literal_eval(onto_cont)
flag_kw=0
if maincat in dict_onto.keys(): # Layer 2, main category
if subcat in dict_onto[maincat].keys(): # Layer 3, keywords shown in results
for kw in str.split(next(iter(dict_onto[maincat][subcat])), '|'):
keycat_ls = keycat.split('|')
for keycat_word in keycat_ls: # Layer 4, synonyms
if kw==keycat_word:
dict_onto[maincat][subcat]=re.sub(r'\|'+keycat_word+'\'', '\'', str(dict_onto[maincat][subcat]))
dict_onto[maincat][subcat]=re.sub(r'\''+keycat_word+'\|', '\'', str(dict_onto[maincat][subcat]))
dict_onto[maincat][subcat]=re.sub(r'\|'+keycat_word+'\|', '|', str(dict_onto[maincat][subcat]))
dict_onto[maincat][subcat]=re.sub(r'\''+keycat_word+'\'', '', str(dict_onto[maincat][subcat]))
flag_kw=1
if '{}' in dict_onto[maincat][subcat]:
dict_onto[maincat]=re.sub(r', \''+subcat+'\': \'{}\' ', '', str(dict_onto[maincat]))
dict_onto[maincat]=re.sub(r'\''+subcat+'\': \'{}\', ', '', str(dict_onto[maincat]))
dict_onto[maincat]=re.sub(r'\''+subcat+'\': \'{}\'', '', str(dict_onto[maincat]))
if '{}' in dict_onto[maincat]:
dict_onto=re.sub(r', \''+maincat+'\': \'{}\'', '', str(dict_onto))
dict_onto=str(dict_onto).replace('\"{','{')
dict_onto=str(dict_onto).replace('}\"','}')
dict_onto=str(dict_onto).replace('\'{','{')
dict_onto=str(dict_onto).replace('}\'','}')
with open(session['namecat']+'.onto', 'w') as file3:
file3.write(str(dict_onto))
if flag_kw==0:
flash("\""+keycat+"\" is not a keyword.","inval")
else:
flash("\""+subcat+"\" is not a subcategory.","inval")
else:
flash("\""+subcat+"\" is not a category.","inval")
else:
if namecat=='addiction':
flash("You must login to change the addiction ontology.")
else:
flash("You must login to create a new ontology.")
if 'namecat' in session:
file2 = open(session['namecat']+".onto","r")
onto_cont=file2.read()
if onto_cont=='':
dict_onto={}
else:
dict_onto=ast.literal_eval(onto_cont)
else:
session['namecat']='addiction'
file2 = open(session['namecat']+".onto","r")
onto_cont=file2.read()
dict_onto=ast.literal_eval(onto_cont)
name_to_html = str(session['namecat']).split('/')[-1]
if ('email' in session):
ontoarchive()
onto_len_dir = session['onto_len_dir']
onto_list = session['onto_list']
else:
onto_len_dir=0
onto_list=''
return render_template('ontology.html',dict_onto=dict_onto, namecat=name_to_html, onto_len_dir=onto_len_dir, onto_list=onto_list,no_footer=True,version=version())
@app.route("/ontoarchive")
def ontoarchive():
session['onto_len_dir'] = 0
session['onto_list'] = ''
if ('email' in session):
if os.path.exists(datadir+"/user/"+str(session['hashed_email'])+"/ontology") == False:
flash("Ontology history doesn't exist!")
onto_len_dir = 0
onto_list = ''
onto_cont=open("addiction.onto","r").read()
dict_onto=ast.literal_eval(onto_cont)
return render_template('index.html',onto_len_dir=onto_len_dir, onto_list=onto_list, ontol = 'addiction', dict_onto = dict_onto,version=version())
else:
session['user_folder'] = datadir+"/user/"+str(session['hashed_email'])
else:
flash("You logged out!")
onto_len_dir = 0
onto_list = ''
onto_cont=open("addiction.onto","r").read()
dict_onto=ast.literal_eval(onto_cont)
return render_template('index.html', onto_len_dir=onto_len_dir, onto_list=onto_list, ontol = 'addiction', dict_onto = dict_onto,version=version())
session_id=session['id']
def sorted_alphanumeric(data):
convert = lambda text: int(text) if text.isdigit() else text.lower()
alphanum_key = lambda key: [ convert(c) for c in re.split('([0-9]+)', key) ]
return sorted(data, key=alphanum_key)
dirlist = sorted_alphanumeric(os.listdir(session['user_folder']+"/ontology/"))
onto_folder_list = []
onto_directory_list = []
onto_list=[]
for filename in dirlist:
onto_folder_list.append(filename)
onto_name = filename.split('_0_')[1]
onto_name = onto_name.replace('_', ', ')
onto_list.append(onto_name)
onto_name=""
filename=filename[0:4]+"-"+filename[5:7]+"-"+filename[8:13]+":"+filename[14:16]+":"+filename[17:19]
onto_directory_list.append(filename)
onto_len_dir = len(onto_directory_list)
session['onto_len_dir'] = onto_len_dir
session['onto_list'] = onto_list
message3="<ul><li> Click on the Date/Time to view archived results. <li>The Date/Time are based on US Central time zone.</ul> "
return render_template('ontoarchive.html', onto_len_dir=onto_len_dir, onto_list = onto_list, onto_folder_list=onto_folder_list, onto_directory_list=onto_directory_list, session_id=session_id, message3=message3,version=version())
# Remove an ontology folder
@app.route('/removeonto', methods=['GET', 'POST'])
def removeonto():
if('email' in session):
remove_folder = request.args.get('remove_folder')
shutil.rmtree(datadir+"/user/"+str(session['hashed_email']+"/ontology/"+remove_folder), ignore_errors=True)
return redirect(url_for('ontoarchive'))
else:
flash("You logged out!")
onto_len_dir = 0
onto_list = ''
onto_cont=open("addiction.onto","r").read()
dict_onto=ast.literal_eval(onto_cont)
return render_template('index.html', onto_len_dir=onto_len_dir, onto_list=onto_list, ontol = 'addiction', dict_onto = dict_onto,version=version())
@app.route('/progress')
def progress():
genes=request.args.get('query')
genes=genes.replace(",", " ")
genes=genes.replace(";", " ")
genes=re.sub(r'\bLOC\d*?\b', "", genes, flags=re.I)
genes=genes.replace(" \'", " \"")
genes=genes.replace("\' ", "\" ")
genes=genes.replace("\'", "-")
genes1 = [f[1:-1] for f in re.findall('".+?"', genes)]
genes2 = [p for p in re.findall(r'([^""]+)',genes) if p not in genes1]
genes2_str = ''.join(genes2)
genes2 = genes2_str.split()
genes3 = genes1 + genes2
genes = [re.sub("\s+", '-', s) for s in genes3]
# Only 1-200 terms are allowed
if len(genes)>=200:
if ('email' in session):
onto_len_dir = session['onto_len_dir']
onto_list = session['onto_list']
else:
onto_len_dir = 0
onto_list = ''
onto_cont=open("addiction.onto","r").read()
dict_onto=ast.literal_eval(onto_cont)
message="<span class='text-danger'>Up to 200 terms can be searched at a time</span>"
return render_template('index.html' ,onto_len_dir=onto_len_dir, onto_list=onto_list, ontol = 'addiction', dict_onto = dict_onto, message=message,version=version())
if len(genes)==0:
if ('email' in session):
onto_len_dir = session['onto_len_dir']
onto_list = session['onto_list']
else:
onto_len_dir = 0
onto_list = ''
onto_cont=open("addiction.onto","r").read()
dict_onto=ast.literal_eval(onto_cont)
message="<span class='text-danger'>Please enter a search term </span>"
return render_template('index.html',onto_len_dir=onto_len_dir, onto_list=onto_list, ontol = 'addiction', dict_onto = dict_onto, message=message,version=version())
tf_path=tempfile.gettempdir()
genes_for_folder_name =""
if len(genes) == 1:
marker = ""
genes_for_folder_name =str(genes[0])
elif len(genes) == 2:
marker = ""
genes_for_folder_name =str(genes[0])+"_"+str(genes[1])
elif len(genes) == 3:
marker = ""
genes_for_folder_name =str(genes[0])+"_"+str(genes[1])+"_"+str(genes[2])
else:
genes_for_folder_name =str(genes[0])+"_"+str(genes[1])+"_"+str(genes[2])
marker="_m"
# Generate a unique session ID depending on timestamp to track the results
timestamp = datetime.utcnow().replace(microsecond=0)
timestamp = timestamp.replace(tzinfo=pytz.utc)
timestamp = timestamp.astimezone(pytz.timezone("America/Chicago"))
timeextension = str(timestamp)
timeextension = timeextension.replace(':', '_')
timeextension = timeextension.replace('-', '_')
timeextension = timeextension.replace(' ', '_')
timeextension = timeextension.replace('_06_00', '')
session['timeextension'] = timeextension
namecat_exist=0
# Create a folder for the search
if ('email' in session):
try:
namecat=session['namecat']
except:
namecat = 'addiction'
session['namecat'] = namecat
if namecat=='choose your ontology' or namecat=='addiction' or namecat == 'addiction': # Redundant 'addiction' check
session['namecat']='addiction'
onto_cont=open("addiction.onto","r").read()
# dictionary=ast.literal_eval(onto_cont) # dictionary is global, no need to re-assign from local onto_cont
search_type = request.args.getlist('type')
if (search_type == []):
search_type = ['GWAS', 'function', 'addiction', 'drug', 'brain', 'stress', 'psychiatric', 'cell']
session['search_type'] = search_type
else:
dirlist = os.listdir(session['user_folder']+"/ontology/")
for filename in dirlist:
onto_name = filename.split('_0_')[1]
if onto_name==namecat:
namecat_exist=1
namecat_filename=filename
break
if (namecat_exist==1):
session['namecat'] = session['user_folder']+"/ontology/"+namecat_filename+'/'+namecat
onto_cont=open(session['namecat']+".onto","r").read()
dict_onto=ast.literal_eval(onto_cont)
search_type = request.args.getlist('type')
if (search_type == []):
search_type = list(dict_onto.keys())
session['search_type'] = search_type
# Save the ontology name in the user search history table
if session['namecat']=='addiction':
onto_name_archive = session['namecat']
elif ('/' in session['namecat']):
onto_name_archive = session['namecat'].split('/')[-1]
else:
onto_name_archive = '-'
os.makedirs(datadir + "/user/"+str(session['hashed_email'])+"/"+str(timeextension)+"_0_"+genes_for_folder_name+marker+"_0_"+onto_name_archive,exist_ok=True)
session['path_user'] = datadir+"/user/"+str(session['hashed_email'])+"/"+str(timeextension)+"_0_"+genes_for_folder_name+marker+"_0_"+onto_name_archive+"/"
session['rnd'] = timeextension+"_0_"+genes_for_folder_name+marker+"_0_"+onto_name_archive
rnd = session['rnd']
else:
rnd = "tmp" + ''.join(random.choice(string.ascii_letters) for x in range(6))
session['path']=tf_path+ "/" + rnd
os.makedirs(session['path'])
search_type = request.args.getlist('type')
if (search_type == []):
search_type = ['GWAS', 'function', 'addiction', 'drug', 'brain', 'stress', 'psychiatric', 'cell']
session['search_type'] = search_type
# Use default addiction ontology unless redirected from /create-ontology
if request.referrer and '/create-ontology' in request.referrer:
pass # keep session['namecat'] set by /create-ontology
elif 'namecat' in session:
del session['namecat']
genes_session = ''
for gen in genes:
genes_session += str(gen) + "_"
genes_session = genes_session[:-1]
session['query']=genes
return render_template('progress.html', url_in="search", url_out="cytoscape/?rnd="+rnd+"&genequery="+genes_session,version=version())
@app.route("/search")
def search():
genes=session['query']
percent_ratio=len(genes)+1
if(len(genes)==1):
percent_ratio=2
timeextension=session['timeextension']
percent=100/percent_ratio-0.00000001 # 7 categories + 1 at the beginning
if ('email' in session):
sessionpath = session['path_user'] + timeextension
path_user=session['path_user']
else:
sessionpath = session['path']
path_user=session['path']+"/"
snt_file=sessionpath+"_snt"
cysdata=open(sessionpath+"_cy","w+")
sntdata=open(snt_file,"w+")
zeroLinkNode=open(sessionpath+"_0link","w+")
search_type = session['search_type']
temp_nodes = ""
json_nodes = "{\"data\":["
n_num=0
d={}
nodecolor={}
nodecolor['GWAS'] = "hsl(0, 0%, 70%)"
nodes_list = []
if 'namecat' in session:
namecat_flag=1
ses_namecat = session['namecat']
print(f" /search: namecat={ses_namecat}, search_type={search_type}")
onto_cont = open(session['namecat']+".onto","r").read()
dict_onto=ast.literal_eval(onto_cont)
print(f" /search: onto categories={list(dict_onto.keys())[:10]}")
for ky in dict_onto.keys():
nodecolor[ky] = "hsl("+str((n_num+1)*int(360/len(dict_onto.keys())))+", 70%, 80%)"
d["nj{0}".format(n_num)]=generate_nodes_json(dict_onto[ky],str(ky),nodecolor[ky])
n_num+=1
if (ky in search_type):
temp_nodes += generate_nodes(dict_onto[ky],str(ky),nodecolor[ky])
for nd in dict_onto[ky]:
nodes_list.append(nd)
json_nodes += generate_nodes_json(dict_onto[ky],str(ky),nodecolor[ky] )
d["nj{0}".format(n_num)]=''
else:
namecat_flag=0
for ky in dictionary.keys(): # Using global 'dictionary'
nodecolor[ky] = "hsl("+str((n_num+1)*int(360/len(dictionary.keys())))+", 70%, 80%)"
d["nj{0}".format(n_num)]=generate_nodes_json(dictionary[ky],str(ky),nodecolor[ky])
n_num+=1
if (ky in search_type):
temp_nodes += generate_nodes(dictionary[ky],str(ky),nodecolor[ky])
for nd in dictionary[ky]:
nodes_list.append(nd)
json_nodes += generate_nodes_json(dictionary[ky],str(ky),nodecolor[ky])
d["nj{0}".format(n_num)]=''
json_nodes = json_nodes[:-2] # Handles case if json_nodes was only "{\"data\":["
if json_nodes == "{\"data\"": # if it was empty before -2
json_nodes = "{\"data\":[]}"
else:
json_nodes =json_nodes+"]}"
def generate(genes, tf_name): # tf_name is snt_file
with app.test_request_context():
from nltk.tokenize import sent_tokenize # Moved import here, as it's only used in this function scope.
sentences=str()
edges=str()
nodes = temp_nodes
progress=0
searchCnt=0
nodesToHide=str()
json_edges = str()
#genes_or = ' [tiab] or '.join(genes)
all_d=''
current_dict_onto = {} # To hold the relevant ontology for this search pass
if namecat_flag==1:
onto_cont_local = open(ses_namecat+".onto","r").read() # ses_namecat from outer scope
current_dict_onto=ast.literal_eval(onto_cont_local)
else:
current_dict_onto = dictionary # Use global dictionary
for ky in current_dict_onto.keys():
if (ky in search_type):
all_d_ls=undic(list(current_dict_onto[ky].values()))
all_d = all_d+'|'+all_d_ls
if all_d: # Check if all_d is not empty
all_d=all_d[1:]
print(f" /search generate: all_d={all_d[:200] if all_d else '(empty)'}, search_type={search_type}")
if ("GWAS" in search_type):
datf = pd.read_csv('./utility/gwas_used.csv',sep='\t')
progress+=percent
yield "data:"+str(progress)+"\n\n"
# Batch fetch all abstracts in a single PubMed query
print(f"Batch fetching abstracts for {len(genes)} genes")
all_abstracts_raw = getabstracts_batch(genes, all_d) if all_d else ""
# Parse all sentences once
all_sentences = []
for row in all_abstracts_raw.split("\n"):
if not row.strip(): continue
tiab = row.split("\t")
pmid = tiab.pop(0)
tiab_text = " ".join(tiab)
for sent_tok in sent_tokenize(tiab_text):
all_sentences.append(pmid + ' ' + sent_tok)
for gene in genes:
gene = gene.replace("-", " ")