-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py.bak
More file actions
2663 lines (2194 loc) · 123 KB
/
app.py.bak
File metadata and controls
2663 lines (2194 loc) · 123 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.')
# Load the default OwlTester
logger.info("Initializing OwlTester...")
try:
owl_tester = OwlTester()
logger.info(f"Successfully loaded {len(owl_tester.get_bfo_classes())} BFO classes and {len(owl_tester.get_bfo_relations())} relations")
except Exception as e:
logger.error(f"Error initializing OwlTester: {str(e)}")
owl_tester = None
@app.route('/')
def index():
"""Render the main page."""
if owl_tester is None:
return render_template('index.html', error="OwlTester is not initialized properly")
# Format BFO classes as a list with id and label attributes for the template
bfo_classes_dict = owl_tester.get_bfo_classes()
bfo_classes = []
for key, data in bfo_classes_dict.items():
bfo_classes.append({
'id': key,
'label': data['label'],
'description': data.get('description', '')
})
# Format BFO relations as a list with id and label attributes for the template
bfo_relations_dict = owl_tester.get_bfo_relations()
bfo_relations = []
for key, data in bfo_relations_dict.items():
bfo_relations.append({
'id': key,
'label': data['label'],
'description': data.get('description', '')
})
return render_template('index.html',
bfo_classes=bfo_classes,
bfo_relations=bfo_relations)
@app.route('/about')
def about():
"""Render the about page with information about FOL-BFO-OWL testing."""
return render_template('about.html')
@app.route('/api/test', methods=['POST'])
def test_expression():
"""API endpoint to test a FOL expression."""
if owl_tester is None:
return jsonify({"error": "OwlTester is not initialized properly"}), 500
data = request.get_json()
if not data or 'expression' not in data:
return jsonify({"error": "No expression provided"}), 400
expression = data['expression']
logger.debug(f"Testing expression: {expression}")
# Check if the expression contains comma-separated quantifiers and needs preprocessing
needs_preprocessing = ',' in expression and re.search(r'(forall|exists)\s+\w+\s*,', expression)
if needs_preprocessing:
processed_expr = preprocess_expression(expression)
logger.debug(f"Preprocessed expression: {processed_expr}")
else:
processed_expr = expression
try:
result = owl_tester.test_expression(processed_expr)
# Add preprocessing info to the result
if needs_preprocessing:
result['preprocessed'] = True
result['original_expression'] = expression
result['preprocessed_expression'] = processed_expr
# Save the test result to the database
# Associate expression with current user if logged in
user_id = current_user.id if current_user.is_authenticated else None
fol_expression = FOLExpression()
fol_expression.expression = expression
fol_expression.is_valid = result.get('valid', False)
fol_expression.test_results = result
fol_expression.issues = result.get('issues', [])
fol_expression.bfo_classes_used = result.get('bfo_classes_used', [])
fol_expression.bfo_relations_used = result.get('bfo_relations_used', [])
fol_expression.non_bfo_terms = result.get('non_bfo_terms', [])
fol_expression.user_id = user_id
db.session.add(fol_expression)
db.session.commit()
logger.info(f"Saved FOL expression test results to database with ID {fol_expression.id}")
return jsonify(result)
except Exception as e:
logger.error(f"Error testing expression: {str(e)}")
return jsonify({"error": f"Internal server error: {str(e)}"}), 500
@app.route('/api/bfo-classes')
def get_bfo_classes():
"""API endpoint to get all BFO classes."""
if owl_tester is None:
return jsonify({"error": "OwlTester is not initialized properly"}), 500
# Format BFO classes as a list with id and label attributes
bfo_classes_dict = owl_tester.get_bfo_classes()
bfo_classes = []
for key, data in bfo_classes_dict.items():
bfo_classes.append({
'id': key,
'label': data['label'],
'description': data.get('description', '')
})
return jsonify({"classes": bfo_classes})
@app.route('/api/bfo-relations')
def get_bfo_relations():
"""API endpoint to get all BFO relations."""
if owl_tester is None:
return jsonify({"error": "OwlTester is not initialized properly"}), 500
# Format BFO relations as a list with id and label attributes
bfo_relations_dict = owl_tester.get_bfo_relations()
bfo_relations = []
for key, data in bfo_relations_dict.items():
bfo_relations.append({
'id': key,
'label': data['label'],
'description': data.get('description', '')
})
return jsonify({"relations": bfo_relations})
@app.route('/api/validate-completeness/<int:analysis_id>', methods=['GET'])
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:
# Find the analysis
analysis = OntologyAnalysis.query.get(analysis_id)
if not analysis:
return jsonify({"error": "Analysis not found"}), 404
# Get the ontology file
ontology_file = OntologyFile.query.get(analysis.ontology_file_id)
if not ontology_file:
return jsonify({"error": "Ontology file not found"}), 404
# Create a custom tester for this ontology
try:
custom_tester = OwlTester()
# Load the ontology file
result = custom_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')
raise Exception(f"Failed to load ontology for completeness validation: {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")
except Exception as e:
logger.error(f"Error loading ontology for completeness validation: {str(e)}")
raise e
# Perform completeness validation
completeness_report = custom_tester.validate_completeness(onto)
# Store the result in the database if possible
# Update analysis model if needed - for now just return
logger.info(f"Validated completeness for analysis ID {analysis_id}: {completeness_report.get('complete')}")
return jsonify({
"success": True,
"completeness": completeness_report
})
except Exception as e:
logger.error(f"Error validating completeness: {str(e)}")
return jsonify({
"success": False,
"error": f"Error validating completeness: {str(e)}"
}), 500
@app.route('/api/enhanced-consistency/<int:analysis_id>', methods=['GET'])
def check_enhanced_consistency(analysis_id):
"""
Perform enhanced consistency checking using multiple reasoners.
Returns detailed report about contradictions and problematic axioms.
"""
try:
# Find the analysis
analysis = OntologyAnalysis.query.get(analysis_id)
if not analysis:
return jsonify({"error": "Analysis not found"}), 404
# Get the ontology file
ontology_file = OntologyFile.query.get(analysis.ontology_file_id)
if not ontology_file:
return jsonify({"error": "Ontology file not found"}), 404
# Create a custom tester for this ontology
try:
custom_tester = OwlTester()
# Load the ontology file
result = custom_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')
raise Exception(f"Failed to load ontology for enhanced consistency: {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")
except Exception as e:
logger.error(f"Error loading ontology for enhanced consistency: {str(e)}")
raise e
# Perform enhanced consistency checking
consistency_report = custom_tester.check_consistency(onto)
# Update the analysis record if possible
analysis.consistency_issues = consistency_report
db.session.commit()
logger.info(f"Checked enhanced consistency for analysis ID {analysis_id}: {consistency_report.get('consistent')}")
return jsonify({
"success": True,
"consistency": consistency_report
})
except Exception as e:
logger.error(f"Error checking enhanced consistency: {str(e)}")
return jsonify({
"success": False,
"error": f"Error checking enhanced consistency: {str(e)}"
}), 500
@app.route('/upload', methods=['GET', 'POST'])
def upload_owl():
"""Handle OWL file upload and redirection to analysis page."""
if request.method == 'POST' and 'owl_file' in request.files:
# Get the file
file = request.files['owl_file']
if file.filename == '':
flash('No file selected', 'error')
return redirect(request.url)
if not allowed_file(file.filename):
flash('Invalid file type. Please upload an OWL/RDF file (.owl, .rdf, .xml, .ttl, .n3, .nt, .ofn, .own, .owx)', 'error')
return redirect(request.url)
try:
# Generate a unique filename to avoid collisions
filename = file.filename or "unknown_file.owl"
original_filename = secure_filename(filename)
file_ext = os.path.splitext(original_filename)[1]
unique_filename = f"{uuid.uuid4().hex}{file_ext}"
# Save the file
file_path = os.path.join(app.config['UPLOADED_OWLS_DEST'], unique_filename)
file.save(file_path)
# Save file info to the database
file_size = os.path.getsize(file_path)
mime_type = file.content_type if hasattr(file, 'content_type') else 'application/rdf+xml'
# Associate file with current user if logged in
user_id = current_user.id if current_user.is_authenticated else None
ontology_file = OntologyFile()
ontology_file.filename = unique_filename
ontology_file.original_filename = original_filename
ontology_file.file_path = file_path
ontology_file.file_size = file_size
ontology_file.mime_type = mime_type
ontology_file.user_id = user_id
db.session.add(ontology_file)
db.session.commit()
logger.info(f"File uploaded: {original_filename} (saved as {unique_filename}) with ID {ontology_file.id}")
# Redirect to the analysis page
return redirect(url_for('analyze_owl', filename=unique_filename,
original_name=original_filename,
file_id=ontology_file.id))
except Exception as e:
logger.error(f"Error during file upload: {str(e)}")
flash(f"Error during file upload: {str(e)}", 'error')
return redirect(request.url)
# GET request - render upload form
return render_template('upload.html')
@app.route('/analyze/<filename>')
def analyze_owl(filename):
"""Analyze an uploaded OWL file and display results."""
try:
# Get the original filename from query parameters
original_name = request.args.get('original_name', filename)
file_id = request.args.get('file_id')
# Construct full path to the file
file_path = os.path.join(app.config['UPLOADED_OWLS_DEST'], filename)
if not os.path.exists(file_path):
flash('File not found', 'error')
return redirect(url_for('upload_owl'))
# Create a new OwlTester instance
custom_tester = OwlTester()
# Load the ontology file
result = custom_tester.load_ontology_from_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')
flash(f"Failed to load ontology: {error_msg}", 'error')
return redirect(url_for('upload_owl'))
# Get the ontology object from the result
onto = None
if isinstance(result, dict) and 'ontology' in result:
onto = result.get('ontology')
if not onto:
flash("Loaded ontology object not found in result", 'error')
return redirect(url_for('upload_owl'))
# Generate analysis report with the ontology object
analysis = custom_tester.analyze_ontology(onto)
# Generate PlantUML diagram code
from plantuml_generator import PlantUMLGenerator
plant_generator = PlantUMLGenerator()
plantuml_code, diagram_path, svg_path = plant_generator.generate_class_diagram(
onto,
filename_base=os.path.splitext(filename)[0], # Use the current filename as base
include_individuals=False,
include_data_properties=True,
include_annotation_properties=False,
max_classes=1000 # Increased to show more classes
)
# plantuml_code is already populated from generate_class_diagram
# Save analysis to database if we have a file_id
if file_id:
try:
ontology_file = OntologyFile.query.get(int(file_id))
if ontology_file:
# Create analysis record
ontology_analysis = OntologyAnalysis()
ontology_analysis.ontology_file_id = ontology_file.id
ontology_analysis.ontology_name = analysis.get('ontology_name', 'Unknown')
ontology_analysis.ontology_iri = analysis.get('ontology_iri', '')
# Handle consistency properly depending on type
consistency_data = analysis.get('consistency')
if isinstance(consistency_data, dict):
# Traditional analysis with consistency as a dictionary
ontology_analysis.is_consistent = consistency_data.get('consistent', True)
elif isinstance(consistency_data, str):
# RDFLIB analysis with consistency as a string
ontology_analysis.is_consistent = (consistency_data != 'Inconsistent')
# Save counts with debug logging
class_count = analysis.get('class_count', 0)
obj_prop_count = analysis.get('object_property_count', 0)
data_prop_count = analysis.get('data_property_count', 0)
indiv_count = analysis.get('individual_count', 0)
annot_prop_count = analysis.get('annotation_property_count', 0)
axiom_count = analysis.get('axiom_count', 0)
app.logger.info(f"★★★ DATABASE COUNTS - Classes: {class_count}, Obj Props: {obj_prop_count}, Data Props: {data_prop_count}, Individuals: {indiv_count} ★★★")
# Check for the non-standard naming convention keys
if 'classes' in analysis:
rdflib_class_count = analysis.get('classes')
app.logger.info(f"★★★ Found 'classes' key: {rdflib_class_count} ★★★")
if isinstance(rdflib_class_count, int) and rdflib_class_count > 0:
class_count = rdflib_class_count
# Explicitly add the standardized key for saving to DB
analysis['class_count'] = class_count
app.logger.info(f"★★★ Setting class_count to {class_count} ★★★")
if 'object_properties' in analysis:
rdflib_obj_count = analysis.get('object_properties')
app.logger.info(f"★★★ Found 'object_properties' key: {rdflib_obj_count} ★★★")
if isinstance(rdflib_obj_count, int) and rdflib_obj_count > 0:
obj_prop_count = rdflib_obj_count
# Explicitly add the standardized key for saving to DB
analysis['object_property_count'] = obj_prop_count
app.logger.info(f"★★★ Setting object_property_count to {obj_prop_count} ★★★")
if 'data_properties' in analysis:
rdflib_data_count = analysis.get('data_properties')
app.logger.info(f"★★★ Found 'data_properties' key: {rdflib_data_count} ★★★")
if isinstance(rdflib_data_count, int) and rdflib_data_count > 0:
data_prop_count = rdflib_data_count
analysis['data_property_count'] = data_prop_count
app.logger.info(f"★★★ Setting data_property_count to {data_prop_count} ★★★")
if 'individuals' in analysis:
rdflib_indiv_count = analysis.get('individuals')
app.logger.info(f"★★★ Found 'individuals' key: {rdflib_indiv_count} ★★★")
if isinstance(rdflib_indiv_count, int) and rdflib_indiv_count > 0:
indiv_count = rdflib_indiv_count
analysis['individual_count'] = indiv_count
app.logger.info(f"★★★ Setting individual_count to {indiv_count} ★★★")
if 'annotation_properties' in analysis:
rdflib_annot_count = analysis.get('annotation_properties')
app.logger.info(f"★★★ Found 'annotation_properties' key: {rdflib_annot_count} ★★★")
if isinstance(rdflib_annot_count, int) and rdflib_annot_count > 0:
annot_prop_count = rdflib_annot_count
analysis['annotation_property_count'] = annot_prop_count
app.logger.info(f"★★★ Setting annotation_property_count to {annot_prop_count} ★★★")
ontology_analysis.class_count = class_count
ontology_analysis.object_property_count = obj_prop_count
ontology_analysis.data_property_count = data_prop_count
ontology_analysis.individual_count = indiv_count
ontology_analysis.annotation_property_count = annot_prop_count
ontology_analysis.axiom_count = axiom_count
ontology_analysis.expressivity = analysis.get('expressivity', '')
ontology_analysis.complexity = analysis.get('complexity', 0)
# Handle axioms properly depending on type
axioms_data = analysis.get('axioms', [])
if isinstance(axioms_data, int):
# If axioms is just a count (from rdflib analysis), store an empty list
ontology_analysis.axioms = []
else:
ontology_analysis.axioms = axioms_data
# Handle consistency issues properly
consistency_data = analysis.get('consistency')
if isinstance(consistency_data, dict):
ontology_analysis.consistency_issues = consistency_data.get('issues', [])
else:
# For rdflib analysis, no detailed issues available
ontology_analysis.consistency_issues = []
ontology_analysis.inferred_axioms = analysis.get('inferred', [])
# Make sure FOL premises are correctly extracted from the analysis
fol_premises = analysis.get('fol_premises', [])
# If no premises were found, generate default ones
if not fol_premises:
app.logger.warning("★★★ NO FOL PREMISES FOUND, GENERATING DEFAULTS ★★★")
# Access class and property lists from the analysis
classes_list = analysis.get('class_list', [])
obj_properties_list = analysis.get('object_property_list', [])
app.logger.info(f"★★★ FOUND {len(classes_list)} CLASSES AND {len(obj_properties_list)} PROPERTIES FOR DEFAULT PREMISES ★★★")
# Generate basic premises for all classes
for cls_info in classes_list:
try:
if isinstance(cls_info, dict) and 'name' in cls_info:
cls_label = cls_info['name']
elif isinstance(cls_info, str):
cls_label = cls_info
else:
continue
# Skip external ontology classes like owl:Thing
if cls_label.startswith("owl:") or cls_label == "Thing":
continue
fol_premises.append({
'type': 'class',
'fol': f"instance_of(x, {cls_label}, t)",
'description': f"Entities that are instances of {cls_label}"
})
app.logger.info(f"★★★ Added default class FOL premise for: {cls_label} ★★★")
except Exception as e:
app.logger.error(f"★★★ Error generating default FOL premise for class: {str(e)} ★★★")
# Generate basic premises for object properties
for prop_info in obj_properties_list:
try:
if isinstance(prop_info, dict) and 'name' in prop_info:
prop_label = prop_info['name']
elif isinstance(prop_info, str):
prop_label = prop_info
else:
continue
fol_premises.append({
'type': 'property',
'fol': f"{prop_label}(x, y, t)",
'description': f"Relation {prop_label} between entities"
})
app.logger.info(f"★★★ Added default property FOL premise for: {prop_label} ★★★")
except Exception as e:
app.logger.error(f"★★★ Error generating default FOL premise for property: {str(e)} ★★★")
app.logger.info(f"★★★ SAVING FOL PREMISES TO DATABASE: COUNT = {len(fol_premises)} ★★★")
if fol_premises:
app.logger.info(f"★★★ SAMPLE FOL PREMISES BEING SAVED: {fol_premises[:2]} ★★★")
else:
app.logger.warning("★★★ NO FOL PREMISES FOUND TO SAVE TO DATABASE ★★★")
# Save to database
ontology_analysis.fol_premises = fol_premises
db.session.add(ontology_analysis)
db.session.commit()
logger.info(f"★★★ COMMITTED TO DATABASE - Classes: {ontology_analysis.class_count}, Object Props: {ontology_analysis.object_property_count} ★★★")
logger.info(f"Saved analysis to database with ID {ontology_analysis.id}")
except Exception as e:
logger.error(f"Error saving analysis to database: {str(e)}")
# Continue with the analysis even if saving to DB fails
# Debug log to see what fields are in the analysis
logger.info(f"Analysis keys: {list(analysis.keys())}")
if 'stats' in analysis:
logger.info(f"Stats: {analysis['stats']}")
# Move stats to the top level for easier access in the template
if 'stats' in analysis:
# Move stats fields to the top level of the analysis object
for key, value in analysis['stats'].items():
analysis[key] = value
# Add total axiom count if not present
# Handle axioms properly depending on type
if 'axioms' in analysis:
if isinstance(analysis['axioms'], list):
analysis['axiom_count'] = len(analysis['axioms'])
elif isinstance(analysis['axioms'], int):
analysis['axiom_count'] = analysis['axioms']
# Add expressivity from metrics if available
if 'metrics' in analysis and 'expressivity' in analysis['metrics']:
analysis['expressivity'] = analysis['metrics']['expressivity']
# Add complexity from metrics if available
if 'metrics' in analysis and 'complexity' in analysis['metrics']:
analysis['complexity'] = analysis['metrics']['complexity']
# Debug log to show what fields are now in the analysis
logger.info(f"Updated analysis keys: {list(analysis.keys())}")
logger.info(f"★★★ ANALYSIS VALUES BEFORE RENDERING TEMPLATE ★★★")
logger.info(f"Class count: {analysis.get('class_count')} or {analysis.get('classes')}")
logger.info(f"Object property count: {analysis.get('object_property_count')} or {analysis.get('object_properties')}")
logger.info(f"Data property count: {analysis.get('data_property_count')} or {analysis.get('data_properties')}")
logger.info(f"Individual count: {analysis.get('individual_count')} or {analysis.get('individuals')}")
logger.info(f"Axiom count: {analysis.get('axiom_count')}")
# Check if FOL premises are present and log them
fol_premises = analysis.get('fol_premises', [])
logger.info(f"★★★ FOL PREMISES COUNT BEFORE RENDERING: {len(fol_premises)} ★★★")
if fol_premises:
logger.info(f"★★★ SAMPLE FOL PREMISES BEFORE RENDERING: {fol_premises[:3]} ★★★")
# Ensure FOL premises are properly formatted for rendering
if isinstance(fol_premises, list) and all(isinstance(p, dict) for p in fol_premises):
logger.info("★★★ FOL premises are properly formatted as list of dictionaries ★★★")
else:
logger.warning("★★★ FOL premises are not properly formatted, converting... ★★★")
# Attempt to fix format if needed
if isinstance(fol_premises, str):
logger.warning("★★★ FOL premises found as string, converting to list ★★★")
try:
import json
fol_premises = json.loads(fol_premises)
analysis['fol_premises'] = fol_premises
except:
logger.error("★★★ Failed to convert FOL premises from string ★★★")
else:
logger.warning(f"★★★ NO FOL PREMISES FOUND IN ANALYSIS DICT, GENERATING DEFAULT PREMISES ★★★")
# Generate default FOL premises
fol_premises = []
# Get class and property lists
class_list = analysis.get('class_list', [])
obj_property_list = analysis.get('object_property_list', [])
logger.info(f"★★★ FOUND {len(class_list)} CLASSES AND {len(obj_property_list)} PROPERTIES FOR DEFAULT PREMISES ★★★")
# Generate basic premises for all classes
for cls_info in class_list:
try:
if isinstance(cls_info, dict) and 'name' in cls_info:
cls_label = cls_info['name']
elif isinstance(cls_info, str):
cls_label = cls_info
else:
continue
# Skip external ontology classes like owl:Thing
if cls_label.startswith("owl:") or cls_label == "Thing":
continue
fol_premises.append({
'type': 'class',
'fol': f"instance_of(x, {cls_label}, t)",
'description': f"Entities that are instances of {cls_label}"
})
logger.info(f"★★★ Added default class FOL premise for: {cls_label} ★★★")
except Exception as e:
logger.error(f"★★★ Error generating default FOL premise for class: {str(e)} ★★★")
# Generate basic premises for object properties
for prop_info in obj_property_list:
try:
if isinstance(prop_info, dict) and 'name' in prop_info:
prop_label = prop_info['name']
elif isinstance(prop_info, str):
prop_label = prop_info
else:
continue
fol_premises.append({
'type': 'property',
'fol': f"{prop_label}(x, y, t)",
'description': f"Relation {prop_label} between entities"
})
logger.info(f"★★★ Added default property FOL premise for: {prop_label} ★★★")
except Exception as e:
logger.error(f"★★★ Error generating default FOL premise for property: {str(e)} ★★★")
# Update the analysis with the generated premises
analysis['fol_premises'] = fol_premises
logger.info(f"★★★ GENERATED {len(fol_premises)} DEFAULT FOL PREMISES ★★★")
# Update analysis with completeness validation if available
if 'completeness' in analysis:
logger.info(f"Completeness data available: {analysis['completeness']}")
# Add analysis ID for API calls
analysis_id = None
try:
# Try to get the analysis ID if we saved to DB
if file_id:
ont_analysis = OntologyAnalysis.query.filter_by(ontology_file_id=int(file_id)).order_by(OntologyAnalysis.id.desc()).first()
if ont_analysis:
analysis_id = ont_analysis.id
logger.info(f"Using analysis ID {analysis_id} for API calls")
except Exception as e:
logger.error(f"Error getting analysis ID: {str(e)}")
# Render enhanced analysis template with results
return render_template('analysis_enhanced.html',
original_filename=original_name,
filename=filename,
file_id=file_id,
analysis_id=analysis_id,
analysis=analysis,
plantuml_code=plantuml_code)
except Exception as e:
logger.error(f"Error analyzing OWL file: {str(e)}")
flash(f"Error analyzing OWL file: {str(e)}", 'error')
return redirect(url_for('upload_owl'))
@app.route('/api/analyze/<filename>', methods=['GET'])
def api_analyze_owl(filename):
"""API endpoint for analyzing an uploaded OWL file."""
try:
# Construct full path to the file
file_path = os.path.join(app.config['UPLOADED_OWLS_DEST'], filename)
if not os.path.exists(file_path):
return jsonify({"error": "File not found"}), 404
# Create a new OwlTester instance
custom_tester = OwlTester()
# First try to directly analyze with rdflib without going through owlready2
try:
import rdflib
from rdflib import RDF, RDFS, OWL
app.logger.info(f"★★★ TRYING RDFLIB ANALYSIS ★★★: {file_path}")
g = rdflib.Graph()
g.parse(file_path)
if len(g) > 0:
app.logger.info(f"★★★ Successfully loaded {len(g)} triples with rdflib ★★★")
# Debug triples to see what's in the graph
app.logger.info("Inspecting RDF triples...")
type_triples = []
for s, p, o in g.triples((None, RDF.type, None)):
type_triples.append(f"{s} {p} {o}")
app.logger.info(f"Found {len(type_triples)} type triples")
if len(type_triples) > 0:
app.logger.info(f"Sample types: {type_triples[:5]}")
# Debug domain/range
domain_triples = []
for s, p, o in g.triples((None, RDFS.domain, None)):
domain_triples.append(f"{s} has domain {o}")
app.logger.info(f"Found {len(domain_triples)} domain triples: {domain_triples[:5]}")
# Explicitly define namespaces
OWL = rdflib.Namespace("http://www.w3.org/2002/07/owl#")
# Count classes - support all formats of OWL class declarations
classes = set()
app.logger.info("★★★ SEARCHING FOR CLASSES IN MULTIPLE FORMATS ★★★")
# Standard OWL class declaration check
explicit_classes = []
for s, p, o in g.triples((None, RDF.type, OWL.Class)):
class_uri = str(s)
classes.add(class_uri)
explicit_classes.append(class_uri)
app.logger.info(f"★★★ Found explicit OWL Class: {class_uri} ★★★")
app.logger.info(f"★★★ Found {len(explicit_classes)} explicit OWL Classes ★★★")
# RDF Schema class definition - subclass relationships
subclass_classes = []
for s, p, o in g.triples((None, RDFS.subClassOf, None)):
class_uri = str(s)
classes.add(class_uri)
if class_uri not in explicit_classes:
subclass_classes.append(class_uri)
app.logger.info(f"★★★ Found class from subClassOf: {class_uri} ★★★")
app.logger.info(f"★★★ Found {len(subclass_classes)} additional classes from subClassOf ★★★")
# Add parent classes from subClassOf relationships as well
parent_classes = []
for s, p, o in g.triples((None, RDFS.subClassOf, None)):
if str(o) != str(OWL.Thing) and str(o) != str(RDFS.Resource):
parent_class = str(o)
classes.add(parent_class)
if parent_class not in explicit_classes and parent_class not in subclass_classes:
parent_classes.append(parent_class)
app.logger.info(f"★★★ Found parent class from subClassOf: {parent_class} ★★★")
app.logger.info(f"★★★ Found {len(parent_classes)} additional parent classes ★★★")
# Important: Handle alternate formats - in some RDF/XML formats, classes
# are just referenced in domain/range without explicit type declaration
domain_range_resources = set()
# Get all domain values (often classes)
for s, p, o in g.triples((None, RDFS.domain, None)):
domain_range_resources.add(str(o))
# Get all range values (often classes)
for s, p, o in g.triples((None, RDFS.range, None)):
domain_range_resources.add(str(o))
# Check for other RDF/XML formats where Classes may be implied by other patterns
# - Classes often have a "label" property
for s, p, o in g.triples((None, RDFS.label, None)):
# Verify this is an entity without a defined type (which would be handled elsewhere)
has_type = False
for _, _, _ in g.triples((s, RDF.type, None)):
has_type = True
break
# If it's just a labelled resource with no type, check for class-like patterns
if not has_type:
# See if it appears in any domain/range (class-like behavior)
in_domain_range = False
for _, _, o2 in g.triples((None, RDFS.domain, s)):
in_domain_range = True
break
for _, _, o2 in g.triples((None, RDFS.range, s)):
in_domain_range = True
break
if in_domain_range:
classes.add(str(s))
# Add any resource referenced in domain or range if it's not a literal or XSD type
for resource in domain_range_resources:
if not str(resource).startswith("http://www.w3.org/2001/XMLSchema#") and str(resource) != str(RDFS.Literal):
# Check if not already a property
is_property = False
for _, _, _ in g.triples((rdflib.URIRef(resource), RDF.type, OWL.ObjectProperty)):
is_property = True
break
for _, _, _ in g.triples((rdflib.URIRef(resource), RDF.type, OWL.DatatypeProperty)):
is_property = True
break
if not is_property:
classes.add(resource)
app.logger.info(f"★★★ FINAL CLASS COUNT: {len(classes)} ★★★")
short_names = [c.split('#')[-1] if '#' in c else c.split('/')[-1] for c in classes]
app.logger.info(f"★★★ CLASS SHORT NAMES: {short_names} ★★★")
# Count object properties - support both direct declaration and domain/range indicators
obj_properties = set()
# First identify explicitly typed ObjectProperties
for s, p, o in g.triples((None, RDF.type, OWL.ObjectProperty)):
obj_properties.add(str(s))
app.logger.info(f"Found {len(obj_properties)} explicitly typed ObjectProperties")
# Then identify properties that have domain and range but might not be explicitly typed
domain_props = set()
for s, _, _ in g.triples((None, RDFS.domain, None)):
domain_props.add(str(s))
# For each property with a domain, check if it has a range that's not a literal
range_count = 0
for prop in domain_props:
for _, _, r in g.triples((rdflib.URIRef(prop), RDFS.range, None)):
if str(r) != str(RDFS.Literal) and not str(r).startswith("http://www.w3.org/2001/XMLSchema#"):
obj_properties.add(prop)
range_count += 1
app.logger.info(f"Found {len(domain_props)} properties with domain declarations")
app.logger.info(f"Found {range_count} non-literal range declarations")
app.logger.info(f"Total object properties after domain/range analysis: {len(obj_properties)}")
app.logger.info(f"Object property URIs: {list(obj_properties)}")
# Count data properties
data_properties = set()
# First identify explicitly typed DatatypeProperties
for s, p, o in g.triples((None, RDF.type, OWL.DatatypeProperty)):
data_properties.add(str(s))
app.logger.info(f"Found {len(data_properties)} explicitly typed DatatypeProperties")
# Then identify properties with literal or XMLSchema ranges
for s, _, _ in g.triples((None, RDFS.domain, None)):
for _, _, r in g.triples((s, RDFS.range, None)):
if str(r) == str(RDFS.Literal) or str(r).startswith("http://www.w3.org/2001/XMLSchema#"):
data_properties.add(str(s))
app.logger.info(f"Total data properties after range analysis: {len(data_properties)}")
app.logger.info(f"Data property URIs: {list(data_properties)}")
# Remove from object properties if it was misclassified
for s in data_properties:
if s in obj_properties:
obj_properties.remove(s)
# Count individuals
individuals = set()
# First look for explicitly typed NamedIndividuals
for s, p, o in g.triples((None, RDF.type, OWL.NamedIndividual)):
individuals.add(str(s))
app.logger.info(f"Found {len(individuals)} explicitly typed NamedIndividuals")
# Then check for instances of classes
instance_count = 0
for c in classes:
for s, p, o in g.triples((None, RDF.type, rdflib.URIRef(c))):
individuals.add(str(s))
instance_count += 1
app.logger.info(f"Found {instance_count} instances of defined classes")
app.logger.info(f"Total individuals: {len(individuals)}")
app.logger.info(f"Individual URIs: {list(individuals)[:5] if len(individuals) > 0 else []}...")
# Count annotation properties
annot_properties = set()
for s, p, o in g.triples((None, RDF.type, OWL.AnnotationProperty)):
annot_properties.add(str(s))
app.logger.info(f"Found {len(annot_properties)} annotation properties")
# Extract class names for display
class_list = []
for cls in classes:
# Try to get a label
label = None
for _, _, l in g.triples((rdflib.URIRef(cls), RDFS.label, None)):
label = str(l)
break
# Get comment/description if available