-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathreasoning_demo.py
More file actions
105 lines (86 loc) · 4.62 KB
/
reasoning_demo.py
File metadata and controls
105 lines (86 loc) · 4.62 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
#!/usr/bin/env python3
"""
Demonstrate automatic classification using the OWL reasoner.
This script shows how OWL reasoning can automatically classify dishes as VegetarianDish.
"""
from owlready2 import * # type: ignore
import sys
def demonstrate_reasoning():
"""Load ontology, run reasoner, and show automatic classification."""
try:
# Load the updated ontology
print("🔄 Loading ontology...")
onto = get_ontology("restaurant-ontology-updated.owl").load() # type: ignore
# Get references to classes
Dish = onto.Dish
VegetarianDish = onto.VegetarianDish
print("\n🧠 Running the Reasoner...\n")
# Before Reasoning: Count VegetarianDish instances
vegetarian_dishes_before = list(VegetarianDish.instances())
print("📋 Before reasoning:")
print(f" Dishes marked as VegetarianDish: {len(vegetarian_dishes_before)}")
# Count dishes with isVegetarian=True property
all_dishes = list(Dish.instances())
vegetarian_by_property = [
dish for dish in all_dishes
if hasattr(dish, 'isVegetarian') and dish.isVegetarian and dish.isVegetarian[0] == True
]
print(f" Dishes with isVegetarian=True: {len(vegetarian_by_property)}")
if vegetarian_by_property:
names = []
for dish in vegetarian_by_property:
name = dish.hasName[0] if hasattr(dish, 'hasName') and dish.hasName else dish.name
names.append(name)
for name in names:
print(f" - {name}")
# Run Reasoner
print("\n🔮 Running inference engine...")
with onto:
sync_reasoner(infer_property_values=True) # type: ignore
print("✅ Reasoning complete!\n")
# After Reasoning: Count VegetarianDish instances
vegetarian_dishes_after = list(VegetarianDish.instances())
print("📋 After reasoning:")
print(f" Dishes classified as VegetarianDish: {len(vegetarian_dishes_after)}")
if vegetarian_dishes_after:
print("\n Vegetarian dishes (automatically classified):")
for dish in vegetarian_dishes_after:
name = dish.hasName[0] if hasattr(dish, 'hasName') and dish.hasName else dish.name
price = dish.hasPrice[0] if hasattr(dish, 'hasPrice') and dish.hasPrice else "N/A"
spiciness = dish.hasSpiciness[0] if hasattr(dish, 'hasSpiciness') and dish.hasSpiciness else "N/A"
print(f" 🌱 {name} - ${price} (Spiciness: {spiciness})")
# Smart Query: Find restaurants that serve vegetarian dishes
print("\n🔍 Smart Query: Restaurants serving vegetarian dishes\n")
Restaurant = onto.Restaurant
all_restaurants = list(Restaurant.instances())
restaurants_with_veg = []
for restaurant in all_restaurants:
restaurant_name = restaurant.hasName[0] if hasattr(restaurant, 'hasName') and restaurant.hasName else restaurant.name
if hasattr(restaurant, 'serves') and restaurant.serves:
dishes_list = restaurant.serves if isinstance(restaurant.serves, list) else [restaurant.serves]
veg_dishes = [dish for dish in dishes_list if dish in vegetarian_dishes_after]
if veg_dishes:
restaurants_with_veg.append((restaurant, restaurant_name, veg_dishes))
if restaurants_with_veg:
print(f" Found {len(restaurants_with_veg)} restaurants serving vegetarian dishes:\n")
for restaurant, name, veg_dishes in restaurants_with_veg:
print(f" 🏪 {name}")
for dish in veg_dishes:
dish_name = dish.hasName[0] if hasattr(dish, 'hasName') and dish.hasName else dish.name
price = dish.hasPrice[0] if hasattr(dish, 'hasPrice') and dish.hasPrice else "N/A"
print(f" 🌱 {dish_name} - ${price}")
print()
else:
print(" No restaurants found serving vegetarian dishes.")
print("\n✨ Reasoning demonstration complete!")
except FileNotFoundError:
print("❌ Error: Could not find 'restaurant-ontology-updated.owl'")
print(" Please run 'add_data.py' first to create the updated ontology.")
sys.exit(1)
except Exception as e:
print(f"❌ Error: {type(e).__name__}: {e}")
import traceback
traceback.print_exc()
sys.exit(1)
if __name__ == "__main__":
demonstrate_reasoning()