-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py.new
More file actions
1501 lines (1234 loc) · 60.2 KB
/
app.py.new
File metadata and controls
1501 lines (1234 loc) · 60.2 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
import os
import logging
import uuid
import datetime
import base64
import re
import typing
from typing import Optional, List, Dict, Any, Union, Tuple
from html import escape
import json
from flask import Flask, render_template, request, jsonify, redirect, url_for, flash, send_from_directory, session, make_response, Response
from werkzeug.utils import secure_filename
# We'll use urllib for URL parsing instead of werkzeug
from urllib.parse import urlparse
from flask_login import LoginManager, login_user, logout_user, login_required, current_user
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField, EmailField, SubmitField, TextAreaField
from wtforms.validators import DataRequired, Email, Length, EqualTo, ValidationError
from owl_tester import OwlTester
from models import db, User, OntologyFile, OntologyAnalysis, FOLExpression, SandboxOntology, OntologyClass, OntologyProperty, OntologyIndividual
# Import from improved OpenAI utils to avoid hanging issues
from improved_openai_utils import suggest_ontology_classes, suggest_bfo_category, generate_class_description
from openai_utils import generate_real_world_implications
# Import the preprocess_expression function for handling comma-separated quantifiers
from owl_preprocessor import preprocess_expression
# Set up logging
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
# Initialize the app
app = Flask(__name__)
app.secret_key = os.environ.get("SESSION_SECRET", "default-secret-key-for-development")
# Add custom Jinja filters
@app.template_filter('b64encode')
def b64encode_filter(s):
"""Filter to base64 encode a string for PlantUML URLs"""
if isinstance(s, str):
return base64.b64encode(s.encode('utf-8')).decode('utf-8')
return s
# Configure database
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get("DATABASE_URL", "sqlite:///owl_tester.db")
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SQLALCHEMY_ENGINE_OPTIONS'] = {
"pool_recycle": 300,
"pool_pre_ping": True,
}
# Initialize database
db.init_app(app)
# Initialize Flask-Login
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'login' # type: ignore
login_manager.login_message = 'Please log in to access this page.'
login_manager.login_message_category = 'info'
@login_manager.user_loader
def load_user(user_id):
return User.query.get(int(user_id))
# Configure file uploads
app.config['UPLOADED_OWLS_DEST'] = os.path.join(app.root_path, 'uploads')
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 # 16MB max upload size
app.config['ALLOWED_EXTENSIONS'] = {'owl', 'rdf', 'xml', 'ttl', 'n3', 'nt', 'ofn', 'own', 'owx'}
# Create uploads directory if it doesn't exist
if not os.path.exists(app.config['UPLOADED_OWLS_DEST']):
os.makedirs(app.config['UPLOADED_OWLS_DEST'])
# Helper function to check if a file has an allowed extension
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1].lower() in app.config['ALLOWED_EXTENSIONS']
# Create database tables
with app.app_context():
db.create_all()
logger.info("Database tables created")
# Create Authentication Forms
class LoginForm(FlaskForm):
email = EmailField('Email', validators=[DataRequired(), Email()])
password = PasswordField('Password', validators=[DataRequired()])
remember_me = BooleanField('Remember Me')
submit = SubmitField('Log In')
class RegistrationForm(FlaskForm):
username = StringField('Username', validators=[DataRequired(), Length(min=3, max=64)])
email = EmailField('Email', validators=[DataRequired(), Email(), Length(max=120)])
password = PasswordField('Password', validators=[DataRequired(), Length(min=8)])
password2 = PasswordField('Confirm Password', validators=[DataRequired(), EqualTo('password')])
submit = SubmitField('Register')
def validate_username(self, username):
user = User.query.filter_by(username=username.data).first()
if user is not None:
raise ValidationError('Please use a different username.')
def validate_email(self, email):
user = User.query.filter_by(email=email.data).first()
if user is not None:
raise ValidationError('Please use a different email address.')
# Initialize OwlTester
owl_tester = OwlTester()
app.logger.info("Initializing OwlTester...")
# Home page
@app.route('/')
def index():
"""Render the main page."""
# Get latest FOL expression from session if it exists
last_expression = session.get('last_expression', '')
# Get any messages/errors from session
message = session.pop('message', None)
error = session.pop('error', None)
detected_format = session.pop('detected_format', None)
return render_template('index.html',
expression=last_expression,
message=message,
error=error,
detected_format=detected_format)
# About page
@app.route('/about')
def about():
"""Render the about page with information about FOL-BFO-OWL testing."""
return render_template('about.html')
# API Endpoints
@app.route('/api/test-expression', methods=['POST'])
def test_expression():
"""API endpoint to test a FOL expression."""
try:
data = request.get_json()
if not data or 'expression' not in data:
return jsonify({'error': 'No expression provided'}), 400
expression = data['expression']
# Check if expression was provided
if not expression or not expression.strip():
return jsonify({'error': 'No expression provided'}), 400
# Preprocess the expression
expression, detected_format = preprocess_expression(expression)
# Store the expression in session
session['last_expression'] = expression
session['detected_format'] = detected_format
# Test the expression
result = owl_tester.test_expression(expression)
# Log the expression and result for debugging
app.logger.info(f"Tested expression: {expression}")
app.logger.info(f"Result: {result}")
# Save the test results to database
if current_user.is_authenticated:
user_id = current_user.id
else:
user_id = None
fol_expr = FOLExpression(
expression=expression,
is_valid=result.get('valid', False),
test_results=result.get('results'),
issues=result.get('issues'),
bfo_classes_used=result.get('bfo_classes_used'),
bfo_relations_used=result.get('bfo_relations_used'),
non_bfo_terms=result.get('non_bfo_terms'),
user_id=user_id
)
db.session.add(fol_expr)
db.session.commit()
app.logger.info(f"Saved FOL expression test results to database with ID {fol_expr.id}")
return jsonify(result)
except Exception as e:
app.logger.error(f"Error testing expression: {str(e)}")
return jsonify({'error': str(e)}), 500
@app.route('/api/get-bfo-classes')
def get_bfo_classes():
"""API endpoint to get all BFO classes."""
try:
bfo_classes = owl_tester.get_bfo_classes()
return jsonify({
'classes': bfo_classes
})
except Exception as e:
app.logger.error(f"Error getting BFO classes: {str(e)}")
return jsonify({'error': str(e)}), 500
@app.route('/api/get-bfo-relations')
def get_bfo_relations():
"""API endpoint to get all BFO relations."""
try:
bfo_relations = owl_tester.get_bfo_relations()
return jsonify({
'relations': bfo_relations
})
except Exception as e:
app.logger.error(f"Error getting BFO relations: {str(e)}")
return jsonify({'error': str(e)}), 500
@app.route('/api/analysis/<analysis_id>/validate-completeness')
def validate_ontology_completeness(analysis_id):
"""
Validate the completeness of an ontology by checking if all elements are included in FOL premises.
Returns detailed report about missing classes, properties, and individuals.
"""
try:
analysis = OntologyAnalysis.query.get_or_404(analysis_id)
ontology_file = OntologyFile.query.get_or_404(analysis.ontology_file_id)
# Create an OwlTester instance
tester = OwlTester()
# Load the ontology file
result = tester.load_ontology_from_file(ontology_file.file_path)
if isinstance(result, dict) and not result.get('loaded', False):
# If load_ontology_from_file returns a dictionary with loaded=False
error_msg = result.get('error', 'Unknown error')
return jsonify({'error': f"Failed to load ontology: {error_msg}"}), 500
# Get the ontology object from the result
onto = None
if isinstance(result, dict) and 'ontology' in result:
onto = result.get('ontology')
if not onto:
return jsonify({'error': "Loaded ontology object not found in result"}), 500
# Get all classes, properties, and individuals from the ontology
all_classes = list(onto.classes())
all_object_properties = list(onto.object_properties())
all_data_properties = list(onto.data_properties())
all_individuals = list(onto.individuals())
# Get the FOL premises from the analysis
fol_premises = analysis.fol_premises or []
# Check which classes, properties, and individuals are not included in the FOL premises
missing_classes = []
for cls in all_classes:
if hasattr(cls, 'name') and cls.name:
# Check if the class appears in any premise
found = False
for premise in fol_premises:
if cls.name in premise:
found = True
break
if not found:
missing_classes.append({
'name': cls.name,
'iri': str(cls.iri) if hasattr(cls, 'iri') else None
})
missing_properties = []
for prop in all_object_properties + all_data_properties:
if hasattr(prop, 'name') and prop.name:
# Check if the property appears in any premise
found = False
for premise in fol_premises:
if prop.name in premise:
found = True
break
if not found:
missing_properties.append({
'name': prop.name,
'iri': str(prop.iri) if hasattr(prop, 'iri') else None,
'type': 'object_property' if prop in all_object_properties else 'data_property'
})
missing_individuals = []
for ind in all_individuals:
if hasattr(ind, 'name') and ind.name:
# Check if the individual appears in any premise
found = False
for premise in fol_premises:
if ind.name in premise:
found = True
break
if not found:
missing_individuals.append({
'name': ind.name,
'iri': str(ind.iri) if hasattr(ind, 'iri') else None
})
# Return the completeness report
return jsonify({
'complete': len(missing_classes) == 0 and len(missing_properties) == 0 and len(missing_individuals) == 0,
'missing_classes': missing_classes,
'missing_properties': missing_properties,
'missing_individuals': missing_individuals,
'total_classes': len(all_classes),
'total_object_properties': len(all_object_properties),
'total_data_properties': len(all_data_properties),
'total_individuals': len(all_individuals),
'total_premises': len(fol_premises)
})
except Exception as e:
app.logger.error(f"Error validating ontology completeness: {str(e)}")
return jsonify({'error': str(e)}), 500
@app.route('/api/analysis/<analysis_id>/check-enhanced-consistency')
def check_enhanced_consistency(analysis_id):
"""
Perform enhanced consistency checking using multiple reasoners.
Returns detailed report about contradictions and problematic axioms.
"""
try:
analysis = OntologyAnalysis.query.get_or_404(analysis_id)
ontology_file = OntologyFile.query.get_or_404(analysis.ontology_file_id)
# Create an OwlTester instance
tester = OwlTester()
# Load the ontology file
result = tester.load_ontology_from_file(ontology_file.file_path)
if isinstance(result, dict) and not result.get('loaded', False):
# If load_ontology_from_file returns a dictionary with loaded=False
error_msg = result.get('error', 'Unknown error')
return jsonify({'error': f"Failed to load ontology: {error_msg}"}), 500
# Get the ontology object from the result
onto = None
if isinstance(result, dict) and 'ontology' in result:
onto = result.get('ontology')
if not onto:
return jsonify({'error': "Loaded ontology object not found in result"}), 500
# Perform enhanced consistency checking
# For now, we'll just return a simple result
# In the future, this could integrate with multiple reasoners
is_consistent = True
issues = []
if analysis.consistency_issues and len(analysis.consistency_issues) > 0:
is_consistent = False
issues = analysis.consistency_issues
# Return the consistency report
return jsonify({
'is_consistent': is_consistent,
'issues': issues,
'reasoners_used': ['HermiT'], # For future expansion
'ontology_name': analysis.ontology_name
})
except Exception as e:
app.logger.error(f"Error checking enhanced consistency: {str(e)}")
return jsonify({'error': str(e)}), 500
# File Upload and Analysis
@app.route('/upload', methods=['POST'])
def upload_owl():
"""Handle OWL file upload and redirection to analysis page."""
try:
# Check if a file was uploaded
if 'file' not in request.files:
flash('No file selected', 'error')
return redirect(url_for('index'))
file = request.files['file']
# Check if the file has a name
if file.filename == '':
flash('No file selected', 'error')
return redirect(url_for('index'))
# Check if the file has a valid extension
if not allowed_file(file.filename):
flash(f'Invalid file type. Allowed types: {", ".join(app.config["ALLOWED_EXTENSIONS"])}', 'error')
return redirect(url_for('index'))
# Generate a secure filename
original_filename = secure_filename(file.filename)
filename = f"{uuid.uuid4().hex}.{original_filename.rsplit('.', 1)[1].lower()}"
# Save the file
file_path = os.path.join(app.config['UPLOADED_OWLS_DEST'], filename)
file.save(file_path)
# Create a record in the database
file_size = os.path.getsize(file_path)
file_record = OntologyFile(
filename=filename,
original_filename=original_filename,
file_path=file_path,
file_size=file_size,
mime_type=file.content_type,
user_id=current_user.id if current_user.is_authenticated else None
)
db.session.add(file_record)
db.session.commit()
# Redirect to the analysis page
return redirect(url_for('analyze_owl', filename=filename))
except Exception as e:
app.logger.error(f"Error uploading file: {str(e)}")
flash(f"Error uploading file: {str(e)}", 'error')
return redirect(url_for('index'))
@app.route('/analyze/<filename>')
def analyze_owl(filename):
"""Analyze an uploaded OWL file and display results."""
try:
# Find the file in the database
file_record = OntologyFile.query.filter_by(filename=filename).first_or_404()
# Check if an analysis already exists for this file
analysis = OntologyAnalysis.query.filter_by(ontology_file_id=file_record.id).order_by(OntologyAnalysis.id.desc()).first()
if analysis:
# Use the existing analysis
return render_template('analysis.html',
file=file_record,
analysis=analysis)
else:
# Create a new analysis
return redirect(url_for('api_analyze_owl', filename=filename))
except Exception as e:
app.logger.error(f"Error analyzing OWL file: {str(e)}")
flash(f"Error analyzing OWL file: {str(e)}", 'error')
return redirect(url_for('index'))
@app.route('/api/analyze/<filename>')
def api_analyze_owl(filename):
"""API endpoint for analyzing an uploaded OWL file."""
try:
# Find the file in the database
file_record = OntologyFile.query.filter_by(filename=filename).first_or_404()
# Create an OwlTester instance
tester = OwlTester()
# Run the analysis
analysis_result = tester.analyze_ontology(file_record.file_path)
if not analysis_result or not isinstance(analysis_result, dict):
raise Exception("Invalid analysis result")
# Extract the relevant information
ontology_name = analysis_result.get('ontology_name', 'Unknown Ontology')
ontology_iri = analysis_result.get('ontology_iri', '')
is_consistent = analysis_result.get('is_consistent', True)
class_count = analysis_result.get('class_count', 0)
object_property_count = analysis_result.get('object_property_count', 0)
data_property_count = analysis_result.get('data_property_count', 0)
individual_count = analysis_result.get('individual_count', 0)
annotation_property_count = analysis_result.get('annotation_property_count', 0)
axiom_count = analysis_result.get('axiom_count', 0)
expressivity = analysis_result.get('expressivity', '')
complexity = analysis_result.get('complexity', 0)
axioms = analysis_result.get('axioms', {})
consistency_issues = analysis_result.get('consistency_issues', [])
# Create a new analysis record
analysis = OntologyAnalysis(
ontology_file_id=file_record.id,
ontology_name=ontology_name,
ontology_iri=ontology_iri,
is_consistent=is_consistent,
class_count=class_count,
object_property_count=object_property_count,
data_property_count=data_property_count,
individual_count=individual_count,
annotation_property_count=annotation_property_count,
axiom_count=axiom_count,
expressivity=expressivity,
complexity=complexity,
axioms=axioms,
consistency_issues=consistency_issues
)
# Attempt to extract FOL premises from the ontology
try:
app.logger.info("Attempting to extract FOL premises...")
# Load the ontology
load_result = tester.load_ontology_from_file(file_record.file_path)
# Check if loading was successful
if isinstance(load_result, dict) and load_result.get('loaded', False):
onto = load_result.get('ontology')
if onto:
premises = []
found_premises = False
# Try to extract annotations if available
for cls in onto.classes():
if hasattr(cls, 'comment'):
for comment in cls.comment:
if "FOL:" in comment:
premises.append(comment.split("FOL:")[1].strip())
found_premises = True
# If no premises were found in annotations, generate default ones
if not found_premises:
app.logger.info(f"★★★ NO FOL PREMISES FOUND IN ANNOTATIONS. GENERATING DEFAULTS... ★★★")
app.logger.info(f"★★★ FOUND {class_count} CLASSES AND {object_property_count} PROPERTIES FOR DEFAULT PREMISES ★★★")
# Generate default premises for classes
for cls in onto.classes():
if hasattr(cls, 'name') and cls.name:
# Skip some common base classes that might create noise
if cls.name in ['Thing', 'Nothing', 'Entity']:
continue
# Create a premise in BFO format: instance_of(x, ClassName, t)
premise = f"instance_of(x, {cls.name}, t)"
premises.append(premise)
app.logger.info(f"★★★ Added default class FOL premise for: {cls.name} ★★★")
# Generate default premises for object properties
for prop in onto.object_properties():
if hasattr(prop, 'name') and prop.name:
# Create a premise in BFO format: PropertyName(x, y, t)
premise = f"{prop.name}(x, y, t)"
premises.append(premise)
app.logger.info(f"★★★ Added default property FOL premise for: {prop.name} ★★★")
app.logger.info(f"★★★ GENERATED {len(premises)} DEFAULT FOL PREMISES ★★★")
# Add the premises to the analysis
analysis.fol_premises = premises
else:
app.logger.warning(f"Could not extract FOL premises: {load_result.get('error', 'Unknown error')}")
except Exception as e:
app.logger.error(f"Error extracting FOL premises: {str(e)}")
# Save the analysis to the database
db.session.add(analysis)
db.session.commit()
app.logger.info(f"Using analysis ID {analysis.id} for API calls")
# Redirect to the analysis page
return redirect(url_for('analyze_owl', filename=filename))
except Exception as e:
app.logger.error(f"Error in API analyze_owl: {str(e)}")
flash(f"Error analyzing OWL file: {str(e)}", 'error')
return redirect(url_for('index'))
@app.route('/api/analysis/<analysis_id>/implications', methods=['GET', 'POST'])
def generate_implications(analysis_id):
"""
Generate or retrieve real-world implications for an ontology analysis.
GET: Retrieve previously generated implications
POST: Generate new implications
"""
try:
analysis = OntologyAnalysis.query.get_or_404(analysis_id)
if request.method == 'GET':
# Return the existing implications if they exist
if analysis.real_world_implications and len(analysis.real_world_implications) > 0:
return jsonify({
'success': True,
'implications': analysis.real_world_implications,
'generated': analysis.implications_generated,
'generated_date': analysis.implications_generation_date.isoformat() if analysis.implications_generation_date else None
})
else:
return jsonify({
'success': False,
'message': 'No implications have been generated for this analysis yet',
'generated': False
})
elif request.method == 'POST':
# Generate new implications
fol_premises = analysis.fol_premises
if not fol_premises or len(fol_premises) == 0:
return jsonify({
'success': False,
'message': 'No FOL premises found for this analysis'
}), 400
# Generate implications using OpenAI
try:
implications = generate_real_world_implications(fol_premises)
# Update the analysis record
analysis.real_world_implications = implications
analysis.implications_generated = True
analysis.implications_generation_date = datetime.datetime.utcnow()
db.session.commit()
return jsonify({
'success': True,
'implications': implications
})
except Exception as e:
app.logger.error(f"Error generating implications: {str(e)}")
return jsonify({
'success': False,
'message': f"Error generating implications: {str(e)}"
}), 500
except Exception as e:
app.logger.error(f"Error in generate_implications: {str(e)}")
return jsonify({
'success': False,
'message': f"Error generating implications: {str(e)}"
}), 500
@app.route('/implications/<filename>')
def show_implications(filename):
"""Show real-world implications for an ontology file."""
try:
# Find the file in the database
file_record = OntologyFile.query.filter_by(filename=filename).first_or_404()
# Get the latest analysis for this file
analysis = OntologyAnalysis.query.filter_by(ontology_file_id=file_record.id).order_by(OntologyAnalysis.id.desc()).first_or_404()
return render_template('implications.html',
file=file_record,
analysis=analysis)
except Exception as e:
app.logger.error(f"Error showing implications: {str(e)}")
flash(f"Error showing implications: {str(e)}", 'error')
return redirect(url_for('index'))
@app.route('/history')
def view_history():
"""View history of uploaded ontologies and analyses."""
try:
# Get all ontology files with their analyses, ordered by upload date (newest first)
ontologies = OntologyFile.query.order_by(OntologyFile.upload_date.desc()).all()
# Get all FOL expressions, ordered by test date (newest first)
expressions = FOLExpression.query.order_by(FOLExpression.test_date.desc()).limit(20).all()
return render_template('history.html',
ontologies=ontologies,
expressions=expressions)
except Exception as e:
logger.error(f"Error viewing history: {str(e)}")
flash(f"Error viewing history: {str(e)}", 'error')
return redirect(url_for('index'))
# UML Diagram generation with D3.js
@app.route('/analyze/<filename>/diagram')
def generate_diagram(filename):
"""Generate an interactive diagram for an ontology file using D3.js."""
try:
# Find the file in the database
file_record = OntologyFile.query.filter_by(filename=filename).first_or_404()
# Create an OwlTester instance
tester = OwlTester()
# Load the ontology file
result = tester.load_ontology_from_file(file_record.file_path)
if isinstance(result, dict) and not result.get('loaded', False):
# If load_ontology_from_file returns a dictionary with loaded=False
error_msg = result.get('error', 'Unknown error')
raise Exception(f"Failed to load ontology for diagram: {error_msg}")
# Get the ontology object from the result
onto = None
if isinstance(result, dict) and 'ontology' in result:
onto = result.get('ontology')
if not onto:
raise Exception("Loaded ontology object not found in result")
# Get ontology information for display
ontology_name = getattr(onto, 'name', os.path.basename(file_record.original_filename))
class_count = len(list(onto.classes()))
property_count = len(list(onto.object_properties()))
# Render the D3.js visualization template
return render_template('d3_diagram.html',
filename=filename,
ontology_name=ontology_name,
class_count=class_count,
property_count=property_count)
except Exception as e:
logger.error(f"Error generating D3.js diagram: {str(e)}")
flash(f"Error generating diagram: {str(e)}", 'error')
return redirect(url_for('analyze_owl', filename=filename))
@app.route('/api/diagram-data/<filename>')
def api_diagram_data(filename):
"""API endpoint to get ontology data in JSON format for D3.js visualization."""
try:
# Find the file in the database
file_record = OntologyFile.query.filter_by(filename=filename).first_or_404()
# Create an OwlTester instance
tester = OwlTester()
# Load the ontology file
result = tester.load_ontology_from_file(file_record.file_path)
if isinstance(result, dict) and not result.get('loaded', False):
# If load_ontology_from_file returns a dictionary with loaded=False
error_msg = result.get('error', 'Unknown error')
return jsonify({'error': f"Failed to load ontology: {error_msg}"}), 500
# Get the ontology object from the result
onto = None
if isinstance(result, dict) and 'ontology' in result:
onto = result.get('ontology')
if not onto:
return jsonify({'error': "Loaded ontology object not found in result"}), 500
# Process the ontology data into a format suitable for D3.js
classes = []
inheritance = []
properties = []
# Process classes
for cls in onto.classes():
if hasattr(cls, 'name') and cls.name:
# Determine if it's a BFO class
is_bfo = False
if hasattr(cls, 'iri'):
is_bfo = 'BFO' in str(cls.iri) or 'IAO' in str(cls.iri)
classes.append({
'id': cls.name,
'name': cls.name,
'bfo': is_bfo
})
# Process inheritance relationships
for parent in cls.is_a:
if hasattr(parent, 'name') and parent.name:
inheritance.append({
'parent': parent.name,
'child': cls.name
})
# Process object properties
for prop in onto.object_properties():
if hasattr(prop, 'name') and prop.name:
if hasattr(prop, 'domain') and prop.domain and hasattr(prop, 'range') and prop.range:
for domain_cls in prop.domain:
for range_cls in prop.range:
if hasattr(domain_cls, 'name') and domain_cls.name and hasattr(range_cls, 'name') and range_cls.name:
properties.append({
'domain': domain_cls.name,
'range': range_cls.name,
'name': prop.name
})
# Return data as JSON
return jsonify({
'classes': classes,
'inheritance': inheritance,
'properties': properties
})
except Exception as e:
logger.error(f"Error generating diagram data: {str(e)}")
return jsonify({'error': f"Error generating diagram data: {str(e)}"}), 500
@app.route('/api/diagram/<filename>', methods=['GET'])
def api_generate_diagram(filename):
"""Legacy API endpoint - redirects to the new interactive diagram."""
# Redirect to the new interactive diagram
return redirect(url_for('generate_diagram', filename=filename))
# Error handlers
@app.errorhandler(404)
def page_not_found(e):
return render_template('index.html', error="Page not found"), 404
@app.errorhandler(500)
def server_error(e):
return render_template('index.html', error=f"Server error: {str(e)}"), 500
# User Authentication
@app.route('/login', methods=['GET', 'POST'])
def login():
"""User login page"""
if current_user.is_authenticated:
return redirect(url_for('index'))
form = LoginForm()
if form.validate_on_submit():
# Find the user by email
user = User.query.filter_by(email=form.email.data).first()
if user is None or not user.check_password(form.password.data):
flash('Invalid email or password', 'error')
return redirect(url_for('login'))
# Log the user in
login_user(user, remember=form.remember_me.data)
# Update last login timestamp
user.last_login = datetime.datetime.utcnow()
db.session.commit()
# Redirect to the page the user was trying to access
next_page = request.args.get('next')
if not next_page or urlparse(next_page).netloc != '':
next_page = url_for('index')
flash('Login successful', 'success')
return redirect(next_page)
return render_template('login.html', form=form)
@app.route('/register', methods=['GET', 'POST'])
def register():
"""User registration page"""
if current_user.is_authenticated:
return redirect(url_for('index'))
form = RegistrationForm()
if form.validate_on_submit():
# Create a new user
user = User(username=form.username.data, email=form.email.data)
user.set_password(form.password.data)
db.session.add(user)
db.session.commit()
flash('Congratulations, you are now a registered user! Please log in.', 'success')
return redirect(url_for('login'))
return render_template('register.html', form=form)
@app.route('/logout')
def logout():
"""User logout"""
logout_user()
flash('You have been logged out', 'info')
return redirect(url_for('index'))
@app.route('/dashboard')
@login_required
def dashboard():
"""User dashboard with personalized analysis history"""
try:
# Get all ontology files for the current user, ordered by upload date (newest first)
ontologies = OntologyFile.query.filter_by(user_id=current_user.id).order_by(OntologyFile.upload_date.desc()).all()
# Get all FOL expressions for the current user, ordered by test date (newest first)
expressions = FOLExpression.query.filter_by(user_id=current_user.id).order_by(FOLExpression.test_date.desc()).limit(20).all()
return render_template('dashboard.html',
ontologies=ontologies,
expressions=expressions)
except Exception as e:
logger.error(f"Error accessing dashboard: {str(e)}")
flash(f"Error accessing dashboard: {str(e)}", 'error')
return redirect(url_for('index'))
# Sandbox for ontology development
class DomainForm(FlaskForm):
"""Form for creating a new ontology in the sandbox."""
title = StringField('Title', validators=[DataRequired(), Length(min=3, max=255)])
domain = StringField('Domain', validators=[DataRequired(), Length(min=2, max=100)])
subject = StringField('Subject', validators=[DataRequired(), Length(min=2, max=100)])
description = StringField('Description', validators=[Length(max=500)])
submit = SubmitField('Create Ontology')
@app.route('/sandbox')
def sandbox_list():
"""Show a list of sandbox ontologies for the current user or public ones."""
try:
if current_user.is_authenticated:
# Get ontologies for the current user
ontologies = SandboxOntology.query.filter_by(user_id=current_user.id).order_by(SandboxOntology.last_modified.desc()).all()
else:
# Get public ontologies
ontologies = SandboxOntology.query.order_by(SandboxOntology.last_modified.desc()).limit(20).all()
return render_template('sandbox_list.html', ontologies=ontologies)
except Exception as e:
logger.error(f"Error listing sandbox ontologies: {str(e)}")
flash(f"Error listing sandbox ontologies: {str(e)}", 'error')
return redirect(url_for('index'))
@app.route('/sandbox/new', methods=['GET', 'POST'])
def sandbox_new():
"""Create a new sandbox ontology."""
try:
form = DomainForm()
if form.validate_on_submit():
# Create a new ontology
ontology = SandboxOntology(
title=form.title.data,
domain=form.domain.data,
subject=form.subject.data,
description=form.description.data,
user_id=current_user.id if current_user.is_authenticated else None
)
db.session.add(ontology)
db.session.commit()
flash('Ontology created successfully', 'success')
return redirect(url_for('sandbox_view', ontology_id=ontology.id))
return render_template('sandbox_new.html', form=form)
except Exception as e:
logger.error(f"Error creating sandbox ontology: {str(e)}")
flash(f"Error creating sandbox ontology: {str(e)}", 'error')
return redirect(url_for('sandbox_list'))
@app.route('/sandbox/<int:ontology_id>')
def sandbox_view(ontology_id):
"""View a sandbox ontology."""
try:
ontology = SandboxOntology.query.get_or_404(ontology_id)
# Get the ontology's classes, properties, and individuals
classes = OntologyClass.query.filter_by(ontology_id=ontology_id).all()
properties = OntologyProperty.query.filter_by(ontology_id=ontology_id).all()
individuals = OntologyIndividual.query.filter_by(ontology_id=ontology_id).all()
return render_template('sandbox_view.html',
ontology=ontology,
classes=classes,
properties=properties,
individuals=individuals)
except Exception as e:
logger.error(f"Error viewing sandbox ontology: {str(e)}")
flash(f"Error viewing sandbox ontology: {str(e)}", 'error')
return redirect(url_for('sandbox_list'))
@app.route('/sandbox/<int:ontology_id>/edit')
def sandbox_edit(ontology_id):
"""Edit a sandbox ontology."""
try:
ontology = SandboxOntology.query.get_or_404(ontology_id)
# Check if the current user can edit this ontology
if current_user.is_authenticated and ontology.user_id == current_user.id:
return render_template('sandbox_edit.html', ontology=ontology)
else:
flash('You do not have permission to edit this ontology', 'error')
return redirect(url_for('sandbox_view', ontology_id=ontology_id))
except Exception as e:
logger.error(f"Error editing sandbox ontology: {str(e)}")
flash(f"Error editing sandbox ontology: {str(e)}", 'error')
return redirect(url_for('sandbox_list'))
@app.route('/sandbox/<int:ontology_id>/download')
def sandbox_download(ontology_id):
"""Download a sandbox ontology as OWL/RDF."""
try:
ontology = SandboxOntology.query.get_or_404(ontology_id)
# Get the ontology's classes, properties, and individuals
classes = OntologyClass.query.filter_by(ontology_id=ontology_id).all()
properties = OntologyProperty.query.filter_by(ontology_id=ontology_id).all()
individuals = OntologyIndividual.query.filter_by(ontology_id=ontology_id).all()
# Generate OWL/RDF XML
owl_xml = generate_owl_xml(ontology, classes, properties, individuals)
# Create a response with the XML
response = make_response(owl_xml)
response.headers['Content-Type'] = 'application/rdf+xml'