traopia commited on
Commit
cf0b712
·
1 Parent(s): 85e469d

Initial commit

Browse files
.DS_Store ADDED
Binary file (6.15 kB). View file
 
.gitattributes CHANGED
File without changes
.gitignore CHANGED
File without changes
.gradio/certificate.pem ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ -----BEGIN CERTIFICATE-----
2
+ MIIFazCCA1OgAwIBAgIRAIIQz7DSQONZRGPgu2OCiwAwDQYJKoZIhvcNAQELBQAw
3
+ TzELMAkGA1UEBhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IFJlc2Vh
4
+ cmNoIEdyb3VwMRUwEwYDVQQDEwxJU1JHIFJvb3QgWDEwHhcNMTUwNjA0MTEwNDM4
5
+ WhcNMzUwNjA0MTEwNDM4WjBPMQswCQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJu
6
+ ZXQgU2VjdXJpdHkgUmVzZWFyY2ggR3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBY
7
+ MTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAK3oJHP0FDfzm54rVygc
8
+ h77ct984kIxuPOZXoHj3dcKi/vVqbvYATyjb3miGbESTtrFj/RQSa78f0uoxmyF+
9
+ 0TM8ukj13Xnfs7j/EvEhmkvBioZxaUpmZmyPfjxwv60pIgbz5MDmgK7iS4+3mX6U
10
+ A5/TR5d8mUgjU+g4rk8Kb4Mu0UlXjIB0ttov0DiNewNwIRt18jA8+o+u3dpjq+sW
11
+ T8KOEUt+zwvo/7V3LvSye0rgTBIlDHCNAymg4VMk7BPZ7hm/ELNKjD+Jo2FR3qyH
12
+ B5T0Y3HsLuJvW5iB4YlcNHlsdu87kGJ55tukmi8mxdAQ4Q7e2RCOFvu396j3x+UC
13
+ B5iPNgiV5+I3lg02dZ77DnKxHZu8A/lJBdiB3QW0KtZB6awBdpUKD9jf1b0SHzUv
14
+ KBds0pjBqAlkd25HN7rOrFleaJ1/ctaJxQZBKT5ZPt0m9STJEadao0xAH0ahmbWn
15
+ OlFuhjuefXKnEgV4We0+UXgVCwOPjdAvBbI+e0ocS3MFEvzG6uBQE3xDk3SzynTn
16
+ jh8BCNAw1FtxNrQHusEwMFxIt4I7mKZ9YIqioymCzLq9gwQbooMDQaHWBfEbwrbw
17
+ qHyGO0aoSCqI3Haadr8faqU9GY/rOPNk3sgrDQoo//fb4hVC1CLQJ13hef4Y53CI
18
+ rU7m2Ys6xt0nUW7/vGT1M0NPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV
19
+ HRMBAf8EBTADAQH/MB0GA1UdDgQWBBR5tFnme7bl5AFzgAiIyBpY9umbbjANBgkq
20
+ hkiG9w0BAQsFAAOCAgEAVR9YqbyyqFDQDLHYGmkgJykIrGF1XIpu+ILlaS/V9lZL
21
+ ubhzEFnTIZd+50xx+7LSYK05qAvqFyFWhfFQDlnrzuBZ6brJFe+GnY+EgPbk6ZGQ
22
+ 3BebYhtF8GaV0nxvwuo77x/Py9auJ/GpsMiu/X1+mvoiBOv/2X/qkSsisRcOj/KK
23
+ NFtY2PwByVS5uCbMiogziUwthDyC3+6WVwW6LLv3xLfHTjuCvjHIInNzktHCgKQ5
24
+ ORAzI4JMPJ+GslWYHb4phowim57iaztXOoJwTdwJx4nLCgdNbOhdjsnvzqvHu7Ur
25
+ TkXWStAmzOVyyghqpZXjFaH3pO3JLF+l+/+sKAIuvtd7u+Nxe5AW0wdeRlN8NwdC
26
+ jNPElpzVmbUq4JUagEiuTDkHzsxHpFKVK7q4+63SM1N95R1NbdWhscdCb+ZAJzVc
27
+ oyi3B43njTOQ5yOf+1CceWxG1bQVs5ZufpsMljq4Ui0/1lvh+wjChP4kqKOJ2qxq
28
+ 4RgqsahDYVvTH9w7jXbyLeiNdd8XM2w9U/t7y0Ff/9yi0GE44Za4rF2LN9d11TPA
29
+ mRGunUHBcnWEvgJBQl9nJEiU0Zsnvgc/ubhPgXRR4Xq37Z0j4r7g1SgEEzwxA57d
30
+ emyPxgcYxn/eR44/KJ4EBs+lVDR3veyJm+kXQ99b21/+jh5Xos1AnX5iItreGCc=
31
+ -----END CERTIFICATE-----
README.md CHANGED
File without changes
__pycache__/visual_qa.cpython-310.pyc CHANGED
File without changes
playground.ipynb CHANGED
File without changes
playground.py CHANGED
@@ -2,9 +2,22 @@ import chromadb
2
  client = chromadb.PersistentClient(path="./chroma_db") # Change path if needed
3
 
4
  # Get a list of existing collection names
5
- existing_collections = [col.name for col in client.list_collections()]
6
  collection_name = "clip_image_embeddings"
7
  if collection_name in existing_collections:
8
  collection = client.get_collection(name=collection_name)
9
  print(f"Using existing collection: {collection_name}")
10
- print(existing_collections)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
  client = chromadb.PersistentClient(path="./chroma_db") # Change path if needed
3
 
4
  # Get a list of existing collection names
5
+ existing_collections = [col for col in client.list_collections()]
6
  collection_name = "clip_image_embeddings"
7
  if collection_name in existing_collections:
8
  collection = client.get_collection(name=collection_name)
9
  print(f"Using existing collection: {collection_name}")
10
+ print(existing_collections)
11
+
12
+ # Show up to 3 items
13
+ results = collection.get(limit=3)
14
+
15
+ for i in range(len(results["ids"])):
16
+ print(f"\nItem {i + 1}:")
17
+ print(f"ID: {results['ids'][i]}")
18
+ print(f"Document: {results['documents'][i]}")
19
+ print(f"Metadata: {results['metadatas'][i]}")
20
+
21
+ print("Number of items:", len(collection.get()["ids"]))
22
+
23
+ collection_data = collection.get()
requirements.txt CHANGED
File without changes
src/__pycache__/generate_queries_alternative.cpython-310.pyc DELETED
Binary file (17 kB)
 
src/__pycache__/sparql_query_wikibase.cpython-310.pyc DELETED
Binary file (4.42 kB)
 
src/__pycache__/use_llm.cpython-310.pyc DELETED
Binary file (1.43 kB)
 
src/__pycache__/visual_qa.cpython-310.pyc DELETED
Binary file (3.4 kB)
 
src/__pycache__/wikibase_helpers.cpython-310.pyc DELETED
Binary file (5.52 kB)
 
src/generate_queries_alternative.py CHANGED
@@ -9,7 +9,7 @@ import numpy as np
9
  import os
10
  from src.sparql_query_wikibase import wikibase_properties_id, classes_wikibase
11
  #os.environ["TOKENIZERS_PARALLELISM"] = "false"
12
-
13
  import spacy
14
 
15
  def get_nlp():
@@ -23,6 +23,26 @@ nlp = get_nlp()
23
 
24
 
25
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26
  questions_queries_all = [{ "question": education_most_popular_question, "query": education_most_popular_query},
27
  { "question": how_many_designers_per_fashion_house_question, "query": how_many_designers_per_fashion_house_query},
28
  {"question": how_many_directors_per_fashion_house_question, "query": how_many_directors_per_fashion_house_query},
@@ -36,13 +56,15 @@ questions_queries_all = [{ "question": education_most_popular_question, "query":
36
  {"question": collections_jeans_question, "query": collections_jeans_query},
37
  {"question": creative_directors_school_question, "query": creative_directors_school_query},
38
  {"question": fashion_houses_thematic_collection_question, "query": fashion_houses_thematic_collection_query},
39
- {"question": fashion_house_directors_question, "query": fashion_house_directors_query},
40
- { "question": designer_fashion_house_directors_question, "query": designer_fashion_house_directors_query},
41
- { "question": country_designer_question, "query": country_designer_query},
42
- { "question": designer_order_fashion_collection_question, "query": designer_order_fashion_collection_query},
43
- { "question": designer_fashion_director_question2, "query": designer_fashion_director_query2},
44
- { "question": year_designers_birth_question, "query": year_designers_birth_query}
45
- ]
 
 
46
 
47
  if os.path.exists("web_app/query_log.json"):
48
  other_pairs = pd.read_json("web_app/query_log.json")
 
9
  import os
10
  from src.sparql_query_wikibase import wikibase_properties_id, classes_wikibase
11
  #os.environ["TOKENIZERS_PARALLELISM"] = "false"
12
+ import pandas as pd
13
  import spacy
14
 
15
  def get_nlp():
 
23
 
24
 
25
 
26
+ # questions_queries_all = [{ "question": education_most_popular_question, "query": education_most_popular_query},
27
+ # { "question": how_many_designers_per_fashion_house_question, "query": how_many_designers_per_fashion_house_query},
28
+ # {"question": how_many_directors_per_fashion_house_question, "query": how_many_directors_per_fashion_house_query},
29
+ # {"question": designers_multiple_houses_question, "query":designers_multiple_houses_query },
30
+ # {"question": award_question, "query": award_question},
31
+ # {"question": fashion_houses_with_collections_question, "query": fashion_houses_with_collections_query},
32
+ # {"question": popular_year_inception_question, "query": popular_year_inception_query},
33
+ # {"question": longest_serving_director_question, "query": longest_serving_director_query},
34
+ # {"question": houses_most_collections_question, "query": houses_most_collections_query},
35
+ # {"question": collections_sustainability_theme_question, "query": collections_sustainability_theme_query},
36
+ # {"question": collections_jeans_question, "query": collections_jeans_query},
37
+ # {"question": creative_directors_school_question, "query": creative_directors_school_query},
38
+ # {"question": fashion_houses_thematic_collection_question, "query": fashion_houses_thematic_collection_query},
39
+ # {"question": fashion_house_directors_question, "query": fashion_house_directors_query},
40
+ # { "question": designer_fashion_house_directors_question, "query": designer_fashion_house_directors_query},
41
+ # { "question": country_designer_question, "query": country_designer_query},
42
+ # { "question": designer_order_fashion_collection_question, "query": designer_order_fashion_collection_query},
43
+ # { "question": designer_fashion_director_question2, "query": designer_fashion_director_query2},
44
+ # { "question": year_designers_birth_question, "query": year_designers_birth_query}
45
+ # ]
46
  questions_queries_all = [{ "question": education_most_popular_question, "query": education_most_popular_query},
47
  { "question": how_many_designers_per_fashion_house_question, "query": how_many_designers_per_fashion_house_query},
48
  {"question": how_many_directors_per_fashion_house_question, "query": how_many_directors_per_fashion_house_query},
 
56
  {"question": collections_jeans_question, "query": collections_jeans_query},
57
  {"question": creative_directors_school_question, "query": creative_directors_school_query},
58
  {"question": fashion_houses_thematic_collection_question, "query": fashion_houses_thematic_collection_query},
59
+ {"question": fashion_house_directors_question.substitute({ "x": f"{"Chanel"}"}), "query": fashion_house_directors_query.substitute({ "x": f"'{"Chanel"}'"})},
60
+ { "question": designer_fashion_house_directors_question.substitute({ "x": f"{"Alexander McQueen"}"}), "query": designer_fashion_house_directors_query.substitute({ "x": f"'{"Alexander McQueen"}'"})},
61
+ {"question": country_designer_question.substitute({ "x": f"{"Italy"}"}), "query": country_designer_query.substitute({ "x": f"'{"Italy"}'"})},
62
+ { "question": designer_order_fashion_collection_question.substitute({ "x": f"{"Alexander McQueen"}"}), "query": designer_order_fashion_collection_query.substitute({ "x": f"'{"Alexander McQueen"}'"})},
63
+ {"question": designer_fashion_director_question2.substitute({ "x": f"{"Alexander McQueen"}"}), "query": designer_fashion_director_query2.substitute({ "x": f"'{"Alexander McQueen"}'"})},
64
+ { "question": year_designers_birth_question.substitute({ "x": 1970}), "query": year_designers_birth_query.substitute({ "x": 1970})},
65
+ { "question": fashion_collection_images_question.substitute({ "x": f"{"Chanel"}"}), "query": fashion_collection_images_query.substitute({ "x": f"'{"Chanel"}'"})}]
66
+
67
+
68
 
69
  if os.path.exists("web_app/query_log.json"):
70
  other_pairs = pd.read_json("web_app/query_log.json")
src/questions_queries.py CHANGED
@@ -1,3 +1,799 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import sys
2
  import os
3
  sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
@@ -5,8 +801,8 @@ from src.sparql_query_wikibase import *
5
 
6
 
7
 
8
- fashion_collection_images_question = "Images of collections produced by Chanel"
9
- fashion_collection_images_query = """
10
  PREFIX wbt: <https://fashionwiki.wikibase.cloud/prop/direct/>
11
  PREFIX wb: <https://fashionwiki.wikibase.cloud/entity/>
12
  PREFIX pq: <https://fashionwiki.wikibase.cloud/prop/qualifier/>
@@ -17,9 +813,9 @@ PREFIX prov: <http://www.w3.org/ns/prov#>
17
 
18
  SELECT ?statement ?fashion_collectionLabel ?image_url ?reference_URL
19
  ?fashion_seasonLabel (YEAR(?fashion_year) AS ?year) ?categoryLabel WHERE {
20
- { ?fashion_house rdfs:label "Chanel"@en.} # Match label
21
  UNION
22
- { ?fashion_house skos:altLabel "Chanel"@en. } # Match alias
23
 
24
 
25
  ?fashion_house p:P31 ?statement.
@@ -39,10 +835,10 @@ SELECT ?statement ?fashion_collectionLabel ?image_url ?reference_URL
39
  }
40
 
41
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en". } }
42
- """
43
 
44
- year_designers_birth_question = "Which designers were born in 1963?"
45
- year_designers_birth_query = """
46
  PREFIX wbt: <https://fashionwiki.wikibase.cloud/prop/direct/>
47
  PREFIX wb: <https://fashionwiki.wikibase.cloud/entity/>
48
  PREFIX ps: <https://fashionwiki.wikibase.cloud/prop/statement/>
@@ -53,13 +849,13 @@ PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>
53
 
54
  SELECT ?designerLabel ?birthdate WHERE {
55
  ?designer wbt:P3 ?birthdate .
56
- FILTER (YEAR(?birthdate) = 1963)
57
 
58
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
59
- } """
60
 
61
- fashion_house_directors_question = "Which designers have been creative directors of Chanel ?"
62
- fashion_house_directors_query = """
63
  PREFIX wbt: <https://fashionwiki.wikibase.cloud/prop/direct/>
64
  PREFIX wb: <https://fashionwiki.wikibase.cloud/entity/>
65
  PREFIX pq: <https://fashionwiki.wikibase.cloud/prop/qualifier/>
@@ -74,9 +870,9 @@ SELECT
74
  WHERE {
75
  # Fashion house identified by brand name
76
  ?fashion_house wbt:P2 wb:Q1.
77
- { ?fashion_house rdfs:label "Chanel"@en.} # Match label
78
  UNION
79
- { ?fashion_house skos:altLabel "Chanel"@en. } # Match alias
80
 
81
  # Link through designer employed (P29) property for the fashion house - the property for designer employment is P10
82
  {
@@ -139,12 +935,12 @@ WHERE {
139
  FILTER(?reference_URL_source != "")
140
  # Retrieve labels
141
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
142
- } ORDER BY ?start_year """
143
 
144
 
145
 
146
- designer_fashion_house_directors_question = "In which fashion house did Alessandro Michele work as a creative director?"
147
- designer_fashion_house_directors_query = """
148
  PREFIX wbt: <https://fashionwiki.wikibase.cloud/prop/direct/>
149
  PREFIX wb: <https://fashionwiki.wikibase.cloud/entity/>
150
  PREFIX pq: <https://fashionwiki.wikibase.cloud/prop/qualifier/>
@@ -160,9 +956,9 @@ SELECT ?fashion_houseLabel
160
  WHERE {
161
  # Designer linked to fashion house through roles or founded_by
162
  ?fashion_designer wbt:P2 wb:Q5.
163
- { ?fashion_designer rdfs:label "Alessandro Michele"@en.} # Match label
164
  UNION
165
- { ?fashion_designer skos:altLabel "Alessandro Michele"@en. } # Match alias
166
 
167
  # Link through employer (P10)
168
  ?fashion_designer p:P10 ?statement.
@@ -200,11 +996,11 @@ WHERE {
200
 
201
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
202
  }
203
- """
204
 
205
 
206
- designer_fashion_director_question2 = "In which fashion house did Alessandro Michele work as a creative director?"
207
- designer_fashion_director_query2 = """PREFIX wbt: <https://fashionwiki.wikibase.cloud/prop/direct/>
208
  PREFIX wb: <https://fashionwiki.wikibase.cloud/entity/>
209
  PREFIX pq: <https://fashionwiki.wikibase.cloud/prop/qualifier/>
210
  PREFIX pr: <https://fashionwiki.wikibase.cloud/prop/reference/>
@@ -217,9 +1013,9 @@ SELECT
217
  WHERE {
218
  # Fashion designer identified by name
219
  ?creative_director wbt:P2 wb:Q5.
220
- { ?creative_director rdfs:label "Alessandro Michele"@en.} # Match label
221
  UNION
222
- { ?creative_director skos:altLabel "Alessandro Michele"@en. } # Match alias
223
 
224
  # Link through designer employed (P29) property for the fashion house - the property for designer employment is P30
225
  {
@@ -256,10 +1052,10 @@ WHERE {
256
 
257
  # Retrieve labels
258
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
259
- } ORDER BY ?start_year """
260
 
261
- country_designer_question = "Which designers are from Italy ?"
262
- country_designer_query = """PREFIX wbt: <https://fashionwiki.wikibase.cloud/prop/direct/>
263
  PREFIX wb: <https://fashionwiki.wikibase.cloud/entity/>
264
  PREFIX pq: <https://fashionwiki.wikibase.cloud/prop/qualifier/>
265
  PREFIX pr: <https://fashionwiki.wikibase.cloud/prop/reference/>
@@ -276,9 +1072,9 @@ SELECT ?fashion_designerLabel (SAMPLE(?statement) AS ?statement)
276
  # Access the statement for the country relationship
277
  ?fashion_designer p:P6 ?statement.
278
  ?statement ps:P6 ?country.
279
- { ?country rdfs:label "Italy"@en.} # Match label
280
  UNION
281
- { ?country skos:altLabel "Italy"@en. } # Match alias
282
 
283
  # Retrieve references from the statement
284
  OPTIONAL {
@@ -290,9 +1086,9 @@ SELECT ?fashion_designerLabel (SAMPLE(?statement) AS ?statement)
290
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
291
  }
292
  GROUP BY ?fashion_designerLabel
293
- ORDER BY ?fashion_designerLabel """
294
 
295
- country_designer_query = """PREFIX wbt: <https://fashionwiki.wikibase.cloud/prop/direct/>
296
  PREFIX wb: <https://fashionwiki.wikibase.cloud/entity/>
297
  PREFIX pq: <https://fashionwiki.wikibase.cloud/prop/qualifier/>
298
  PREFIX pr: <https://fashionwiki.wikibase.cloud/prop/reference/>
@@ -306,9 +1102,9 @@ SELECT ?fashion_designerLabel (SAMPLE(?reference_URL) AS ?reference_URL) {
306
  ?fashion_designer wbt:P2 wb:Q5.
307
  ?fashion_designer wbt:P6 ?country.
308
  ?fashion_designer p:P6 ?statement.
309
- { ?country rdfs:label "Italy"@en.} # Match label
310
  UNION
311
- { ?country skos:altLabel "Italy"@en. } # Match alias
312
 
313
 
314
  # Retrieve references from the statement
@@ -321,11 +1117,11 @@ SELECT ?fashion_designerLabel (SAMPLE(?reference_URL) AS ?reference_URL) {
321
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
322
  }
323
  GROUP BY ?fashion_designerLabel
324
- ORDER BY ?fashion_designerLabel """
325
 
326
 
327
- designer_order_fashion_collection_question = "Which fashion collections did Alessandro Michele work on?"
328
- designer_order_fashion_collection_query = """PREFIX wbt: <https://fashionwiki.wikibase.cloud/prop/direct/>
329
  PREFIX wb: <https://fashionwiki.wikibase.cloud/entity/>
330
  PREFIX pq: <https://fashionwiki.wikibase.cloud/prop/qualifier/>
331
  PREFIX pr: <https://fashionwiki.wikibase.cloud/prop/reference/>
@@ -340,9 +1136,9 @@ SELECT ?fashion_houseLabel
340
  (YEAR(?fashion_year) as ?year ) ?fashion_seasonLabel ?categoryLabel WHERE {
341
  # Designer linked to fashion house through roles or founded_by
342
  ?fashion_designer wbt:P2 wb:Q5.
343
- { ?fashion_designer rdfs:label "Alessandro Michele"@en.} # Match label
344
  UNION
345
- { ?fashion_designer skos:altLabel "Alessandro Michele"@en. } # Match alias
346
 
347
 
348
  # Link through "creative director" or other roles
@@ -384,7 +1180,7 @@ FILTER(
384
  }
385
 
386
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
387
- } ORDER BY ?year """
388
 
389
 
390
  education_most_popular_question = "What are the most popular educational institutions for fashion designers?"
@@ -683,13 +1479,13 @@ questions_queries_dict = [ { "question": education_most_popular_question, "query
683
  {"question": collections_sustainability_theme_question, "query": collections_sustainability_theme_query},
684
  ]
685
 
686
-
687
- questions_queries_dict_entity = [{"question": fashion_house_directors_question, "query": fashion_house_directors_query},
688
- { "question": designer_fashion_house_directors_question, "query": designer_fashion_house_directors_query},
689
- { "question": country_designer_question, "query": country_designer_query},
690
- { "question": designer_order_fashion_collection_question, "query": designer_order_fashion_collection_query},
691
- { "question": designer_fashion_director_question2, "query": designer_fashion_director_query2},
692
- { "question": year_designers_birth_question, "query": year_designers_birth_query}]
693
 
694
 
695
  # Designers
@@ -795,3 +1591,4 @@ education_influenced_collection_question = "Which fashion collections were influ
795
 
796
 
797
 
 
 
1
+ # import sys
2
+ # import os
3
+ # sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
4
+ # from src.sparql_query_wikibase import *
5
+
6
+
7
+
8
+ # fashion_collection_images_question = "Images of collections produced by Chanel"
9
+ # fashion_collection_images_query = """
10
+ # PREFIX wbt: <https://fashionwiki.wikibase.cloud/prop/direct/>
11
+ # PREFIX wb: <https://fashionwiki.wikibase.cloud/entity/>
12
+ # PREFIX pq: <https://fashionwiki.wikibase.cloud/prop/qualifier/>
13
+ # PREFIX pr: <https://fashionwiki.wikibase.cloud/prop/reference/>
14
+ # PREFIX ps: <https://fashionwiki.wikibase.cloud/prop/statement/>
15
+ # PREFIX p: <https://fashionwiki.wikibase.cloud/prop/>
16
+ # PREFIX prov: <http://www.w3.org/ns/prov#>
17
+
18
+ # SELECT ?statement ?fashion_collectionLabel ?image_url ?reference_URL
19
+ # ?fashion_seasonLabel (YEAR(?fashion_year) AS ?year) ?categoryLabel WHERE {
20
+ # { ?fashion_house rdfs:label "Chanel"@en.} # Match label
21
+ # UNION
22
+ # { ?fashion_house skos:altLabel "Chanel"@en. } # Match alias
23
+
24
+
25
+ # ?fashion_house p:P31 ?statement.
26
+ # ?statement ps:P31 ?fashion_collection.
27
+ # OPTIONAL { ?fashion_collection wbt:P32 ?fashion_season. }
28
+ # OPTIONAL {?fashion_collection wbt:P28 ?fashion_year.}
29
+ # OPTIONAL {?fashion_collection wbt:P38 ?category.}
30
+
31
+ # OPTIONAL {
32
+ # ?statement pq:P35 ?image_url.
33
+ # }
34
+
35
+
36
+ # OPTIONAL {
37
+ # ?statement prov:wasDerivedFrom ?reference.
38
+ # ?reference pr:P24 ?reference_URL.
39
+ # }
40
+
41
+ # SERVICE wikibase:label { bd:serviceParam wikibase:language "en". } }
42
+ # """
43
+
44
+ # year_designers_birth_question = "Which designers were born in 1963?"
45
+ # year_designers_birth_query = """
46
+ # PREFIX wbt: <https://fashionwiki.wikibase.cloud/prop/direct/>
47
+ # PREFIX wb: <https://fashionwiki.wikibase.cloud/entity/>
48
+ # PREFIX ps: <https://fashionwiki.wikibase.cloud/prop/statement/>
49
+ # PREFIX pq: <https://fashionwiki.wikibase.cloud/prop/qualifier/>
50
+ # PREFIX p: <https://fashionwiki.wikibase.cloud/prop/>
51
+ # PREFIX prov: <http://www.w3.org/ns/prov#>
52
+ # PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>
53
+
54
+ # SELECT ?designerLabel ?birthdate WHERE {
55
+ # ?designer wbt:P3 ?birthdate .
56
+ # FILTER (YEAR(?birthdate) = 1963)
57
+
58
+ # SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
59
+ # } """
60
+
61
+ # fashion_house_directors_question = "Which designers have been creative directors of Chanel ?"
62
+ # fashion_house_directors_query = """
63
+ # PREFIX wbt: <https://fashionwiki.wikibase.cloud/prop/direct/>
64
+ # PREFIX wb: <https://fashionwiki.wikibase.cloud/entity/>
65
+ # PREFIX pq: <https://fashionwiki.wikibase.cloud/prop/qualifier/>
66
+ # PREFIX pr: <https://fashionwiki.wikibase.cloud/prop/reference/>
67
+ # PREFIX ps: <https://fashionwiki.wikibase.cloud/prop/statement/>
68
+ # PREFIX p: <https://fashionwiki.wikibase.cloud/prop/>
69
+ # PREFIX prov: <http://www.w3.org/ns/prov#>
70
+
71
+ # SELECT
72
+ # ?creative_directorLabel (COALESCE(YEAR(?start_time), YEAR(?point_time), YEAR(?inception)) AS ?start_year)
73
+ # (YEAR(?end_time) AS ?end_year) ?title ?statement ?reference_URL_source
74
+ # WHERE {
75
+ # # Fashion house identified by brand name
76
+ # ?fashion_house wbt:P2 wb:Q1.
77
+ # { ?fashion_house rdfs:label "Chanel"@en.} # Match label
78
+ # UNION
79
+ # { ?fashion_house skos:altLabel "Chanel"@en. } # Match alias
80
+
81
+ # # Link through designer employed (P29) property for the fashion house - the property for designer employment is P10
82
+ # {
83
+ # ?fashion_house p:P29 ?statement.
84
+ # ?statement ps:P29 ?creative_director.
85
+
86
+ # # Optional qualifiers for P29 regarding the time frame
87
+ # OPTIONAL { ?statement pq:P15 ?start_time. }
88
+ # OPTIONAL { ?statement pq:P28 ?point_time. }
89
+ # OPTIONAL { ?statement pq:P16 ?end_time. }
90
+ # OPTIONAL { ?statement pq:P25 ?title. }
91
+ # OPTIONAL { ?fashion_house wbt:P11 ?inception. }
92
+
93
+
94
+ # # Retrieve references for P29
95
+ # OPTIONAL {
96
+ # ?statement prov:wasDerivedFrom ?reference.
97
+ # ?reference pr:P24 ?reference_URL.
98
+ # BIND(
99
+ # IF(CONTAINS(STR(?reference_URL), "ollama") || CONTAINS(STR(?reference_URL), "gpt"), ?reference_URL, "") AS ?reference_URL_model
100
+ # )
101
+ # BIND(
102
+ # IF(!(CONTAINS(STR(?reference_URL), "ollama") || CONTAINS(STR(?reference_URL), "gpt")), ?reference_URL, "") AS ?reference_URL_source
103
+ # )
104
+ # }
105
+ # }
106
+ # UNION
107
+ # # Link through founded_by (P14) property for the fashion house
108
+ # {
109
+ # ?fashion_house p:P14 ?statement.
110
+ # ?statement ps:P14 ?creative_director.
111
+
112
+ # # Optional qualifiers for P14 (start_year as inception)
113
+ # OPTIONAL { ?statement pq:P15 ?start_time. }
114
+ # OPTIONAL { ?statement pq:P28 ?point_time. }
115
+ # OPTIONAL { ?statement pq:P16 ?end_time. }
116
+ # OPTIONAL { ?statement pq:P25 ?title. }
117
+
118
+
119
+ # # Retrieve references for P14
120
+ # OPTIONAL {
121
+ # ?statement prov:wasDerivedFrom ?reference.
122
+ # ?reference pr:P24 ?reference_URL.
123
+ # BIND(
124
+ # IF(CONTAINS(STR(?reference_URL), "ollama") || CONTAINS(STR(?reference_URL), "gpt"), ?reference_URL, "") AS ?reference_URL_model
125
+ # )
126
+ # BIND(
127
+ # IF(!(CONTAINS(STR(?reference_URL), "ollama") || CONTAINS(STR(?reference_URL), "gpt")), ?reference_URL, "") AS ?reference_URL_source
128
+ # )
129
+ # }
130
+ # }
131
+
132
+ # # Filter for relevant titles (creative director, founder, etc.) to retrieve relevant employment as creative director
133
+ # FILTER (
134
+ # REGEX(?title, "director", "i") ||
135
+ # REGEX(?title, "head designer", "i") ||
136
+ # REGEX(?title, "chief", "i") ||
137
+ # REGEX(?title, "founder", "i")
138
+ # )
139
+ # FILTER(?reference_URL_source != "")
140
+ # # Retrieve labels
141
+ # SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
142
+ # } ORDER BY ?start_year """
143
+
144
+
145
+
146
+ # designer_fashion_house_directors_question = "In which fashion house did Alessandro Michele work as a creative director?"
147
+ # designer_fashion_house_directors_query = """
148
+ # PREFIX wbt: <https://fashionwiki.wikibase.cloud/prop/direct/>
149
+ # PREFIX wb: <https://fashionwiki.wikibase.cloud/entity/>
150
+ # PREFIX pq: <https://fashionwiki.wikibase.cloud/prop/qualifier/>
151
+ # PREFIX pr: <https://fashionwiki.wikibase.cloud/prop/reference/>
152
+ # PREFIX ps: <https://fashionwiki.wikibase.cloud/prop/statement/>
153
+ # PREFIX p: <https://fashionwiki.wikibase.cloud/prop/>
154
+ # PREFIX prov: <http://www.w3.org/ns/prov#>
155
+
156
+ # SELECT ?fashion_houseLabel
157
+ # (COALESCE(YEAR(?start_time), YEAR(?point_time), YEAR(?inception)) AS ?start_year)
158
+ # (YEAR(?end_time) AS ?end_year)
159
+ # ?title ?reference_URL_source ?statement
160
+ # WHERE {
161
+ # # Designer linked to fashion house through roles or founded_by
162
+ # ?fashion_designer wbt:P2 wb:Q5.
163
+ # { ?fashion_designer rdfs:label "Alessandro Michele"@en.} # Match label
164
+ # UNION
165
+ # { ?fashion_designer skos:altLabel "Alessandro Michele"@en. } # Match alias
166
+
167
+ # # Link through employer (P10)
168
+ # ?fashion_designer p:P10 ?statement.
169
+ # ?statement ps:P10 ?fashion_house.
170
+
171
+ # # Optional start and end time qualifiers for roles
172
+ # OPTIONAL { ?statement pq:P15 ?start_time. }
173
+ # OPTIONAL { ?statement pq:P28 ?point_time. }
174
+ # OPTIONAL { ?statement pq:P16 ?end_time. }
175
+ # OPTIONAL { ?statement pq:P25 ?title. }
176
+
177
+ # # Inception as fallback for start year
178
+ # OPTIONAL { ?fashion_house wbt:P11 ?inception. }
179
+
180
+ # # Filter for relevant roles (director, founder, etc.)
181
+ # FILTER (
182
+ # REGEX(?title, "director", "i") ||
183
+ # REGEX(?title, "head designer", "i") ||
184
+ # REGEX(?title, "chief","i") ||
185
+ # REGEX(?title, "founder","i")
186
+ # )
187
+
188
+ # # Retrieve references for the statement
189
+ # OPTIONAL {
190
+ # ?statement prov:wasDerivedFrom ?reference.
191
+ # ?reference pr:P24 ?reference_URL.
192
+ # BIND(
193
+ # IF(CONTAINS(STR(?reference_URL), "ollama") || CONTAINS(STR(?reference_URL), "gpt"), ?reference_URL, "") AS ?reference_URL_model
194
+ # )
195
+ # BIND(
196
+ # IF(!(CONTAINS(STR(?reference_URL), "ollama") || CONTAINS(STR(?reference_URL), "gpt")), ?reference_URL, "") AS ?reference_URL_source
197
+ # )
198
+ # }
199
+ # FILTER(?reference_URL_source != "")
200
+
201
+ # SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
202
+ # }
203
+ # """
204
+
205
+
206
+ # designer_fashion_director_question2 = "In which fashion house did Alessandro Michele work as a creative director?"
207
+ # designer_fashion_director_query2 = """PREFIX wbt: <https://fashionwiki.wikibase.cloud/prop/direct/>
208
+ # PREFIX wb: <https://fashionwiki.wikibase.cloud/entity/>
209
+ # PREFIX pq: <https://fashionwiki.wikibase.cloud/prop/qualifier/>
210
+ # PREFIX pr: <https://fashionwiki.wikibase.cloud/prop/reference/>
211
+ # PREFIX ps: <https://fashionwiki.wikibase.cloud/prop/statement/>
212
+ # PREFIX p: <https://fashionwiki.wikibase.cloud/prop/>
213
+ # PREFIX prov: <http://www.w3.org/ns/prov#>
214
+
215
+ # SELECT
216
+ # ?fashion_houseLabel ?creative_directorLabel (COALESCE(YEAR(?start_time), YEAR(?point_time), YEAR(?inception)) AS ?start_year) (YEAR(?end_time) AS ?end_year) ?title ?statement ?reference_URL_source
217
+ # WHERE {
218
+ # # Fashion designer identified by name
219
+ # ?creative_director wbt:P2 wb:Q5.
220
+ # { ?creative_director rdfs:label "Alessandro Michele"@en.} # Match label
221
+ # UNION
222
+ # { ?creative_director skos:altLabel "Alessandro Michele"@en. } # Match alias
223
+
224
+ # # Link through designer employed (P29) property for the fashion house - the property for designer employment is P30
225
+ # {
226
+ # ?fashion_house p:P29 ?statement.
227
+ # ?statement ps:P29 ?creative_director.
228
+
229
+ # # Optional qualifiers for P29 regarding the time frame
230
+ # OPTIONAL { ?statement pq:P15 ?start_time. }
231
+ # OPTIONAL { ?statement pq:P28 ?point_time. }
232
+ # OPTIONAL { ?statement pq:P16 ?end_time. }
233
+ # OPTIONAL { ?statement pq:P25 ?title. }
234
+ # OPTIONAL { ?fashion_house wbt:P11 ?inception. }
235
+
236
+
237
+ # # Retrieve references for P29
238
+ # OPTIONAL {
239
+ # ?statement prov:wasDerivedFrom ?reference.
240
+ # ?reference pr:P24 ?reference_URL.
241
+ # BIND(
242
+ # IF(CONTAINS(STR(?reference_URL), "ollama") || CONTAINS(STR(?reference_URL), "gpt"), ?reference_URL, "") AS ?reference_URL_model
243
+ # )
244
+ # BIND(
245
+ # IF(!(CONTAINS(STR(?reference_URL), "ollama") || CONTAINS(STR(?reference_URL), "gpt")), ?reference_URL, "") AS ?reference_URL_source
246
+ # )
247
+ # }
248
+ # }
249
+ # FILTER (
250
+ # REGEX(?title, "director", "i") ||
251
+ # REGEX(?title, "head designer", "i") ||
252
+ # REGEX(?title, "chief", "i") ||
253
+ # REGEX(?title, "founder", "i")
254
+ # )
255
+ # FILTER(?reference_URL_source != "")
256
+
257
+ # # Retrieve labels
258
+ # SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
259
+ # } ORDER BY ?start_year """
260
+
261
+ # country_designer_question = "Which designers are from Italy ?"
262
+ # country_designer_query = """PREFIX wbt: <https://fashionwiki.wikibase.cloud/prop/direct/>
263
+ # PREFIX wb: <https://fashionwiki.wikibase.cloud/entity/>
264
+ # PREFIX pq: <https://fashionwiki.wikibase.cloud/prop/qualifier/>
265
+ # PREFIX pr: <https://fashionwiki.wikibase.cloud/prop/reference/>
266
+ # PREFIX ps: <https://fashionwiki.wikibase.cloud/prop/statement/>
267
+ # PREFIX p: <https://fashionwiki.wikibase.cloud/prop/>
268
+ # PREFIX prov: <http://www.w3.org/ns/prov#>
269
+
270
+ # SELECT ?fashion_designerLabel (SAMPLE(?statement) AS ?statement)
271
+ # (SAMPLE(?reference_URL) AS ?reference_URL) WHERE {
272
+ # # Restrict to designers who are instances of fashion designer (Q5)
273
+
274
+ # ?fashion_designer wbt:P2 wb:Q5.
275
+
276
+ # # Access the statement for the country relationship
277
+ # ?fashion_designer p:P6 ?statement.
278
+ # ?statement ps:P6 ?country.
279
+ # { ?country rdfs:label "Italy"@en.} # Match label
280
+ # UNION
281
+ # { ?country skos:altLabel "Italy"@en. } # Match alias
282
+
283
+ # # Retrieve references from the statement
284
+ # OPTIONAL {
285
+ # ?statement prov:wasDerivedFrom ?reference.
286
+ # ?reference pr:P24 ?reference_URL.
287
+ # }
288
+
289
+ # # Retrieve labels for the fashion designer
290
+ # SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
291
+ # }
292
+ # GROUP BY ?fashion_designerLabel
293
+ # ORDER BY ?fashion_designerLabel """
294
+
295
+ # country_designer_query = """PREFIX wbt: <https://fashionwiki.wikibase.cloud/prop/direct/>
296
+ # PREFIX wb: <https://fashionwiki.wikibase.cloud/entity/>
297
+ # PREFIX pq: <https://fashionwiki.wikibase.cloud/prop/qualifier/>
298
+ # PREFIX pr: <https://fashionwiki.wikibase.cloud/prop/reference/>
299
+ # PREFIX ps: <https://fashionwiki.wikibase.cloud/prop/statement/>
300
+ # PREFIX p: <https://fashionwiki.wikibase.cloud/prop/>
301
+ # PREFIX prov: <http://www.w3.org/ns/prov#>
302
+
303
+ # SELECT ?fashion_designerLabel (SAMPLE(?reference_URL) AS ?reference_URL) {
304
+ # # Restrict to designers who are instances of fashion designer (Q5)
305
+
306
+ # ?fashion_designer wbt:P2 wb:Q5.
307
+ # ?fashion_designer wbt:P6 ?country.
308
+ # ?fashion_designer p:P6 ?statement.
309
+ # { ?country rdfs:label "Italy"@en.} # Match label
310
+ # UNION
311
+ # { ?country skos:altLabel "Italy"@en. } # Match alias
312
+
313
+
314
+ # # Retrieve references from the statement
315
+ # OPTIONAL {
316
+ # ?statement prov:wasDerivedFrom ?reference.
317
+ # ?reference pr:P24 ?reference_URL.
318
+ # }
319
+
320
+ # # Retrieve labels for the fashion designer
321
+ # SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
322
+ # }
323
+ # GROUP BY ?fashion_designerLabel
324
+ # ORDER BY ?fashion_designerLabel """
325
+
326
+
327
+ # designer_order_fashion_collection_question = "Which fashion collections did Alessandro Michele work on?"
328
+ # designer_order_fashion_collection_query = """PREFIX wbt: <https://fashionwiki.wikibase.cloud/prop/direct/>
329
+ # PREFIX wb: <https://fashionwiki.wikibase.cloud/entity/>
330
+ # PREFIX pq: <https://fashionwiki.wikibase.cloud/prop/qualifier/>
331
+ # PREFIX pr: <https://fashionwiki.wikibase.cloud/prop/reference/>
332
+ # PREFIX ps: <https://fashionwiki.wikibase.cloud/prop/statement/>
333
+ # PREFIX p: <https://fashionwiki.wikibase.cloud/prop/>
334
+ # PREFIX prov: <http://www.w3.org/ns/prov#>
335
+
336
+ # SELECT ?fashion_houseLabel
337
+ # (COALESCE(YEAR(?start_time), YEAR(?point_time), YEAR(?inception)) AS ?start_year)
338
+ # (YEAR(?end_time) AS ?end_year)
339
+ # ?title ?reference_URL_source ?statement ?fashion_collectionLabel ?image_url
340
+ # (YEAR(?fashion_year) as ?year ) ?fashion_seasonLabel ?categoryLabel WHERE {
341
+ # # Designer linked to fashion house through roles or founded_by
342
+ # ?fashion_designer wbt:P2 wb:Q5.
343
+ # { ?fashion_designer rdfs:label "Alessandro Michele"@en.} # Match label
344
+ # UNION
345
+ # { ?fashion_designer skos:altLabel "Alessandro Michele"@en. } # Match alias
346
+
347
+
348
+ # # Link through "creative director" or other roles
349
+ # ?fashion_designer p:P10 ?statement_designer.
350
+ # ?statement_designer ps:P10 ?fashion_house.
351
+ # OPTIONAL { ?statement_designer pq:P15 ?start_time. }
352
+ # OPTIONAL { ?statement_designer pq:P28 ?point_time. }
353
+ # OPTIONAL { ?statement_designer pq:P16 ?end_time. }
354
+ # OPTIONAL { ?statement_designer pq:P25 ?title. }
355
+ # OPTIONAL { ?fashion_house wbt:P11 ?inception. }
356
+ # FILTER (
357
+ # REGEX(?title, "director", "i") ||
358
+ # REGEX(?title, "head designer", "i") ||
359
+ # REGEX(?title, "chief","i") ||
360
+ # REGEX(?title, "founder","i")
361
+ # )
362
+
363
+ # ?fashion_house p:P31 ?statement.
364
+ # ?statement ps:P31 ?fashion_collection.
365
+ # OPTIONAL {?fashion_collection wbt:P28 ?fashion_year.}
366
+ # OPTIONAL { ?fashion_collection wbt:P32 ?fashion_season. }
367
+ # OPTIONAL {?fashion_collection wbt:P38 ?category.}
368
+
369
+ # OPTIONAL {?statement pq:P35 ?image_url.}
370
+ # OPTIONAL {?statement pq:P37 ?fashion_date.}
371
+
372
+
373
+ # # Use the adjusted fashion year in the FILTER condition
374
+ # FILTER(
375
+ # (YEAR(?start_time) <= YEAR(?fashion_year) && (!BOUND(?end_time) || YEAR(?end_time) >= YEAR(?fashion_year))) ||
376
+ # (YEAR(?point_time) <= YEAR(?fashion_year)) ||
377
+ # (REGEX(?title, "founder", "i") && YEAR(?inception) <= YEAR(?fashion_year))
378
+ # )
379
+
380
+ # # Retrieve references for the statement
381
+ # OPTIONAL {
382
+ # ?statement prov:wasDerivedFrom ?reference.
383
+ # ?reference pr:P24 ?reference_URL_source.
384
+ # }
385
+
386
+ # SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
387
+ # } ORDER BY ?year """
388
+
389
+
390
+ # education_most_popular_question = "What are the most popular educational institutions for fashion designers?"
391
+ # education_most_popular_query = """ PREFIX wbt: <https://fashionwiki.wikibase.cloud/prop/direct/>
392
+ # PREFIX wb: <https://fashionwiki.wikibase.cloud/entity/>
393
+ # PREFIX pq: <https://fashionwiki.wikibase.cloud/prop/qualifier/>
394
+ # PREFIX pr: <https://fashionwiki.wikibase.cloud/prop/reference/>
395
+ # PREFIX ps: <https://fashionwiki.wikibase.cloud/prop/statement/>
396
+ # PREFIX p: <https://fashionwiki.wikibase.cloud/prop/>
397
+ # PREFIX prov: <http://www.w3.org/ns/prov#>
398
+
399
+ # SELECT ?schoolLabel (COUNT(?fashion_designer) AS ?designer_count) WHERE {
400
+ # # Retrieve all fashion designers and their schools
401
+ # ?fashion_designer wbt:P9 ?school.
402
+
403
+ # SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
404
+ # }
405
+ # GROUP BY ?schoolLabel
406
+ # ORDER BY DESC(?designer_count) """
407
+
408
+ # brands_founded_question = Template("Which fashion houses were founded in $x")
409
+ # brands_founded_query = Template(""" PREFIX wbt: <https://fashionwiki.wikibase.cloud/prop/direct/>
410
+ # PREFIX wb: <https://fashionwiki.wikibase.cloud/entity/>
411
+ # PREFIX p: <https://fashionwiki.wikibase.cloud/prop/>
412
+
413
+ # SELECT ?fashion_houseLabel ?inception
414
+ # WHERE {
415
+ # ?fashion_house wbt:P2 wb:Q1.
416
+ # ?fashion_house wbt:P11 ?inception.
417
+
418
+
419
+ # FILTER(YEAR(?inception) = $x)
420
+
421
+ # SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
422
+ # }""")
423
+
424
+ # how_many_directors_per_fashion_house_question = "How many designers have worked for each fashion house as creative directors?"
425
+ # how_many_directors_per_fashion_house_query = """ PREFIX wbt: <https://fashionwiki.wikibase.cloud/prop/direct/>
426
+ # PREFIX wb: <https://fashionwiki.wikibase.cloud/entity/>
427
+ # PREFIX pq: <https://fashionwiki.wikibase.cloud/prop/qualifier/>
428
+ # PREFIX pr: <https://fashionwiki.wikibase.cloud/prop/reference/>
429
+ # PREFIX ps: <https://fashionwiki.wikibase.cloud/prop/statement/>
430
+ # PREFIX p: <https://fashionwiki.wikibase.cloud/prop/>
431
+ # PREFIX prov: <http://www.w3.org/ns/prov#>
432
+
433
+ # SELECT ?fashion_houseLabel (COUNT(DISTINCT ?fashion_designer) AS ?creative_director_count) WHERE {
434
+ # # Match fashion houses linked to designers via employer property
435
+ # ?fashion_designer p:P10 ?statement.
436
+ # ?statement ps:P10 ?fashion_house.
437
+
438
+ # # Filter for roles related to creative direction
439
+ # OPTIONAL { ?statement pq:P25 ?title. }
440
+ # FILTER (
441
+ # REGEX(?title, "creative director", "i") ||
442
+ # REGEX(?title, "head designer", "i") ||
443
+ # REGEX(?title, "chief", "i") ||
444
+ # REGEX(?title, "founder", "i")
445
+ # )
446
+
447
+ # SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
448
+ # }
449
+ # GROUP BY ?fashion_houseLabel
450
+ # ORDER BY DESC(?creative_director_count)
451
+ # """
452
+
453
+ # how_many_designers_per_fashion_house_question = "How many designers have worked for each fashion house?"
454
+ # how_many_designers_per_fashion_house_query = """ PREFIX wbt: <https://fashionwiki.wikibase.cloud/prop/direct/>
455
+ # PREFIX wb: <https://fashionwiki.wikibase.cloud/entity/>
456
+ # PREFIX pq: <https://fashionwiki.wikibase.cloud/prop/qualifier/>
457
+ # PREFIX pr: <https://fashionwiki.wikibase.cloud/prop/reference/>
458
+ # PREFIX ps: <https://fashionwiki.wikibase.cloud/prop/statement/>
459
+ # PREFIX p: <https://fashionwiki.wikibase.cloud/prop/>
460
+ # PREFIX prov: <http://www.w3.org/ns/prov#>
461
+
462
+ # SELECT ?fashion_houseLabel (COUNT(?designer) AS ?designer_count) WHERE {
463
+ # ?fashion_house wbt:P29 ?designer .
464
+
465
+ # SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
466
+ # }
467
+ # GROUP BY ?fashion_houseLabel
468
+ # ORDER BY DESC(?designer_count) """
469
+
470
+
471
+ # designers_multiple_houses_question = "Which designers have worked for more than one fashion house?"
472
+ # designers_multiple_houses_query = """PREFIX wbt: <https://fashionwiki.wikibase.cloud/prop/direct/>
473
+ # PREFIX wb: <https://fashionwiki.wikibase.cloud/entity/>
474
+ # PREFIX pq: <https://fashionwiki.wikibase.cloud/prop/qualifier/>
475
+ # PREFIX pr: <https://fashionwiki.wikibase.cloud/prop/reference/>
476
+ # PREFIX ps: <https://fashionwiki.wikibase.cloud/prop/statement/>
477
+ # PREFIX p: <https://fashionwiki.wikibase.cloud/prop/>
478
+ # PREFIX prov: <http://www.w3.org/ns/prov#>
479
+
480
+ # SELECT ?designerLabel WHERE {
481
+ # ?designer wbt:P10 ?house .
482
+ # ?designer wbt:P10 ?anotherHouse .
483
+ # SERVICE wikibase:label { bd:serviceParam wikibase:language 'en'. }
484
+ # }
485
+ # GROUP BY ?designerLabel
486
+ # HAVING (COUNT(?house) > 1)"""
487
+
488
+ # award_question = "Which designers won which awards?"
489
+ # award_query = """ PREFIX wbt: <https://fashionwiki.wikibase.cloud/prop/direct/>
490
+ # PREFIX wb: <https://fashionwiki.wikibase.cloud/entity/>
491
+ # PREFIX pq: <https://fashionwiki.wikibase.cloud/prop/qualifier/>
492
+ # PREFIX pr: <https://fashionwiki.wikibase.cloud/prop/reference/>
493
+ # PREFIX ps: <https://fashionwiki.wikibase.cloud/prop/statement/>
494
+ # PREFIX p: <https://fashionwiki.wikibase.cloud/prop/>
495
+ # PREFIX prov: <http://www.w3.org/ns/prov#>
496
+
497
+ # SELECT ?designerLabel ?awardLabel WHERE {
498
+ # ?designer wbt:P18 ?award .
499
+ # SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
500
+ # }"""
501
+
502
+ # fashion_houses_with_collections_question ="Which distinct fashion houses have at least a fashion collection?"
503
+ # fashion_houses_with_collections_query = """PREFIX wbt: <https://fashionwiki.wikibase.cloud/prop/direct/>
504
+ # PREFIX wb: <https://fashionwiki.wikibase.cloud/entity/>
505
+ # PREFIX pq: <https://fashionwiki.wikibase.cloud/prop/qualifier/>
506
+ # PREFIX pr: <https://fashionwiki.wikibase.cloud/prop/reference/>
507
+ # PREFIX ps: <https://fashionwiki.wikibase.cloud/prop/statement/>
508
+ # PREFIX p: <https://fashionwiki.wikibase.cloud/prop/>
509
+ # PREFIX prov: <http://www.w3.org/ns/prov#>
510
+
511
+ # SELECT DISTINCT ?houseLabel WHERE {
512
+ # ?house wbt:P31 ?collection .
513
+ # SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
514
+ # } """
515
+
516
+ # popular_year_inception_question = "In which years were the most fashion houses founded?"
517
+ # popular_year_inception_query = """PREFIX wbt: <https://fashionwiki.wikibase.cloud/prop/direct/>
518
+ # PREFIX wb: <https://fashionwiki.wikibase.cloud/entity/>
519
+ # PREFIX pq: <https://fashionwiki.wikibase.cloud/prop/qualifier/>
520
+ # PREFIX pr: <https://fashionwiki.wikibase.cloud/prop/reference/>
521
+ # PREFIX ps: <https://fashionwiki.wikibase.cloud/prop/statement/>
522
+ # PREFIX p: <https://fashionwiki.wikibase.cloud/prop/>
523
+
524
+ # SELECT ?year_inception (COUNT(DISTINCT ?fashion_house) AS ?count)
525
+ # WHERE {
526
+ # ?fashion_house wbt:P11 ?year.
527
+ # BIND(YEAR(?year) AS ?year_inception)
528
+ # }
529
+ # GROUP BY ?year_inception
530
+ # ORDER BY DESC(?count) """
531
+
532
+
533
+ # longest_serving_director_question = "Which fashion houses have had the longest-serving creative director?"
534
+ # longest_serving_director_query = """ PREFIX wbt: <https://fashionwiki.wikibase.cloud/prop/direct/>
535
+ # PREFIX wb: <https://fashionwiki.wikibase.cloud/entity/>
536
+ # PREFIX pq: <https://fashionwiki.wikibase.cloud/prop/qualifier/>
537
+ # PREFIX pr: <https://fashionwiki.wikibase.cloud/prop/reference/>
538
+ # PREFIX ps: <https://fashionwiki.wikibase.cloud/prop/statement/>
539
+ # PREFIX p: <https://fashionwiki.wikibase.cloud/prop/>
540
+ # PREFIX prov: <http://www.w3.org/ns/prov#>
541
+ # PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>
542
+ # PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
543
+
544
+ # SELECT ?fashion_houseLabel ?duration ?designerLabel
545
+ # WHERE {
546
+ # ?fashion_house p:P29 ?statement.
547
+ # ?statement ps:P29 ?designer.
548
+ # OPTIONAL { ?statement pq:P15 ?startTime. }
549
+ # OPTIONAL { ?statement pq:P16 ?endTime. }
550
+
551
+ # # Ensure we only calculate when both dates exist
552
+ # FILTER(BOUND(?startTime) && BOUND(?endTime))
553
+
554
+ # # Compute duration safely
555
+ # BIND(YEAR(?endTime) - YEAR(?startTime) AS ?duration)
556
+
557
+ # SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
558
+ # }
559
+ # ORDER BY DESC(?duration)"""
560
+
561
+ # houses_most_collections_question = "Which fashion houses have the most collections recorded in the database?"
562
+ # houses_most_collections_query = """ PREFIX wbt: <https://fashionwiki.wikibase.cloud/prop/direct/>
563
+ # PREFIX wb: <https://fashionwiki.wikibase.cloud/entity/>
564
+ # PREFIX pq: <https://fashionwiki.wikibase.cloud/prop/qualifier/>
565
+ # PREFIX pr: <https://fashionwiki.wikibase.cloud/prop/reference/>
566
+ # PREFIX ps: <https://fashionwiki.wikibase.cloud/prop/statement/>
567
+ # PREFIX p: <https://fashionwiki.wikibase.cloud/prop/>
568
+ # PREFIX prov: <http://www.w3.org/ns/prov#>
569
+
570
+ # SELECT ?fashionHouseLabel (COUNT(?collection) AS ?collection_count) WHERE {
571
+ # ?fashionHouse wbt:P31 ?collection .
572
+ # SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
573
+ # }
574
+ # GROUP BY ?fashionHouseLabel
575
+ # ORDER BY DESC(?collection_count)"""
576
+
577
+
578
+ # collections_sustainability_theme_question = "Which collections include sustainability as a key theme?"
579
+ # collections_sustainability_theme_query = """PREFIX wbt: <https://fashionwiki.wikibase.cloud/prop/direct/>
580
+ # PREFIX wb: <https://fashionwiki.wikibase.cloud/entity/>
581
+ # PREFIX pq: <https://fashionwiki.wikibase.cloud/prop/qualifier/>
582
+ # PREFIX pr: <https://fashionwiki.wikibase.cloud/prop/reference/>
583
+ # PREFIX ps: <https://fashionwiki.wikibase.cloud/prop/statement/>
584
+ # PREFIX p: <https://fashionwiki.wikibase.cloud/prop/>
585
+ # PREFIX prov: <http://www.w3.org/ns/prov#>
586
+
587
+ # SELECT ?collectionLabel ?fashion_houseLabel ?reference_URL WHERE {
588
+ # ?fashion_house p:P31 ?statement.
589
+ # ?statement ps:P31 ?collection.
590
+ # ?statement pq:P34 ?description .
591
+ # FILTER (regex(?description, "sustainability", "i"))
592
+ # # Retrieve references for the statement
593
+ # OPTIONAL {
594
+ # ?statement prov:wasDerivedFrom ?reference.
595
+ # ?reference pr:P24 ?reference_URL.
596
+ # }
597
+ # SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
598
+ # } """
599
+
600
+
601
+ # collections_jeans_question = "Which collections showcase products made with jeans?"
602
+ # collections_jeans_query = """PREFIX wbt: <https://fashionwiki.wikibase.cloud/prop/direct/>
603
+ # PREFIX wb: <https://fashionwiki.wikibase.cloud/entity/>
604
+ # PREFIX pq: <https://fashionwiki.wikibase.cloud/prop/qualifier/>
605
+ # PREFIX pr: <https://fashionwiki.wikibase.cloud/prop/reference/>
606
+ # PREFIX ps: <https://fashionwiki.wikibase.cloud/prop/statement/>
607
+ # PREFIX p: <https://fashionwiki.wikibase.cloud/prop/>
608
+ # PREFIX prov: <http://www.w3.org/ns/prov#>
609
+
610
+ # SELECT ?collectionLabel ?fashion_houseLabel ?reference_URL WHERE {
611
+ # ?fashion_house p:P31 ?statement.
612
+ # ?statement ps:P31 ?collection.
613
+ # ?statement pq:P34 ?description .
614
+ # FILTER (regex(?description, "jeans", "i"))
615
+ # # Retrieve references for the statement
616
+ # OPTIONAL {
617
+ # ?statement prov:wasDerivedFrom ?reference.
618
+ # ?reference pr:P24 ?reference_URL.
619
+ # }
620
+ # SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
621
+ # } """
622
+
623
+
624
+ # creative_directors_school_question = "To which school went most designers who later became creative directors of fashion houses?"
625
+ # creative_directors_school_query = """ PREFIX wbt: <https://fashionwiki.wikibase.cloud/prop/direct/>
626
+ # PREFIX wb: <https://fashionwiki.wikibase.cloud/entity/>
627
+ # PREFIX pq: <https://fashionwiki.wikibase.cloud/prop/qualifier/>
628
+ # PREFIX pr: <https://fashionwiki.wikibase.cloud/prop/reference/>
629
+ # PREFIX ps: <https://fashionwiki.wikibase.cloud/prop/statement/>
630
+ # PREFIX p: <https://fashionwiki.wikibase.cloud/prop/>
631
+ # PREFIX prov: <http://www.w3.org/ns/prov#>
632
+
633
+ # SELECT ?schoolLabel (COUNT(DISTINCT ?designer) AS ?designer_count) WHERE {
634
+ # ?designer p:P10 ?fashion_house .
635
+
636
+ # OPTIONAL { ?fashion_house pq:P25 ?title. }
637
+ # FILTER (
638
+ # REGEX(?title, "creative director", "i") ||
639
+ # REGEX(?title, "head designer", "i") ||
640
+ # REGEX(?title, "chief", "i") ||
641
+ # REGEX(?title, "founder", "i")
642
+ # )
643
+
644
+ # OPTIONAL { ?designer wbt:P9 ?school . }
645
+ # SERVICE wikibase:label { bd:serviceParam wikibase:language 'en'. }
646
+ # }
647
+ # GROUP BY ?schoolLabel
648
+ # ORDER BY DESC(?designer_count)"""
649
+
650
+ # fashion_houses_thematic_collection_question = "Which fashion houses had collections with a sustainability theme, and how many of them?"
651
+ # fashion_houses_thematic_collection_query = """PREFIX wbt: <https://fashionwiki.wikibase.cloud/prop/direct/>
652
+ # PREFIX wb: <https://fashionwiki.wikibase.cloud/entity/>
653
+ # PREFIX pq: <https://fashionwiki.wikibase.cloud/prop/qualifier/>
654
+ # PREFIX pr: <https://fashionwiki.wikibase.cloud/prop/reference/>
655
+ # PREFIX ps: <https://fashionwiki.wikibase.cloud/prop/statement/>
656
+ # PREFIX p: <https://fashionwiki.wikibase.cloud/prop/>
657
+ # PREFIX prov: <http://www.w3.org/ns/prov#>
658
+
659
+ # SELECT ?fashion_houseLabel (COUNT(DISTINCT ?collection) AS ?collection_count) WHERE {
660
+ # ?fashion_house p:P31 ?statement.
661
+ # ?statement ps:P31 ?collection.
662
+ # ?statement pq:P34 ?description .
663
+ # FILTER (regex(?description, "sustainability", "i"))
664
+ # # Retrieve references for the statement
665
+ # OPTIONAL {
666
+ # ?statement prov:wasDerivedFrom ?reference.
667
+ # ?reference pr:P24 ?reference_URL.
668
+ # }
669
+ # SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
670
+ # } GROUP BY ?fashion_houseLabel
671
+ # ORDER BY DESC(?collection_count) """
672
+
673
+
674
+ # questions_queries_dict = [ { "question": education_most_popular_question, "query": education_most_popular_query},
675
+ # { "question": how_many_designers_per_fashion_house_question, "query": how_many_designers_per_fashion_house_query},
676
+ # {"question": how_many_directors_per_fashion_house_question, "query": how_many_directors_per_fashion_house_query},
677
+ # {"question": designers_multiple_houses_question, "query":designers_multiple_houses_query },
678
+ # {"question": award_question, "query": award_question},
679
+ # {"question": fashion_houses_with_collections_question, "query": fashion_houses_with_collections_query},
680
+ # {"question": popular_year_inception_question, "query": popular_year_inception_query},
681
+ # {"question": longest_serving_director_question, "query": longest_serving_director_query},
682
+ # {"question": houses_most_collections_question, "query": houses_most_collections_query},
683
+ # {"question": collections_sustainability_theme_question, "query": collections_sustainability_theme_query},
684
+ # ]
685
+
686
+
687
+ # questions_queries_dict_entity = [{"question": fashion_house_directors_question, "query": fashion_house_directors_query},
688
+ # { "question": designer_fashion_house_directors_question, "query": designer_fashion_house_directors_query},
689
+ # { "question": country_designer_question, "query": country_designer_query},
690
+ # { "question": designer_order_fashion_collection_question, "query": designer_order_fashion_collection_query},
691
+ # { "question": designer_fashion_director_question2, "query": designer_fashion_director_query2},
692
+ # { "question": year_designers_birth_question, "query": year_designers_birth_query}]
693
+
694
+
695
+ # # Designers
696
+ # designers_born_in_year_question = "Which designers were born in year $x?"
697
+ # creative_directors_of_house_question = "Which designers have been creative directors of $x?"
698
+ # designers_multiple_houses_question = "Which designers have worked for more than one fashion house?"
699
+ # educated_at_school_question = "Which designers were educated at $x fashion school?"
700
+ # won_award_question = "Which designers have won the $x award?"
701
+ # launched_own_label_question = "Which designers launched their own fashion label?"
702
+ # worked_at_x_between_years_question = "Which designers worked at $x between year $y and $z?"
703
+ # designers_multiple_collaborations_question = "Which designers have collaborated with multiple fashion houses?"
704
+ # designers_lived_in_city_question = "Which designers have lived in $x city?"
705
+ # designers_active_decade_question = "Which designers were active during the $x decade?"
706
+
707
+ # # Fashion Houses
708
+ # designers_worked_for_house_question = "Which designers have worked for fashion house $x?"
709
+ # creative_directors_per_house_question = "How many designers have worked for each fashion house as creative directors?"
710
+ # houses_founded_in_year_question = "Which fashion houses were founded in year $x?"
711
+ # houses_most_director_changes_question = "Which fashion houses have undergone the most creative director changes?"
712
+ # longest_serving_director_question = "Which fashion houses have had the longest-serving creative director?"
713
+ # houses_collaborations_question = "Which fashion houses have collaborated with other fashion houses or brands?"
714
+ # houses_haute_couture_question = "Which fashion houses have produced haute couture collections?"
715
+ # houses_active_decade_question = "Which fashion houses were active during the $x decade?"
716
+ # houses_most_collections_question = "Which fashion houses have the most collections recorded in the database?"
717
+
718
+ # # Fashion Collections
719
+ # designer_worked_on_collections_question = "Which fashion collections did $x work on?"
720
+ # collections_inspired_by_theme_question = "Which fashion house produced a collection inspired by $x theme?"
721
+ # collections_high_critical_acclaim_question = "Which collections received the highest critical acclaim?"
722
+ # collections_historical_references_question = "Which collections feature references to historical fashion styles?"
723
+ # collections_sustainability_theme_question = "Which collections include sustainability as a key theme?"
724
+ # collections_per_house_per_year_question = "How many collections did each fashion house produce in year $x?"
725
+ # collections_avant_garde_question = "Which collections have been described as avant-garde?"
726
+ # collections_stylistic_similarity_question = "Which collections share stylistic similarities with $x?"
727
+ # collections_evolution_over_time_question = "How has the style of $x fashion house evolved over the years?"
728
+ # collections_shown_at_fashion_week_question = "Which collections were showcased at $x fashion week?"
729
+
730
+ # # Designers & Fashion Houses
731
+ # studied_then_director_question = "Which designers who studied at $x fashion school later became creative directors at $y fashion house?"
732
+ # worked_at_both_houses_question = "Which designers have worked at both $x and $y fashion houses?"
733
+ # launched_label_after_working_question = "Which designers who launched their own fashion labels had previously worked at $x fashion house?"
734
+ # won_award_then_worked_question = "Which designers who won the $x award also worked for $y fashion house?"
735
+ # lived_in_city_and_director_question = "Which designers who lived in $x city have worked as creative directors for $y fashion house?"
736
+ # worked_for_three_houses_question = "Which designers have worked for at least three different fashion houses during their career?"
737
+ # designed_for_two_brands_same_year_question = "Which designers who were creative directors at $x fashion house also designed collections for another brand in the same year?"
738
+ # creative_director_and_label_founder_question = "Which designers were both fashion house creative directors and independent label founders at the same time?"
739
+ # collaborated_with_two_houses_question = "Which designers have collaborated with both $x and $y fashion houses?"
740
+ # worked_at_x_before_y_question = "Which designers worked at $x fashion house before moving to $y?"
741
+
742
+ # # Designers & Collections
743
+ # designed_for_multiple_houses_same_season_question = "Which designers have designed collections for multiple fashion houses in the same season?"
744
+ # couture_and_ready_to_wear_question = "Which designers who specialized in haute couture have also designed ready-to-wear collections?"
745
+ # similar_theme_collections_question = "Which designers who worked on $x collection had previously worked on a similar-themed collection for another brand?"
746
+ # award_winner_inspired_by_history_question = "Which designers who have won an award have produced a collection inspired by $x historical period?"
747
+ # alma_mater_referenced_in_collection_question = "Which designers who studied at $x school designed a collection that referenced their alma mater?"
748
+
749
+ # # Fashion Houses & Collections
750
+ # same_historical_period_collections_question = "Which fashion houses have produced collections inspired by the same historical period?"
751
+ # collaborations_with_artists_question = "Which fashion houses have produced collections featuring collaborations with artists from $x field (e.g., photography, sculpture, film)?"
752
+ # change_director_different_collection_question = "Which fashion houses have changed creative directors and immediately released a significantly different collection?"
753
+ # avant_garde_and_minimalist_question = "Which fashion houses have produced both avant-garde and minimalist collections?"
754
+ # inspired_by_other_brands_question = "Which fashion houses have produced a collection inspired by a previous designer’s work from another brand?"
755
+
756
+ # # Multi-Category (Designers, Houses, Collections)
757
+ # designer_worked_house_then_influenced_question = "Which designers who worked for $x fashion house also designed a collection influenced by $y movement?"
758
+ # designer_lived_in_city_referenced_collection_question = "Which designers who lived in $x city during year $y produced a collection with references to that place?"
759
+ # multiple_designers_same_collection_question = "Which fashion houses have had at least three designers contribute to the same collection?"
760
+ # worked_elsewhere_during_collection_question = "Which collections were created by a designer who was also working at another fashion house at the time?"
761
+ # education_influenced_collection_question = "Which fashion collections were influenced by a designer’s education at $x fashion school?"
762
+
763
+ # # Designers & Fashion Houses
764
+ # studied_then_director_question = "Which designers who studied at $x fashion school later became creative directors at $y fashion house?"
765
+ # worked_at_both_houses_question = "Which designers have worked at both $x and $y fashion houses?"
766
+ # launched_label_after_working_question = "Which designers who launched their own fashion labels had previously worked at $x fashion house?"
767
+ # won_award_then_worked_question = "Which designers who won the $x award also worked for $y fashion house?"
768
+ # lived_in_city_and_director_question = "Which designers who lived in $x city have worked as creative directors for $y fashion house?"
769
+ # worked_for_three_houses_question = "Which designers have worked for at least three different fashion houses during their career?"
770
+ # designed_for_two_brands_same_year_question = "Which designers who were creative directors at $x fashion house also designed collections for another brand in the same year?"
771
+ # creative_director_and_label_founder_question = "Which designers were both fashion house creative directors and independent label founders at the same time?"
772
+ # collaborated_with_two_houses_question = "Which designers have collaborated with both $x and $y fashion houses?"
773
+ # worked_at_x_before_y_question = "Which designers worked at $x fashion house before moving to $y?"
774
+
775
+ # # Designers & Collections
776
+ # designed_for_multiple_houses_same_season_question = "Which designers have designed collections for multiple fashion houses in the same season?"
777
+ # couture_and_ready_to_wear_question = "Which designers who specialized in haute couture have also designed ready-to-wear collections?"
778
+ # similar_theme_collections_question = "Which designers who worked on $x collection had previously worked on a similar-themed collection for another brand?"
779
+ # award_winner_inspired_by_history_question = "Which designers who have won an award have produced a collection inspired by $x historical period?"
780
+ # alma_mater_referenced_in_collection_question = "Which designers who studied at $x school designed a collection that referenced their alma mater?"
781
+
782
+ # # Fashion Houses & Collections
783
+ # same_historical_period_collections_question = "Which fashion houses have produced collections inspired by the same historical period?"
784
+ # collaborations_with_artists_question = "Which fashion houses have produced collections featuring collaborations with artists from $x field (e.g., photography, sculpture, film)?"
785
+ # change_director_different_collection_question = "Which fashion houses have changed creative directors and immediately released a significantly different collection?"
786
+ # avant_garde_and_minimalist_question = "Which fashion houses have produced both avant-garde and minimalist collections?"
787
+ # inspired_by_other_brands_question = "Which fashion houses have produced a collection inspired by a previous designer’s work from another brand?"
788
+
789
+ # # Multi-Category (Designers, Houses, Collections)
790
+ # designer_worked_house_then_influenced_question = "Which designers who worked for $x fashion house also designed a collection influenced by $y movement?"
791
+ # designer_lived_in_city_referenced_collection_question = "Which designers who lived in $x city during year $y produced a collection with references to that place?"
792
+ # multiple_designers_same_collection_question = "Which fashion houses have had at least three designers contribute to the same collection?"
793
+ # worked_elsewhere_during_collection_question = "Which collections were created by a designer who was also working at another fashion house at the time?"
794
+ # education_influenced_collection_question = "Which fashion collections were influenced by a designer’s education at $x fashion school?"
795
+
796
+
797
  import sys
798
  import os
799
  sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
 
801
 
802
 
803
 
804
+ fashion_collection_images_question = Template("Images of collections produced by $x")
805
+ fashion_collection_images_query = Template("""
806
  PREFIX wbt: <https://fashionwiki.wikibase.cloud/prop/direct/>
807
  PREFIX wb: <https://fashionwiki.wikibase.cloud/entity/>
808
  PREFIX pq: <https://fashionwiki.wikibase.cloud/prop/qualifier/>
 
813
 
814
  SELECT ?statement ?fashion_collectionLabel ?image_url ?reference_URL
815
  ?fashion_seasonLabel (YEAR(?fashion_year) AS ?year) ?categoryLabel WHERE {
816
+ { ?fashion_house rdfs:label $x@en.} # Match label
817
  UNION
818
+ { ?fashion_house skos:altLabel $x@en. } # Match alias
819
 
820
 
821
  ?fashion_house p:P31 ?statement.
 
835
  }
836
 
837
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en". } }
838
+ """)
839
 
840
+ year_designers_birth_question = Template("Which designers were born in $x?")
841
+ year_designers_birth_query = Template("""
842
  PREFIX wbt: <https://fashionwiki.wikibase.cloud/prop/direct/>
843
  PREFIX wb: <https://fashionwiki.wikibase.cloud/entity/>
844
  PREFIX ps: <https://fashionwiki.wikibase.cloud/prop/statement/>
 
849
 
850
  SELECT ?designerLabel ?birthdate WHERE {
851
  ?designer wbt:P3 ?birthdate .
852
+ FILTER (YEAR(?birthdate) = $x)
853
 
854
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
855
+ } """)
856
 
857
+ fashion_house_directors_question = Template("Which designers have been creative directors of $x ?")
858
+ fashion_house_directors_query = Template("""
859
  PREFIX wbt: <https://fashionwiki.wikibase.cloud/prop/direct/>
860
  PREFIX wb: <https://fashionwiki.wikibase.cloud/entity/>
861
  PREFIX pq: <https://fashionwiki.wikibase.cloud/prop/qualifier/>
 
870
  WHERE {
871
  # Fashion house identified by brand name
872
  ?fashion_house wbt:P2 wb:Q1.
873
+ { ?fashion_house rdfs:label $x@en.} # Match label
874
  UNION
875
+ { ?fashion_house skos:altLabel $x@en. } # Match alias
876
 
877
  # Link through designer employed (P29) property for the fashion house - the property for designer employment is P10
878
  {
 
935
  FILTER(?reference_URL_source != "")
936
  # Retrieve labels
937
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
938
+ } ORDER BY ?start_year """)
939
 
940
 
941
 
942
+ designer_fashion_house_directors_question = Template("In which fashion house did $x work as a creative director?")
943
+ designer_fashion_house_directors_query = Template("""
944
  PREFIX wbt: <https://fashionwiki.wikibase.cloud/prop/direct/>
945
  PREFIX wb: <https://fashionwiki.wikibase.cloud/entity/>
946
  PREFIX pq: <https://fashionwiki.wikibase.cloud/prop/qualifier/>
 
956
  WHERE {
957
  # Designer linked to fashion house through roles or founded_by
958
  ?fashion_designer wbt:P2 wb:Q5.
959
+ { ?fashion_designer rdfs:label $x@en.} # Match label
960
  UNION
961
+ { ?fashion_designer skos:altLabel $x@en. } # Match alias
962
 
963
  # Link through employer (P10)
964
  ?fashion_designer p:P10 ?statement.
 
996
 
997
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
998
  }
999
+ """)
1000
 
1001
 
1002
+ designer_fashion_director_question2 = Template("In which fashion house did $x work as a creative director?")
1003
+ designer_fashion_director_query2 = Template("""PREFIX wbt: <https://fashionwiki.wikibase.cloud/prop/direct/>
1004
  PREFIX wb: <https://fashionwiki.wikibase.cloud/entity/>
1005
  PREFIX pq: <https://fashionwiki.wikibase.cloud/prop/qualifier/>
1006
  PREFIX pr: <https://fashionwiki.wikibase.cloud/prop/reference/>
 
1013
  WHERE {
1014
  # Fashion designer identified by name
1015
  ?creative_director wbt:P2 wb:Q5.
1016
+ { ?creative_director rdfs:label $x@en.} # Match label
1017
  UNION
1018
+ { ?creative_director skos:altLabel $x@en. } # Match alias
1019
 
1020
  # Link through designer employed (P29) property for the fashion house - the property for designer employment is P30
1021
  {
 
1052
 
1053
  # Retrieve labels
1054
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
1055
+ } ORDER BY ?start_year """)
1056
 
1057
+ country_designer_question = Template("Which designers are from $x ?")
1058
+ country_designer_query = Template("""PREFIX wbt: <https://fashionwiki.wikibase.cloud/prop/direct/>
1059
  PREFIX wb: <https://fashionwiki.wikibase.cloud/entity/>
1060
  PREFIX pq: <https://fashionwiki.wikibase.cloud/prop/qualifier/>
1061
  PREFIX pr: <https://fashionwiki.wikibase.cloud/prop/reference/>
 
1072
  # Access the statement for the country relationship
1073
  ?fashion_designer p:P6 ?statement.
1074
  ?statement ps:P6 ?country.
1075
+ { ?country rdfs:label $x@en.} # Match label
1076
  UNION
1077
+ { ?country skos:altLabel $x@en. } # Match alias
1078
 
1079
  # Retrieve references from the statement
1080
  OPTIONAL {
 
1086
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
1087
  }
1088
  GROUP BY ?fashion_designerLabel
1089
+ ORDER BY ?fashion_designerLabel """)
1090
 
1091
+ country_designer_query = Template("""PREFIX wbt: <https://fashionwiki.wikibase.cloud/prop/direct/>
1092
  PREFIX wb: <https://fashionwiki.wikibase.cloud/entity/>
1093
  PREFIX pq: <https://fashionwiki.wikibase.cloud/prop/qualifier/>
1094
  PREFIX pr: <https://fashionwiki.wikibase.cloud/prop/reference/>
 
1102
  ?fashion_designer wbt:P2 wb:Q5.
1103
  ?fashion_designer wbt:P6 ?country.
1104
  ?fashion_designer p:P6 ?statement.
1105
+ { ?country rdfs:label $x@en.} # Match label
1106
  UNION
1107
+ { ?country skos:altLabel $x@en. } # Match alias
1108
 
1109
 
1110
  # Retrieve references from the statement
 
1117
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
1118
  }
1119
  GROUP BY ?fashion_designerLabel
1120
+ ORDER BY ?fashion_designerLabel """)
1121
 
1122
 
1123
+ designer_order_fashion_collection_question = Template("Which fashion collections did $x work on?")
1124
+ designer_order_fashion_collection_query = Template("""PREFIX wbt: <https://fashionwiki.wikibase.cloud/prop/direct/>
1125
  PREFIX wb: <https://fashionwiki.wikibase.cloud/entity/>
1126
  PREFIX pq: <https://fashionwiki.wikibase.cloud/prop/qualifier/>
1127
  PREFIX pr: <https://fashionwiki.wikibase.cloud/prop/reference/>
 
1136
  (YEAR(?fashion_year) as ?year ) ?fashion_seasonLabel ?categoryLabel WHERE {
1137
  # Designer linked to fashion house through roles or founded_by
1138
  ?fashion_designer wbt:P2 wb:Q5.
1139
+ { ?fashion_designer rdfs:label $x@en.} # Match label
1140
  UNION
1141
+ { ?fashion_designer skos:altLabel $x@en. } # Match alias
1142
 
1143
 
1144
  # Link through "creative director" or other roles
 
1180
  }
1181
 
1182
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
1183
+ } ORDER BY ?year """)
1184
 
1185
 
1186
  education_most_popular_question = "What are the most popular educational institutions for fashion designers?"
 
1479
  {"question": collections_sustainability_theme_question, "query": collections_sustainability_theme_query},
1480
  ]
1481
 
1482
+ questions_queries_dict_entity = [ {"question": fashion_house_directors_question.substitute({ "x": f"{"Chanel"}"}), "query": fashion_house_directors_query.substitute({ "x": f"'{"Chanel"}'"})},
1483
+ { "question": designer_fashion_house_directors_question.substitute({ "x": f"{"Alexander McQueen"}"}), "query": designer_fashion_house_directors_query.substitute({ "x": f"'{"Alexander McQueen"}'"})},
1484
+ {"question": country_designer_question.substitute({ "x": f"{"Italy"}"}), "query": country_designer_query.substitute({ "x": f"'{"Italy"}'"})},
1485
+ { "question": designer_order_fashion_collection_question.substitute({ "x": f"{"Alexander McQueen"}"}), "query": designer_order_fashion_collection_query.substitute({ "x": f"'{"Alexander McQueen"}'"})},
1486
+ {"question": designer_fashion_director_question2.substitute({ "x": f"{"Alexander McQueen"}"}), "query": designer_fashion_director_query2.substitute({ "x": f"'{"Alexander McQueen"}'"})},
1487
+ { "question": year_designers_birth_question.substitute({ "x": 1970}), "query": year_designers_birth_query.substitute({ "x": 1970})},
1488
+ { "question": fashion_collection_images_question.substitute({ "x": f"{"Chanel"}"}), "query": fashion_collection_images_query.substitute({ "x": f"'{"Chanel"}'"})}]
1489
 
1490
 
1491
  # Designers
 
1591
 
1592
 
1593
 
1594
+
src/sparql_query_wikibase.py CHANGED
File without changes
src/use_llm.py CHANGED
@@ -1,42 +1,80 @@
1
 
2
- from huggingface_hub import InferenceClient
3
- import os
4
 
5
- # Use a Hugging Face inference endpoint like "google/gemma-1.1-7b-it"
6
- # You must have access to this model (either public or via token)
7
 
8
- HUGGINGFACE_API_TOKEN = os.getenv("HF_TOKEN") # Add this in your HF Space's secret settings
9
- DEFAULT_MODEL = "google/gemma-1.1-7b-it"
10
 
11
- client = InferenceClient(DEFAULT_MODEL, token=HUGGINGFACE_API_TOKEN)
12
 
13
- def send_chat_prompt(prompt: str, model: str, system_prompt: str) -> str:
14
- full_prompt = f"<|start_of_turn|>system\n{system_prompt}<|end_of_turn|>\n" \
15
- f"<|start_of_turn|>user\n{prompt}<|end_of_turn|>\n" \
16
- f"<|start_of_turn|>assistant\n"
17
 
18
- response = client.text_generation(
19
- prompt=full_prompt,
20
- max_new_tokens=500,
21
- temperature=0.5,
22
- stop_sequences=["<|end_of_turn|>"]
23
- )
24
 
25
- return response.strip()
26
 
27
- def main_generate(prompt, model=DEFAULT_MODEL, system_prompt="You are a helpful assistant that generates SPARQL queries."):
28
- response = send_chat_prompt(prompt, model, system_prompt)
29
- response = response.replace('```', '').replace('json', '').strip()
30
- return response
 
 
 
 
 
 
 
 
 
31
 
 
 
 
 
 
32
 
33
 
34
- from sentence_transformers import SentenceTransformer
35
 
36
- model = SentenceTransformer("thenlper/gte-large") # downloaded from Hugging Face
 
 
 
 
37
 
38
  def get_embeddings(texts):
39
- if isinstance(texts, str):
40
- texts = [texts]
41
- embeddings = model.encode(texts, convert_to_numpy=True)
42
- return embeddings
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
 
2
+ # from huggingface_hub import InferenceClient
3
+ # import os
4
 
5
+ # # Use a Hugging Face inference endpoint like "google/gemma-1.1-7b-it"
6
+ # # You must have access to this model (either public or via token)
7
 
8
+ # HUGGINGFACE_API_TOKEN = os.getenv("HF_TOKEN") # Add this in your HF Space's secret settings
9
+ # DEFAULT_MODEL = "google/gemma-1.1-7b-it"
10
 
11
+ # client = InferenceClient(DEFAULT_MODEL, token=HUGGINGFACE_API_TOKEN)
12
 
13
+ # def send_chat_prompt(prompt: str, model: str, system_prompt: str) -> str:
14
+ # full_prompt = f"<|start_of_turn|>system\n{system_prompt}<|end_of_turn|>\n" \
15
+ # f"<|start_of_turn|>user\n{prompt}<|end_of_turn|>\n" \
16
+ # f"<|start_of_turn|>assistant\n"
17
 
18
+ # response = client.text_generation(
19
+ # prompt=full_prompt,
20
+ # max_new_tokens=500,
21
+ # temperature=0.5,
22
+ # stop_sequences=["<|end_of_turn|>"]
23
+ # )
24
 
25
+ # return response.strip()
26
 
27
+ # def main_generate(prompt, model=DEFAULT_MODEL, system_prompt="You are a helpful assistant that generates SPARQL queries."):
28
+ # response = send_chat_prompt(prompt, model, system_prompt)
29
+ # response = response.replace('```', '').replace('json', '').strip()
30
+ # return response
31
+
32
+
33
+
34
+
35
+
36
+
37
+ # from sentence_transformers import SentenceTransformer
38
+
39
+ # model = SentenceTransformer("thenlper/gte-large") # downloaded from Hugging Face
40
 
41
+ # def get_embeddings(texts):
42
+ # if isinstance(texts, str):
43
+ # texts = [texts]
44
+ # embeddings = model.encode(texts, convert_to_numpy=True)
45
+ # return embeddings
46
 
47
 
 
48
 
49
+
50
+
51
+
52
+ import ollama
53
+ import openai
54
 
55
  def get_embeddings(texts):
56
+ response = ollama.embed(model="mxbai-embed-large", input=texts)
57
+ embeddings = response["embeddings"]
58
+ return embeddings
59
+
60
+
61
+ openai_api_key = "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"
62
+ #generate
63
+ def send_chat_prompt(prompt, model, system_prompt ):
64
+ client = openai.OpenAI(
65
+ base_url="http://localhost:11434/v1" if not "gpt" in model else None,
66
+ api_key= "ollama" if not "gpt" in model else openai_api_key)
67
+ resp = client.chat.completions.create(
68
+ model=model,
69
+ temperature = 0.5 ,
70
+ messages=[
71
+ {"role": "system", "content": system_prompt},
72
+ {"role": "user", "content": prompt}])
73
+ response = resp.choices[0].message.content
74
+ return response
75
+
76
+ def main_generate(prompt,model, system_prompt):
77
+ response = send_chat_prompt(prompt,model, system_prompt)
78
+ response = response.replace('```','').replace('json','')
79
+ #print(f" {model} Response:", response)
80
+ return response
src/visual_qa.py CHANGED
@@ -8,12 +8,16 @@ os.environ["TOKENIZERS_PARALLELISM"] = "false"
8
 
9
  from datasets import load_dataset
10
  import chromadb
 
 
11
 
12
  from datetime import datetime
13
 
14
  def initialize_collection(collection_name="clip_image_embeddings"):
15
  # Initialize ChromaDB client (PersistentClient stores embeddings between runs)
16
  client = chromadb.PersistentClient(path="./chroma_db") # Change path if needed
 
 
17
 
18
  # Get a list of existing collection names
19
  existing_collections = [col for col in client.list_collections()] # v0.6.0 change
@@ -86,7 +90,7 @@ def main_text_retrieve_images(text, result_query=None, n_retrieved=5):
86
 
87
  # Convert to pandas DataFrame
88
  df_emb = full_dataset.to_pandas()
89
- #print(df_emb.head()) # Debugging statement
90
  df_emb = df_emb.drop_duplicates(subset='image_urls')
91
  df_emb['fashion_clip_image'] = df_emb['fashion_clip_image'].apply(lambda x: x[0] if type(x) == list else None)
92
  df_emb['image_url'] = df_emb['image_urls'].apply(lambda x: x[0] if x else None)
@@ -124,3 +128,4 @@ def main_text_retrieve_images(text, result_query=None, n_retrieved=5):
124
  # text = "dress"
125
  # result = main_text_retrieve_images(text)
126
  # print(result)
 
 
8
 
9
  from datasets import load_dataset
10
  import chromadb
11
+ from chromadb import Client
12
+ from chromadb.config import Settings
13
 
14
  from datetime import datetime
15
 
16
  def initialize_collection(collection_name="clip_image_embeddings"):
17
  # Initialize ChromaDB client (PersistentClient stores embeddings between runs)
18
  client = chromadb.PersistentClient(path="./chroma_db") # Change path if needed
19
+ #client = chromadb.EphemeralClient()
20
+
21
 
22
  # Get a list of existing collection names
23
  existing_collections = [col for col in client.list_collections()] # v0.6.0 change
 
90
 
91
  # Convert to pandas DataFrame
92
  df_emb = full_dataset.to_pandas()
93
+ print(df_emb.head()) # Debugging statement
94
  df_emb = df_emb.drop_duplicates(subset='image_urls')
95
  df_emb['fashion_clip_image'] = df_emb['fashion_clip_image'].apply(lambda x: x[0] if type(x) == list else None)
96
  df_emb['image_url'] = df_emb['image_urls'].apply(lambda x: x[0] if x else None)
 
128
  # text = "dress"
129
  # result = main_text_retrieve_images(text)
130
  # print(result)
131
+
src1/__pycache__/generate_queries_alternative.cpython-312.pyc ADDED
Binary file (27.7 kB). View file
 
src/__pycache__/questions_queries.cpython-310.pyc → src1/__pycache__/questions_queries.cpython-312.pyc RENAMED
Binary files a/src/__pycache__/questions_queries.cpython-310.pyc and b/src1/__pycache__/questions_queries.cpython-312.pyc differ
 
src1/__pycache__/visual_qa.cpython-312.pyc ADDED
Binary file (5.49 kB). View file
 
src1/generate_queries_alternative.py ADDED
@@ -0,0 +1,619 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from src1.questions_queries import *
2
+ import time
3
+ import ollama
4
+ import uuid
5
+ import chromadb
6
+ import openai
7
+ openai_api_key = "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"
8
+
9
+ import spacy
10
+ nlp = spacy.load("en_core_web_sm")
11
+ import os
12
+ #os.environ["TOKENIZERS_PARALLELISM"] = "false"
13
+
14
+ wikibase_properties_id = {'instance of': 'P2',
15
+ 'reference URL': 'P24',
16
+ 'start time': 'P15',
17
+ 'end time': 'P16',
18
+ 'occupation title': 'P25',
19
+ 'educated at': 'P9',
20
+ 'employer': 'P10',
21
+ 'work location': 'P7',
22
+ 'award received': 'P18',
23
+ 'point in time': 'P28',
24
+ 'exact match': 'P23',
25
+ 'date of birth': 'P3',
26
+ 'place of birth': 'P4',
27
+ 'date of death': 'P5',
28
+ 'country of citizenship': 'P6',
29
+ 'occupation': 'P19',
30
+ 'sex or gender': 'P8',
31
+ 'official website': 'P17',
32
+ 'perfumes': 'P27',
33
+ 'who wears it': 'P26',
34
+ 'inception': 'P11',
35
+ 'headquarters location': 'P12',
36
+ 'parent organization': 'P13',
37
+ 'founded by': 'P14',
38
+ 'owned by': 'P22',
39
+ 'industry': 'P20',
40
+ 'country': 'P30',
41
+ 'total revenue': 'P21',
42
+ 'designer employed': 'P29',
43
+ 'country of origin': 'P30',
44
+ 'fashion collection': 'P31',
45
+ 'fashion season': 'P32',
46
+ 'fashion show location': 'P33',
47
+ 'description of fashion collection': 'P34',
48
+ 'image of fashion collection': 'P35',
49
+ 'editor of fashion collection description': 'P36',
50
+ 'date of fashion collection': 'P37',
51
+ 'fashion show category': 'P38',
52
+ 'fashion house X fashion collection': 'P39'}
53
+
54
+ classes_wikibase = {'fashion designer': 'Q5',
55
+ 'fashion house': 'Q1',
56
+ 'business': 'Q9',
57
+ 'academic institution': 'Q2',
58
+ 'geographic location': 'Q4',
59
+ 'fashion award': 'Q8',
60
+ 'gender': 'Q6',
61
+ 'occupation': 'Q7',
62
+ 'human': 'Q36',
63
+ 'organization': 'Q3',
64
+ 'brand': 'Q38',
65
+ 'lifestyle brand': 'Q3417',
66
+ 'privately held company': 'Q1729',
67
+ 'fashion season': 'Q8199',
68
+ 'fashion show category': 'Q8200',
69
+ 'fashion season collection': 'Q8201',
70
+ 'fashion journalist': 'Q8207'}
71
+
72
+ questions_queries_all = [{ "question": education_most_popular_question, "query": education_most_popular_query},
73
+ { "question": how_many_designers_per_fashion_house_question, "query": how_many_designers_per_fashion_house_query},
74
+ {"question": how_many_directors_per_fashion_house_question, "query": how_many_directors_per_fashion_house_query},
75
+ {"question": designers_multiple_houses_question, "query":designers_multiple_houses_query },
76
+ {"question": award_question, "query": award_question},
77
+ {"question": fashion_houses_with_collections_question, "query": fashion_houses_with_collections_query},
78
+ {"question": popular_year_inception_question, "query": popular_year_inception_query},
79
+ {"question": longest_serving_director_question, "query": longest_serving_director_query},
80
+ {"question": houses_most_collections_question, "query": houses_most_collections_query},
81
+ {"question": collections_sustainability_theme_question, "query": collections_sustainability_theme_query},
82
+ {"question": collections_jeans_question, "query": collections_jeans_query},
83
+ {"question": creative_directors_school_question, "query": creative_directors_school_query},
84
+ {"question": fashion_houses_thematic_collection_question, "query": fashion_houses_thematic_collection_query},
85
+ {"question": fashion_house_directors_question.substitute({ "x": f"{"Chanel"}"}), "query": fashion_house_directors_query.substitute({ "x": f"'{"Chanel"}'"})},
86
+ { "question": designer_fashion_house_directors_question.substitute({ "x": f"{"Alexander McQueen"}"}), "query": designer_fashion_house_directors_query.substitute({ "x": f"'{"Alexander McQueen"}'"})},
87
+ {"question": country_designer_question.substitute({ "x": f"{"Italy"}"}), "query": country_designer_query.substitute({ "x": f"'{"Italy"}'"})},
88
+ { "question": designer_order_fashion_collection_question.substitute({ "x": f"{"Alexander McQueen"}"}), "query": designer_order_fashion_collection_query.substitute({ "x": f"'{"Alexander McQueen"}'"})},
89
+ {"question": designer_fashion_director_question2.substitute({ "x": f"{"Alexander McQueen"}"}), "query": designer_fashion_director_query2.substitute({ "x": f"'{"Alexander McQueen"}'"})},
90
+ { "question": year_designers_birth_question.substitute({ "x": 1970}), "query": year_designers_birth_query.substitute({ "x": 1970})},
91
+ { "question": fashion_collection_images_question.substitute({ "x": f"{"Chanel"}"}), "query": fashion_collection_images_query.substitute({ "x": f"'{"Chanel"}'"})}
92
+ ]
93
+
94
+ if os.path.exists("web_app/query_log.json"):
95
+ other_pairs = pd.read_json("web_app/query_log.json")
96
+ other_pairs_success = other_pairs[(other_pairs["status"] == "Success") & (other_pairs["feedback"] == "good")]
97
+ other_pairs_success = other_pairs_success[["question", "query"]]
98
+ questions_queries_all = questions_queries_all + other_pairs_success.to_dict(orient='records')
99
+
100
+ #print only the questions
101
+ #print([q["question"] for q in questions_queries_all])
102
+
103
+
104
+
105
+
106
+
107
+ def mask_entities(text, nlp):
108
+ doc = nlp(text)
109
+ masked_text = text
110
+ for ent in doc.ents:
111
+ masked_text = masked_text.replace(ent.text, "[ENTITY]")
112
+ return masked_text
113
+
114
+
115
+
116
+
117
+ import re
118
+ import spacy
119
+
120
+ def replace_entity(original_question, to_do_question, query):
121
+ """
122
+ Replaces entities in the query using entities from to_do_question while preserving quotation marks.
123
+ Handles multiple entity replacements and numerical entity replacements.
124
+ """
125
+ nlp = spacy.load("en_core_web_sm")
126
+
127
+ original_doc = nlp(original_question)
128
+ to_do_doc = nlp(to_do_question)
129
+
130
+ # Extract entities from both questions
131
+ original_entities = [ent.text for ent in original_doc.ents]
132
+ to_do_entities = [ent.text for ent in to_do_doc.ents]
133
+ # print("Original Entities:", original_entities)
134
+ # print("To-Do Entities:", to_do_entities)
135
+
136
+ # Create entity mapping
137
+ entity_mapping = {}
138
+
139
+ for orig_ent, new_ent in zip(original_entities, to_do_entities):
140
+ # Find numbers in each entity
141
+ orig_numbers = re.findall(r"\d+", orig_ent)
142
+ new_numbers = re.findall(r"\d+", new_ent)
143
+
144
+ if orig_numbers and new_numbers and len(orig_numbers) == len(new_numbers):
145
+ # If multiple numbers, replace each one
146
+ for orig_num, new_num in zip(orig_numbers, new_numbers):
147
+ entity_mapping[orig_num] = new_num
148
+ else:
149
+ # Otherwise, replace entire entity
150
+ entity_mapping[orig_ent] = new_ent
151
+
152
+ #print("Entity Mapping:", entity_mapping)
153
+
154
+ # Replace entities in the query
155
+ for orig, new in entity_mapping.items():
156
+ query = re.sub(rf'("{orig}"|\b{re.escape(orig)}\b)',
157
+ lambda match: f'"{new}"' if match.group(0).startswith('"') else new,
158
+ query)
159
+
160
+ return query
161
+
162
+
163
+ def capitalize_sentences(sentences):
164
+ """
165
+ Ensures that each sentence in a list starts with an uppercase letter.
166
+ """
167
+ capitalized_sentences = []
168
+
169
+ for sentence in sentences:
170
+ sentence = sentence.strip() # Remove leading/trailing spaces
171
+ if sentence: # Check if the sentence is not empty
172
+ sentence = sentence[0].upper() + sentence[1:] # Capitalize first letter
173
+ capitalized_sentences.append(sentence)
174
+
175
+ return capitalized_sentences
176
+
177
+
178
+
179
+ import numpy as np
180
+ import spacy
181
+
182
+
183
+
184
+ def similarity_question(question, questions_queries_dictionary, collection, n_results=5, threshold=0.15):
185
+ """
186
+ Removes duplicate embeddings and retrieves similar questions.
187
+ """
188
+ nlp = spacy.load("en_core_web_sm") # Load spaCy model for entity recognition
189
+
190
+ original_documents = [questions_queries_dictionary[i]["question"] for i in range(len(questions_queries_dictionary))]
191
+ masked_documents = [mask_entities(q, nlp) for q in original_documents]
192
+
193
+ # Dictionary to store unique embeddings
194
+ unique_embeddings = {}
195
+
196
+ # Store each unique document in the vector embedding database
197
+ for i, d in enumerate(masked_documents):
198
+ response = ollama.embed(model="mxbai-embed-large", input=d)
199
+ embedding = response["embeddings"][0] # Extract the first (and only) embedding from the nested list
200
+
201
+ # Check if embedding is unique
202
+ is_duplicate = any(np.allclose(embedding, np.array(e), atol=1e-6) for e in unique_embeddings.values())
203
+ if not is_duplicate:
204
+ unique_embeddings[str(i)] = embedding # Store unique embedding as a list
205
+
206
+ collection.add(
207
+ ids=[str(i)],
208
+ embeddings=[embedding], # Ensure this is a list of lists
209
+ documents=[d]
210
+ )
211
+
212
+ # Compute the embedding for the input question
213
+ masked_question = mask_entities(question, nlp)
214
+ response = ollama.embed(model="mxbai-embed-large", input=masked_question)
215
+ query_embedding = response["embeddings"][0] # Extract embedding
216
+
217
+ results = collection.query(
218
+ query_embeddings=[query_embedding], # Ensure correct format
219
+ n_results=n_results
220
+ )
221
+
222
+ triples = []
223
+ for i in range(len(results['documents'][0])):
224
+ masked_similar_question = results['documents'][0][i]
225
+ distance = results['distances'][0][i]
226
+ print(distance)
227
+ paraphrase = distance < threshold
228
+
229
+ # Find the corresponding original question
230
+ index_similar_query = masked_documents.index(masked_similar_question)
231
+ original_similar_question = original_documents[index_similar_query]
232
+ similar_query = questions_queries_dictionary[index_similar_query]["query"]
233
+
234
+ if paraphrase and "[ENTITY]" in masked_similar_question and "[ENTITY]" in masked_question:
235
+ to_do_query = replace_entity(original_similar_question, question, similar_query)
236
+ else:
237
+ to_do_query = None
238
+
239
+ triples.append((original_similar_question, similar_query, to_do_query))
240
+
241
+ return triples
242
+
243
+
244
+ def similarity_question_no_masking(question, questions_queries_dictionary, collection, n_results=5, threshold=0.15):
245
+ """
246
+ Removes duplicate embeddings and retrieves similar questions.
247
+ """
248
+
249
+ original_documents = [questions_queries_dictionary[i]["question"] for i in range(len(questions_queries_dictionary))]
250
+
251
+
252
+ # Dictionary to store unique embeddings
253
+ unique_embeddings = {}
254
+
255
+ # Store each unique document in the vector embedding database
256
+ for i, d in enumerate(original_documents):
257
+ response = ollama.embed(model="mxbai-embed-large", input=d)
258
+ embedding = response["embeddings"][0] # Extract the first (and only) embedding from the nested list
259
+
260
+ # Check if embedding is unique
261
+ is_duplicate = any(np.allclose(embedding, np.array(e), atol=1e-6) for e in unique_embeddings.values())
262
+ if not is_duplicate:
263
+ unique_embeddings[str(i)] = embedding # Store unique embedding as a list
264
+
265
+ collection.add(
266
+ ids=[str(i)],
267
+ embeddings=[embedding], # Ensure this is a list of lists
268
+ documents=[d]
269
+ )
270
+
271
+ # Compute the embedding for the input question
272
+
273
+ response = ollama.embed(model="mxbai-embed-large", input=question)
274
+ query_embedding = response["embeddings"][0] # Extract embedding
275
+
276
+ results = collection.query(
277
+ query_embeddings=[query_embedding], # Ensure correct format
278
+ n_results=n_results
279
+ )
280
+
281
+ triples = []
282
+ for i in range(len(results['documents'][0])):
283
+ similar_question = results['documents'][0][i]
284
+ distance = results['distances'][0][i]
285
+ print(distance)
286
+ paraphrase = distance < threshold
287
+
288
+ # Find the corresponding original question
289
+ index_similar_query = original_documents.index(similar_question)
290
+ original_similar_question = original_documents[index_similar_query]
291
+ similar_query = questions_queries_dictionary[index_similar_query]["query"]
292
+
293
+ to_do_query = similar_query if paraphrase else None
294
+
295
+ triples.append((original_similar_question, similar_query, to_do_query))
296
+
297
+ return triples
298
+
299
+ def select_dict(dict, keys):
300
+ return {k: dict[k] for k in keys if k in dict}
301
+
302
+ def prompt_template(to_do_question,triples_examples,wikibase_properties_id,how_many_examples = 1, ):
303
+
304
+ questions = [triples_examples[i][0] for i in range(len(triples_examples))][:how_many_examples]
305
+ print("EXAMPLE QUESTION(s): ",questions)
306
+
307
+ classes_wikibase_selection = select_dict(classes_wikibase, ["fashion house", "fashion designer"])
308
+ general_properties = select_dict(wikibase_properties_id, ["instance of", "reference URL", "start time", "end time", "occupation title", "point in time", "official website"])
309
+ general_properties["rdfs:label"] = "rdfs:label"
310
+ designer_properties = select_dict(wikibase_properties_id, ["employer", "educated at", "work location", "award received", "date of birth", "date of death", "place of birth", "country of citizenship", "occupation", "sex or gender"])
311
+ fashion_house_properties = select_dict(wikibase_properties_id, ["inception","headquarters location", "parent organization", "founded by","owned by", "industry", "country", "total revenue", "designer employed", "fashion collection", "description of fashion collection","image of fashion collection"])
312
+ fashion_collection_properties = select_dict(wikibase_properties_id, ["fashion show category", "fashion show location", "fashion season"])
313
+ qualifier_properties = select_dict(wikibase_properties_id, ["start time", "end time", "occupation title", "point in time","description of fashion collection","image of fashion collection"])
314
+
315
+ prompt = f"""You are an expert in translating natural language questions into SPARQL queries for FashionDB - a knwoledge graph about Fashion.
316
+ I provide you with the ontology of FashionDB. The properties are stored in a dictionary as property_label: property_id. The classes are stored in a dictionary as class_label: class_id.
317
+ General Properties: {general_properties}, Fashion Designer Properties: {designer_properties}, Fashion House Properties: {fashion_house_properties}, Fashion Collection Properties: {fashion_collection_properties}.
318
+ In particular the following properties are always qualifiers thus their prefix is always pq: {qualifier_properties}.
319
+ Classes: {classes_wikibase_selection}.
320
+ Remember to use the entities presented in Natural language question to translate , when generating the corresponding SPARQL query.
321
+
322
+
323
+ I provide you with example."""
324
+ for i in range(len(questions)):
325
+ prompt += f""" Example question: {triples_examples[i][0]}
326
+ Corresponding SPARQL query:{triples_examples[i][1]} """
327
+ prompt += f""" Question to translate to SPARQL: {to_do_question}
328
+ Remember that the use case is FASHION: if there is a mispelling of a fashion designer or house, you can adjust it according to your knowledge of fashion. Example: "balenciaho" should be "Balenciaga".
329
+ Your generated corresponding SPARQL query: """
330
+
331
+ return prompt
332
+
333
+
334
+ def prompt_template_gemma2(to_do_question, triples_examples, wikibase_properties_id, how_many_examples=1):
335
+ questions = [triples_examples[i][0] for i in range(len(triples_examples))][:how_many_examples]
336
+ print("EXAMPLE QUESTION(s): ",questions)
337
+ classes_wikibase_selection = select_dict(classes_wikibase, ["fashion house", "fashion designer"])
338
+ general_properties = select_dict(wikibase_properties_id, ["instance of", "reference URL", "start time", "end time", "occupation title", "point in time", "official website"])
339
+ general_properties["rdfs:label"] = "rdfs:label"
340
+ designer_properties = select_dict(wikibase_properties_id, ["employer", "educated at", "work location", "award received", "date of birth", "date of death", "place of birth", "country of citizenship", "occupation", "sex or gender"])
341
+ fashion_house_properties = select_dict(wikibase_properties_id, ["inception", "headquarters location", "parent organization", "founded by", "owned by", "industry", "country", "total revenue", "designer employed", "fashion collection", "description of fashion collection", "image of fashion collection"])
342
+ fashion_collection_properties = select_dict(wikibase_properties_id, ["fashion show category", "fashion show location", "fashion season"])
343
+ qualifier_properties = select_dict(wikibase_properties_id, ["start time", "end time", "occupation title", "point in time", "description of fashion collection", "image of fashion collection"])
344
+
345
+ prompt = f"""
346
+ You are an expert in translating natural language fashion-related questions into **SPARQL queries** for **FashionDB**, a knowledge graph about fashion.
347
+
348
+ ---
349
+ ## **FashionDB Ontology**
350
+ - **Classes**: {classes_wikibase_selection}
351
+ - **General Properties**: {general_properties}
352
+ - **Fashion Designer Properties**: {designer_properties}
353
+ - **Fashion House Properties**: {fashion_house_properties}
354
+ - **Fashion Collection Properties**: {fashion_collection_properties}
355
+ - **Qualifier Properties** (always prefixed with `pq:`): {qualifier_properties}
356
+
357
+ ---
358
+ ## **Instructions**
359
+ - **Fix misspellings** of fashion brands and designers before generating the query.
360
+ - Example: "Guxci" → **"Gucci"**, "Balenciaho" → **"Balenciaga"**.
361
+ - If a brand or designer **isn't recognized**, **make a reasonable correction** based on common fashion knowledge.
362
+ - Handle **abstract or conceptual fashion questions**, such as:
363
+ - "Which fashion houses have had the most influence in the 20th century?"
364
+ - "What are the key design trends in haute couture from the 1990s?"
365
+ - **Always return a valid SPARQL query** using the provided ontology.
366
+
367
+ ---
368
+ ## **Example(s)**
369
+ """
370
+
371
+ for i in range(len(questions)):
372
+ prompt += f"""
373
+ **Example {i+1}**
374
+ - **Question**: {triples_examples[i][0]}
375
+ - **SPARQL Query**:
376
+ ```sparql
377
+ {triples_examples[i][1]}
378
+ ```
379
+ """
380
+
381
+ prompt += f"""
382
+ ---
383
+ ## **Your Task**
384
+ **Question**: {to_do_question}
385
+
386
+ **SPARQL Query:**
387
+ ```sparql
388
+ """
389
+
390
+ return prompt
391
+
392
+ def prompt_template_gpt4o_mini(to_do_question, triples_examples, wikibase_properties_id, how_many_examples=1):
393
+ questions = [triples_examples[i][0] for i in range(len(triples_examples))][:how_many_examples]
394
+
395
+ classes_wikibase_selection = select_dict(classes_wikibase, ["fashion house", "fashion designer"])
396
+ general_properties = select_dict(wikibase_properties_id, ["instance of", "reference URL", "start time", "end time", "occupation title", "point in time", "official website"])
397
+ general_properties["rdfs:label"] = "rdfs:label"
398
+ designer_properties = select_dict(wikibase_properties_id, ["employer", "educated at", "work location", "award received", "date of birth", "date of death", "place of birth", "country of citizenship", "occupation", "sex or gender"])
399
+ fashion_house_properties = select_dict(wikibase_properties_id, ["inception", "headquarters location", "parent organization", "founded by", "owned by", "industry", "country", "total revenue", "designer employed", "fashion collection", "description of fashion collection", "image of fashion collection"])
400
+ fashion_collection_properties = select_dict(wikibase_properties_id, ["fashion show category", "fashion show location", "fashion season"])
401
+ qualifier_properties = select_dict(wikibase_properties_id, ["start time", "end time", "occupation title", "point in time", "description of fashion collection", "image of fashion collection"])
402
+
403
+ prompt = f"""
404
+ You are a **SPARQL expert** specializing in **FashionDB**, a knowledge graph about fashion.
405
+
406
+ ### **Your Task**
407
+ - Translate the given **natural language question** into a **valid SPARQL query**.
408
+ - **Fix spelling mistakes** of fashion brands and designers.
409
+ - Example: "Guxci" → "Gucci", "Balenciaho" → "Balenciaga".
410
+ - If a brand or designer isn't recognized, **guess the correct name** based on fashion industry knowledge.
411
+ - Support **abstract fashion questions**, such as:
412
+ - "How did Dior's designs evolve over the decades?"
413
+ - "Which fashion houses had the biggest impact on 21st-century streetwear?"
414
+ - Your **SPARQL query must use the correct ontology**.
415
+
416
+ ---
417
+ ### **FashionDB Ontology**
418
+ - **Classes**: {classes_wikibase_selection}
419
+ - **General Properties**: {general_properties}
420
+ - **Fashion Designer Properties**: {designer_properties}
421
+ - **Fashion House Properties**: {fashion_house_properties}
422
+ - **Fashion Collection Properties**: {fashion_collection_properties}
423
+ - **Qualifier Properties (always prefixed with `pq:`)**: {qualifier_properties}
424
+
425
+ ---
426
+ ### **Example(s)**
427
+ """
428
+
429
+ for i in range(len(questions)):
430
+ prompt += f"""
431
+ **Example {i+1}**
432
+ - **Question**: {triples_examples[i][0]}
433
+ - **SPARQL Query**:
434
+ ```sparql
435
+ {triples_examples[i][1]}
436
+ ```
437
+ """
438
+
439
+ prompt += f"""
440
+ ---
441
+ ### **Now Translate This Question**
442
+ **Question**: {to_do_question}
443
+
444
+ **SPARQL Query:**
445
+ ```sparql
446
+ """
447
+
448
+ return prompt
449
+
450
+ #generate
451
+ def send_chat_prompt(prompt, model, system_prompt ):
452
+ client = openai.OpenAI(
453
+ base_url="http://localhost:11434/v1" if not "gpt" in model else None,
454
+ api_key= "ollama" if not "gpt" in model else openai_api_key)
455
+ resp = client.chat.completions.create(
456
+ model=model,
457
+ temperature = 0.5 ,
458
+ messages=[
459
+ {"role": "system", "content": system_prompt},
460
+ {"role": "user", "content": prompt}])
461
+ response = resp.choices[0].message.content
462
+ return response
463
+
464
+ def main_generate(prompt,model, system_prompt):
465
+ response = send_chat_prompt(prompt,model, system_prompt)
466
+ response = response.replace('```','').replace('json','')
467
+ #print(f" {model} Response:", response)
468
+ return response
469
+
470
+
471
+ #validate
472
+ def replace_last_occurrence(s, pattern, replacement):
473
+ pos = s.rfind(pattern) # Find the last occurrence of the pattern
474
+ if pos != -1:
475
+ return s[:pos] + s[pos:].replace(pattern, replacement, 1)
476
+
477
+ def validation_query(sparql_query):
478
+ if sparql_query.startswith("sparql"):
479
+ sparql_query = sparql_query[6:]
480
+ #if last character is \n remove it
481
+ while sparql_query[-1] == "\n" or sparql_query[-1] == " ":
482
+ sparql_query = sparql_query[:-1]
483
+
484
+ if sparql_query[-1] == ".":
485
+ sparql_query = sparql_query[:-1]
486
+ sparql_query = sparql_query.encode().decode('unicode_escape')
487
+ sparql_query = sparql_query.replace("wdt", "wbt")
488
+ if "SERVICE" not in sparql_query:
489
+ sparql_query = replace_last_occurrence(sparql_query, "}", "SERVICE wikibase:label { bd:serviceParam wikibase:language 'en'. } \n }")
490
+
491
+ return sparql_query
492
+
493
+
494
+ def safe_get_results(query, max_retries=3):
495
+ """
496
+ Safely executes a SPARQL query, handling HTTP errors gracefully.
497
+
498
+ Parameters:
499
+ - query (str): The SPARQL query to execute.
500
+ - max_retries (int): Number of retries before failing.
501
+
502
+ Returns:
503
+ - DataFrame: Query results, or an empty DataFrame if the query fails.
504
+ """
505
+ for attempt in range(max_retries):
506
+ try:
507
+ return get_results_to_df(query) # Attempt to execute the query
508
+ except requests.exceptions.HTTPError as e:
509
+ print(f"Attempt {attempt + 1}: Query failed with HTTPError {e}")
510
+ time.sleep(2) # Wait before retrying
511
+ except Exception as e:
512
+ print(f"Attempt {attempt + 1}: Unexpected error {e}")
513
+ time.sleep(2)
514
+
515
+ print("All attempts failed. Returning empty DataFrame.")
516
+ return pd.DataFrame() # Return empty DataFrame if all retries fail
517
+
518
+
519
+
520
+ def correction_question_prompt(to_do_question):
521
+ correction_prompt = f"""
522
+ You are an expert in **fashion brand and designer names**.
523
+ Your task is to **correct misspellings** in the given question while keeping its original meaning.
524
+ If you recognize a fashion-related name that is misspelled, **fix it**.
525
+ If nothing is wrong, generate the Question to Correct.
526
+ Don't generate **.
527
+
528
+ ### **Examples**
529
+ - "Who founded Guxci?" → "Who founded Gucci?"
530
+ - "What is balenciaho famous for?" → "What is Balenciaga famous for?"
531
+ - "Who is the head designer of gucxi?" → "Who is the head designer of Gucci?"
532
+
533
+ ### **Question to Correct**
534
+ {to_do_question}
535
+
536
+ ### **Corrected Version**
537
+ """
538
+ return correction_prompt
539
+
540
+ def initialize_collection():
541
+ # Initialize ChromaDB client
542
+ client = chromadb.Client()
543
+ # If the collection already exists, delete it to start fresh.
544
+ try:
545
+ client.delete_collection(name="docs") # Delete the existing collection
546
+ except:
547
+ pass
548
+ # Re-create the collection for each query
549
+ collection = client.create_collection(name="docs")
550
+ return collection
551
+
552
+
553
+
554
+
555
+
556
+ def main_generate_queries(to_do_question):
557
+
558
+ # # Initialize ChromaDB client
559
+ # client = chromadb.Client()
560
+ # # If the collection already exists, delete it to start fresh.
561
+ # try:
562
+ # client.delete_collection(name="docs") # Delete the existing collection
563
+ # except:
564
+ # pass
565
+ # # Re-create the collection for each query
566
+ # collection = client.create_collection(name="docs")
567
+ collection = initialize_collection()
568
+ triples_examples = similarity_question(to_do_question, questions_queries_all, collection)
569
+ if triples_examples[0][2] is not None:
570
+ print("it's a paraphrase :)")
571
+ sparql_query = triples_examples[0][2]
572
+ print(triples_examples[0][0])
573
+ result_query = safe_get_results(sparql_query)
574
+ if result_query.empty:
575
+ to_do_question = main_generate(correction_question_prompt(to_do_question), "gemma2", "You have to fix the mispellings of the Question to Correct")
576
+ print(to_do_question)
577
+ sparql_query = replace_entity(triples_examples[0][0], to_do_question, triples_examples[0][1])
578
+ result_query = safe_get_results(sparql_query)
579
+ print(sparql_query)
580
+ if not result_query.empty:
581
+ return result_query.to_dict(orient='records'), sparql_query
582
+
583
+ prompt = prompt_template_gemma2(to_do_question, triples_examples, wikibase_properties_id, how_many_examples=1)
584
+
585
+ sparql_query = main_generate(prompt, "gemma2", "You are a natural language to SPARQL language translator. Do only generate the SPARQL query, nothing else.")
586
+ sparql_query = validation_query(sparql_query)
587
+ result_query = safe_get_results(sparql_query)
588
+
589
+ print(sparql_query)
590
+ if result_query.empty:
591
+ to_do_question = main_generate(correction_question_prompt(to_do_question), "gemma2", "You have to fix the mispellings of the Question to Correct")
592
+ print(to_do_question)
593
+ prompt = prompt_template_gemma2(to_do_question, triples_examples, wikibase_properties_id, how_many_examples=2)
594
+ sparql_query = main_generate(prompt, "gemma2", "You are a natural language to SPARQL language translator. Do only generate the SPARQL query, nothing else.")
595
+ sparql_query = validation_query(sparql_query)
596
+ result_query = safe_get_results(sparql_query)
597
+ if result_query.empty:
598
+ new_collection = initialize_collection()
599
+ triples_examples_no_masked = similarity_question_no_masking(to_do_question, questions_queries_all, new_collection)
600
+ prompt = prompt_template_gemma2(to_do_question, triples_examples_no_masked, wikibase_properties_id, how_many_examples=2)
601
+ sparql_query = main_generate(prompt, "gemma2", "You are a natural language to SPARQL language translator. Do only generate the SPARQL query, nothing else.")
602
+ sparql_query = validation_query(sparql_query)
603
+ result_query = safe_get_results(sparql_query)
604
+ print(sparql_query)
605
+ if result_query.empty:
606
+ text_generated = main_generate(to_do_question, "gemma2", "You are an expert in fashion. Just provide the answer to the question.")
607
+ return text_generated, sparql_query
608
+
609
+ print(sparql_query)
610
+ print(result_query)
611
+
612
+ return result_query.to_dict(orient='records'), sparql_query
613
+
614
+ #main("What is the inception of Chanel?")
615
+ if __name__ == "__main__":
616
+ #main("Which fashion designers being creative directors were born in Italy?")
617
+ #main_generate_queries("Which fashion houses had collections with jeans in their descriptions and how many of the collections have jeans?")
618
+ main_generate_queries("Which designers were born in 1970?")
619
+
src1/questions_queries.py ADDED
@@ -0,0 +1,863 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ import os
3
+ sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
4
+
5
+ from urllib.parse import urlparse
6
+ import logging
7
+ log = logging.getLogger(__name__)
8
+ from time import sleep
9
+ import requests
10
+ helpers_session = requests.Session()
11
+ from wikibaseintegrator.wbi_helpers import get_user_agent
12
+ import pandas as pd
13
+ from string import Template
14
+
15
+
16
+ wikibase_api_url = 'https://fashionwiki.wikibase.cloud/w/api.php'
17
+ config = {
18
+ "SPARQL_ENDPOINT_URL": "https://fashionwiki.wikibase.cloud/query/sparql",
19
+ 'USER_AGENT': 'YourBotName/1.0 (https://yourwebsite.org/bot-info)',#"Traopia",
20
+ 'WIKIBASE_URL': wikibase_api_url,
21
+ }
22
+
23
+ def execute_sparql_query(query: str, prefix: str | None = None, endpoint: str | None = None, user_agent: str | None = None, max_retries: int = 1000, retry_after: int = 60) -> dict:
24
+ """
25
+ Execute any SPARQL query with the provided parameters.
26
+ """
27
+
28
+ sparql_endpoint_url = str(endpoint or config['SPARQL_ENDPOINT_URL'])
29
+ user_agent = user_agent or (str(config['USER_AGENT']) if config['USER_AGENT'] is not None else None)
30
+
31
+ hostname = urlparse(sparql_endpoint_url).hostname
32
+ if hostname and hostname.endswith(('wikidata.org', 'wikipedia.org', 'wikimedia.org')) and user_agent is None:
33
+ log.warning('WARNING: Please set a user agent if you interact with a Wikimedia Foundation instance.')
34
+
35
+ if prefix:
36
+ query = prefix + '\n' + query
37
+
38
+ headers = {
39
+ 'Accept': 'application/sparql-results+json',
40
+ 'User-Agent': get_user_agent(user_agent),
41
+ 'Content-Type': 'application/sparql-query' # Correct Content-Type
42
+ }
43
+
44
+ # Attempt to make the request
45
+ for _ in range(max_retries):
46
+ try:
47
+ # Use 'data' instead of 'params' for the POST request to SPARQL
48
+ response = helpers_session.post(sparql_endpoint_url, data=query, headers=headers)
49
+ except requests.exceptions.ConnectionError as e:
50
+ log.exception("Connection error: %s. Sleeping for %d seconds.", e, retry_after)
51
+ sleep(retry_after)
52
+ continue
53
+ if response.status_code in (500, 502, 503, 504):
54
+ log.error("Service unavailable (HTTP Code %d). Sleeping for %d seconds.", response.status_code, retry_after)
55
+ sleep(retry_after)
56
+ continue
57
+ if response.status_code == 429:
58
+ if 'retry-after' in response.headers:
59
+ retry_after = int(response.headers['retry-after'])
60
+ log.error("Too Many Requests (429). Sleeping for %d seconds", retry_after)
61
+ sleep(retry_after)
62
+ continue
63
+ response.raise_for_status() # Raise any non-success status code
64
+ return response.json() # Return the JSON result if successful
65
+
66
+ raise Exception(f"No result after {max_retries} retries.")
67
+
68
+
69
+ def get_results_to_df( query):
70
+ results = execute_sparql_query(query)
71
+ df = pd.DataFrame(results["results"]["bindings"])
72
+ df = df.map(lambda x: x['value'] if pd.notnull(x) else None)
73
+ return df
74
+
75
+ fashion_collection_images_question = Template("Images of collections produced by $x")
76
+ fashion_collection_images_query = Template("""
77
+ PREFIX wbt: <https://fashionwiki.wikibase.cloud/prop/direct/>
78
+ PREFIX wb: <https://fashionwiki.wikibase.cloud/entity/>
79
+ PREFIX pq: <https://fashionwiki.wikibase.cloud/prop/qualifier/>
80
+ PREFIX pr: <https://fashionwiki.wikibase.cloud/prop/reference/>
81
+ PREFIX ps: <https://fashionwiki.wikibase.cloud/prop/statement/>
82
+ PREFIX p: <https://fashionwiki.wikibase.cloud/prop/>
83
+ PREFIX prov: <http://www.w3.org/ns/prov#>
84
+
85
+ SELECT ?statement ?fashion_collectionLabel ?image_url ?reference_URL
86
+ ?fashion_seasonLabel (YEAR(?fashion_year) AS ?year) ?categoryLabel WHERE {
87
+ { ?fashion_house rdfs:label $x@en.} # Match label
88
+ UNION
89
+ { ?fashion_house skos:altLabel $x@en. } # Match alias
90
+
91
+
92
+ ?fashion_house p:P31 ?statement.
93
+ ?statement ps:P31 ?fashion_collection.
94
+ OPTIONAL { ?fashion_collection wbt:P32 ?fashion_season. }
95
+ OPTIONAL {?fashion_collection wbt:P28 ?fashion_year.}
96
+ OPTIONAL {?fashion_collection wbt:P38 ?category.}
97
+
98
+ OPTIONAL {
99
+ ?statement pq:P35 ?image_url.
100
+ }
101
+
102
+
103
+ OPTIONAL {
104
+ ?statement prov:wasDerivedFrom ?reference.
105
+ ?reference pr:P24 ?reference_URL.
106
+ }
107
+
108
+ SERVICE wikibase:label { bd:serviceParam wikibase:language "en". } }
109
+ """)
110
+
111
+ year_designers_birth_question = Template("Which designers were born in $x?")
112
+ year_designers_birth_query = Template("""
113
+ PREFIX wbt: <https://fashionwiki.wikibase.cloud/prop/direct/>
114
+ PREFIX wb: <https://fashionwiki.wikibase.cloud/entity/>
115
+ PREFIX ps: <https://fashionwiki.wikibase.cloud/prop/statement/>
116
+ PREFIX pq: <https://fashionwiki.wikibase.cloud/prop/qualifier/>
117
+ PREFIX p: <https://fashionwiki.wikibase.cloud/prop/>
118
+ PREFIX prov: <http://www.w3.org/ns/prov#>
119
+ PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>
120
+
121
+ SELECT ?designerLabel ?birthdate WHERE {
122
+ ?designer wbt:P3 ?birthdate .
123
+ FILTER (YEAR(?birthdate) = $x)
124
+
125
+ SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
126
+ } """)
127
+
128
+ fashion_house_directors_question = Template("Which designers have been creative directors of $x ?")
129
+ fashion_house_directors_query = Template("""
130
+ PREFIX wbt: <https://fashionwiki.wikibase.cloud/prop/direct/>
131
+ PREFIX wb: <https://fashionwiki.wikibase.cloud/entity/>
132
+ PREFIX pq: <https://fashionwiki.wikibase.cloud/prop/qualifier/>
133
+ PREFIX pr: <https://fashionwiki.wikibase.cloud/prop/reference/>
134
+ PREFIX ps: <https://fashionwiki.wikibase.cloud/prop/statement/>
135
+ PREFIX p: <https://fashionwiki.wikibase.cloud/prop/>
136
+ PREFIX prov: <http://www.w3.org/ns/prov#>
137
+
138
+ SELECT
139
+ ?creative_directorLabel (COALESCE(YEAR(?start_time), YEAR(?point_time), YEAR(?inception)) AS ?start_year)
140
+ (YEAR(?end_time) AS ?end_year) ?title ?statement ?reference_URL_source
141
+ WHERE {
142
+ # Fashion house identified by brand name
143
+ ?fashion_house wbt:P2 wb:Q1.
144
+ { ?fashion_house rdfs:label $x@en.} # Match label
145
+ UNION
146
+ { ?fashion_house skos:altLabel $x@en. } # Match alias
147
+
148
+ # Link through designer employed (P29) property for the fashion house - the property for designer employment is P10
149
+ {
150
+ ?fashion_house p:P29 ?statement.
151
+ ?statement ps:P29 ?creative_director.
152
+
153
+ # Optional qualifiers for P29 regarding the time frame
154
+ OPTIONAL { ?statement pq:P15 ?start_time. }
155
+ OPTIONAL { ?statement pq:P28 ?point_time. }
156
+ OPTIONAL { ?statement pq:P16 ?end_time. }
157
+ OPTIONAL { ?statement pq:P25 ?title. }
158
+ OPTIONAL { ?fashion_house wbt:P11 ?inception. }
159
+
160
+
161
+ # Retrieve references for P29
162
+ OPTIONAL {
163
+ ?statement prov:wasDerivedFrom ?reference.
164
+ ?reference pr:P24 ?reference_URL.
165
+ BIND(
166
+ IF(CONTAINS(STR(?reference_URL), "ollama") || CONTAINS(STR(?reference_URL), "gpt"), ?reference_URL, "") AS ?reference_URL_model
167
+ )
168
+ BIND(
169
+ IF(!(CONTAINS(STR(?reference_URL), "ollama") || CONTAINS(STR(?reference_URL), "gpt")), ?reference_URL, "") AS ?reference_URL_source
170
+ )
171
+ }
172
+ }
173
+ UNION
174
+ # Link through founded_by (P14) property for the fashion house
175
+ {
176
+ ?fashion_house p:P14 ?statement.
177
+ ?statement ps:P14 ?creative_director.
178
+
179
+ # Optional qualifiers for P14 (start_year as inception)
180
+ OPTIONAL { ?statement pq:P15 ?start_time. }
181
+ OPTIONAL { ?statement pq:P28 ?point_time. }
182
+ OPTIONAL { ?statement pq:P16 ?end_time. }
183
+ OPTIONAL { ?statement pq:P25 ?title. }
184
+
185
+
186
+ # Retrieve references for P14
187
+ OPTIONAL {
188
+ ?statement prov:wasDerivedFrom ?reference.
189
+ ?reference pr:P24 ?reference_URL.
190
+ BIND(
191
+ IF(CONTAINS(STR(?reference_URL), "ollama") || CONTAINS(STR(?reference_URL), "gpt"), ?reference_URL, "") AS ?reference_URL_model
192
+ )
193
+ BIND(
194
+ IF(!(CONTAINS(STR(?reference_URL), "ollama") || CONTAINS(STR(?reference_URL), "gpt")), ?reference_URL, "") AS ?reference_URL_source
195
+ )
196
+ }
197
+ }
198
+
199
+ # Filter for relevant titles (creative director, founder, etc.) to retrieve relevant employment as creative director
200
+ FILTER (
201
+ REGEX(?title, "director", "i") ||
202
+ REGEX(?title, "head designer", "i") ||
203
+ REGEX(?title, "chief", "i") ||
204
+ REGEX(?title, "founder", "i")
205
+ )
206
+ FILTER(?reference_URL_source != "")
207
+ # Retrieve labels
208
+ SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
209
+ } ORDER BY ?start_year """)
210
+
211
+
212
+
213
+ designer_fashion_house_directors_question = Template("In which fashion house did $x work as a creative director?")
214
+ designer_fashion_house_directors_query = Template("""
215
+ PREFIX wbt: <https://fashionwiki.wikibase.cloud/prop/direct/>
216
+ PREFIX wb: <https://fashionwiki.wikibase.cloud/entity/>
217
+ PREFIX pq: <https://fashionwiki.wikibase.cloud/prop/qualifier/>
218
+ PREFIX pr: <https://fashionwiki.wikibase.cloud/prop/reference/>
219
+ PREFIX ps: <https://fashionwiki.wikibase.cloud/prop/statement/>
220
+ PREFIX p: <https://fashionwiki.wikibase.cloud/prop/>
221
+ PREFIX prov: <http://www.w3.org/ns/prov#>
222
+
223
+ SELECT ?fashion_houseLabel
224
+ (COALESCE(YEAR(?start_time), YEAR(?point_time), YEAR(?inception)) AS ?start_year)
225
+ (YEAR(?end_time) AS ?end_year)
226
+ ?title ?reference_URL_source ?statement
227
+ WHERE {
228
+ # Designer linked to fashion house through roles or founded_by
229
+ ?fashion_designer wbt:P2 wb:Q5.
230
+ { ?fashion_designer rdfs:label $x@en.} # Match label
231
+ UNION
232
+ { ?fashion_designer skos:altLabel $x@en. } # Match alias
233
+
234
+ # Link through employer (P10)
235
+ ?fashion_designer p:P10 ?statement.
236
+ ?statement ps:P10 ?fashion_house.
237
+
238
+ # Optional start and end time qualifiers for roles
239
+ OPTIONAL { ?statement pq:P15 ?start_time. }
240
+ OPTIONAL { ?statement pq:P28 ?point_time. }
241
+ OPTIONAL { ?statement pq:P16 ?end_time. }
242
+ OPTIONAL { ?statement pq:P25 ?title. }
243
+
244
+ # Inception as fallback for start year
245
+ OPTIONAL { ?fashion_house wbt:P11 ?inception. }
246
+
247
+ # Filter for relevant roles (director, founder, etc.)
248
+ FILTER (
249
+ REGEX(?title, "director", "i") ||
250
+ REGEX(?title, "head designer", "i") ||
251
+ REGEX(?title, "chief","i") ||
252
+ REGEX(?title, "founder","i")
253
+ )
254
+
255
+ # Retrieve references for the statement
256
+ OPTIONAL {
257
+ ?statement prov:wasDerivedFrom ?reference.
258
+ ?reference pr:P24 ?reference_URL.
259
+ BIND(
260
+ IF(CONTAINS(STR(?reference_URL), "ollama") || CONTAINS(STR(?reference_URL), "gpt"), ?reference_URL, "") AS ?reference_URL_model
261
+ )
262
+ BIND(
263
+ IF(!(CONTAINS(STR(?reference_URL), "ollama") || CONTAINS(STR(?reference_URL), "gpt")), ?reference_URL, "") AS ?reference_URL_source
264
+ )
265
+ }
266
+ FILTER(?reference_URL_source != "")
267
+
268
+ SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
269
+ }
270
+ """)
271
+
272
+
273
+ designer_fashion_director_question2 = Template("In which fashion house did $x work as a creative director?")
274
+ designer_fashion_director_query2 = Template("""PREFIX wbt: <https://fashionwiki.wikibase.cloud/prop/direct/>
275
+ PREFIX wb: <https://fashionwiki.wikibase.cloud/entity/>
276
+ PREFIX pq: <https://fashionwiki.wikibase.cloud/prop/qualifier/>
277
+ PREFIX pr: <https://fashionwiki.wikibase.cloud/prop/reference/>
278
+ PREFIX ps: <https://fashionwiki.wikibase.cloud/prop/statement/>
279
+ PREFIX p: <https://fashionwiki.wikibase.cloud/prop/>
280
+ PREFIX prov: <http://www.w3.org/ns/prov#>
281
+
282
+ SELECT
283
+ ?fashion_houseLabel ?creative_directorLabel (COALESCE(YEAR(?start_time), YEAR(?point_time), YEAR(?inception)) AS ?start_year) (YEAR(?end_time) AS ?end_year) ?title ?statement ?reference_URL_source
284
+ WHERE {
285
+ # Fashion designer identified by name
286
+ ?creative_director wbt:P2 wb:Q5.
287
+ { ?creative_director rdfs:label $x@en.} # Match label
288
+ UNION
289
+ { ?creative_director skos:altLabel $x@en. } # Match alias
290
+
291
+ # Link through designer employed (P29) property for the fashion house - the property for designer employment is P30
292
+ {
293
+ ?fashion_house p:P29 ?statement.
294
+ ?statement ps:P29 ?creative_director.
295
+
296
+ # Optional qualifiers for P29 regarding the time frame
297
+ OPTIONAL { ?statement pq:P15 ?start_time. }
298
+ OPTIONAL { ?statement pq:P28 ?point_time. }
299
+ OPTIONAL { ?statement pq:P16 ?end_time. }
300
+ OPTIONAL { ?statement pq:P25 ?title. }
301
+ OPTIONAL { ?fashion_house wbt:P11 ?inception. }
302
+
303
+
304
+ # Retrieve references for P29
305
+ OPTIONAL {
306
+ ?statement prov:wasDerivedFrom ?reference.
307
+ ?reference pr:P24 ?reference_URL.
308
+ BIND(
309
+ IF(CONTAINS(STR(?reference_URL), "ollama") || CONTAINS(STR(?reference_URL), "gpt"), ?reference_URL, "") AS ?reference_URL_model
310
+ )
311
+ BIND(
312
+ IF(!(CONTAINS(STR(?reference_URL), "ollama") || CONTAINS(STR(?reference_URL), "gpt")), ?reference_URL, "") AS ?reference_URL_source
313
+ )
314
+ }
315
+ }
316
+ FILTER (
317
+ REGEX(?title, "director", "i") ||
318
+ REGEX(?title, "head designer", "i") ||
319
+ REGEX(?title, "chief", "i") ||
320
+ REGEX(?title, "founder", "i")
321
+ )
322
+ FILTER(?reference_URL_source != "")
323
+
324
+ # Retrieve labels
325
+ SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
326
+ } ORDER BY ?start_year """)
327
+
328
+ country_designer_question = Template("Which designers are from $x ?")
329
+ country_designer_query = Template("""PREFIX wbt: <https://fashionwiki.wikibase.cloud/prop/direct/>
330
+ PREFIX wb: <https://fashionwiki.wikibase.cloud/entity/>
331
+ PREFIX pq: <https://fashionwiki.wikibase.cloud/prop/qualifier/>
332
+ PREFIX pr: <https://fashionwiki.wikibase.cloud/prop/reference/>
333
+ PREFIX ps: <https://fashionwiki.wikibase.cloud/prop/statement/>
334
+ PREFIX p: <https://fashionwiki.wikibase.cloud/prop/>
335
+ PREFIX prov: <http://www.w3.org/ns/prov#>
336
+
337
+ SELECT ?fashion_designerLabel (SAMPLE(?statement) AS ?statement)
338
+ (SAMPLE(?reference_URL) AS ?reference_URL) WHERE {
339
+ # Restrict to designers who are instances of fashion designer (Q5)
340
+
341
+ ?fashion_designer wbt:P2 wb:Q5.
342
+
343
+ # Access the statement for the country relationship
344
+ ?fashion_designer p:P6 ?statement.
345
+ ?statement ps:P6 ?country.
346
+ { ?country rdfs:label $x@en.} # Match label
347
+ UNION
348
+ { ?country skos:altLabel $x@en. } # Match alias
349
+
350
+ # Retrieve references from the statement
351
+ OPTIONAL {
352
+ ?statement prov:wasDerivedFrom ?reference.
353
+ ?reference pr:P24 ?reference_URL.
354
+ }
355
+
356
+ # Retrieve labels for the fashion designer
357
+ SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
358
+ }
359
+ GROUP BY ?fashion_designerLabel
360
+ ORDER BY ?fashion_designerLabel """)
361
+
362
+ country_designer_query = Template("""PREFIX wbt: <https://fashionwiki.wikibase.cloud/prop/direct/>
363
+ PREFIX wb: <https://fashionwiki.wikibase.cloud/entity/>
364
+ PREFIX pq: <https://fashionwiki.wikibase.cloud/prop/qualifier/>
365
+ PREFIX pr: <https://fashionwiki.wikibase.cloud/prop/reference/>
366
+ PREFIX ps: <https://fashionwiki.wikibase.cloud/prop/statement/>
367
+ PREFIX p: <https://fashionwiki.wikibase.cloud/prop/>
368
+ PREFIX prov: <http://www.w3.org/ns/prov#>
369
+
370
+ SELECT ?fashion_designerLabel (SAMPLE(?reference_URL) AS ?reference_URL) {
371
+ # Restrict to designers who are instances of fashion designer (Q5)
372
+
373
+ ?fashion_designer wbt:P2 wb:Q5.
374
+ ?fashion_designer wbt:P6 ?country.
375
+ ?fashion_designer p:P6 ?statement.
376
+ { ?country rdfs:label $x@en.} # Match label
377
+ UNION
378
+ { ?country skos:altLabel $x@en. } # Match alias
379
+
380
+
381
+ # Retrieve references from the statement
382
+ OPTIONAL {
383
+ ?statement prov:wasDerivedFrom ?reference.
384
+ ?reference pr:P24 ?reference_URL.
385
+ }
386
+
387
+ # Retrieve labels for the fashion designer
388
+ SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
389
+ }
390
+ GROUP BY ?fashion_designerLabel
391
+ ORDER BY ?fashion_designerLabel """)
392
+
393
+
394
+ designer_order_fashion_collection_question = Template("Which fashion collections did $x work on?")
395
+ designer_order_fashion_collection_query = Template("""PREFIX wbt: <https://fashionwiki.wikibase.cloud/prop/direct/>
396
+ PREFIX wb: <https://fashionwiki.wikibase.cloud/entity/>
397
+ PREFIX pq: <https://fashionwiki.wikibase.cloud/prop/qualifier/>
398
+ PREFIX pr: <https://fashionwiki.wikibase.cloud/prop/reference/>
399
+ PREFIX ps: <https://fashionwiki.wikibase.cloud/prop/statement/>
400
+ PREFIX p: <https://fashionwiki.wikibase.cloud/prop/>
401
+ PREFIX prov: <http://www.w3.org/ns/prov#>
402
+
403
+ SELECT ?fashion_houseLabel
404
+ (COALESCE(YEAR(?start_time), YEAR(?point_time), YEAR(?inception)) AS ?start_year)
405
+ (YEAR(?end_time) AS ?end_year)
406
+ ?title ?reference_URL_source ?statement ?fashion_collectionLabel ?image_url
407
+ (YEAR(?fashion_year) as ?year ) ?fashion_seasonLabel ?categoryLabel WHERE {
408
+ # Designer linked to fashion house through roles or founded_by
409
+ ?fashion_designer wbt:P2 wb:Q5.
410
+ { ?fashion_designer rdfs:label $x@en.} # Match label
411
+ UNION
412
+ { ?fashion_designer skos:altLabel $x@en. } # Match alias
413
+
414
+
415
+ # Link through "creative director" or other roles
416
+ ?fashion_designer p:P10 ?statement_designer.
417
+ ?statement_designer ps:P10 ?fashion_house.
418
+ OPTIONAL { ?statement_designer pq:P15 ?start_time. }
419
+ OPTIONAL { ?statement_designer pq:P28 ?point_time. }
420
+ OPTIONAL { ?statement_designer pq:P16 ?end_time. }
421
+ OPTIONAL { ?statement_designer pq:P25 ?title. }
422
+ OPTIONAL { ?fashion_house wbt:P11 ?inception. }
423
+ FILTER (
424
+ REGEX(?title, "director", "i") ||
425
+ REGEX(?title, "head designer", "i") ||
426
+ REGEX(?title, "chief","i") ||
427
+ REGEX(?title, "founder","i")
428
+ )
429
+
430
+ ?fashion_house p:P31 ?statement.
431
+ ?statement ps:P31 ?fashion_collection.
432
+ OPTIONAL {?fashion_collection wbt:P28 ?fashion_year.}
433
+ OPTIONAL { ?fashion_collection wbt:P32 ?fashion_season. }
434
+ OPTIONAL {?fashion_collection wbt:P38 ?category.}
435
+
436
+ OPTIONAL {?statement pq:P35 ?image_url.}
437
+ OPTIONAL {?statement pq:P37 ?fashion_date.}
438
+
439
+
440
+ # Use the adjusted fashion year in the FILTER condition
441
+ FILTER(
442
+ (YEAR(?start_time) <= YEAR(?fashion_year) && (!BOUND(?end_time) || YEAR(?end_time) >= YEAR(?fashion_year))) ||
443
+ (YEAR(?point_time) <= YEAR(?fashion_year)) ||
444
+ (REGEX(?title, "founder", "i") && YEAR(?inception) <= YEAR(?fashion_year))
445
+ )
446
+
447
+ # Retrieve references for the statement
448
+ OPTIONAL {
449
+ ?statement prov:wasDerivedFrom ?reference.
450
+ ?reference pr:P24 ?reference_URL_source.
451
+ }
452
+
453
+ SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
454
+ } ORDER BY ?year """)
455
+
456
+
457
+ education_most_popular_question = "What are the most popular educational institutions for fashion designers?"
458
+ education_most_popular_query = """ PREFIX wbt: <https://fashionwiki.wikibase.cloud/prop/direct/>
459
+ PREFIX wb: <https://fashionwiki.wikibase.cloud/entity/>
460
+ PREFIX pq: <https://fashionwiki.wikibase.cloud/prop/qualifier/>
461
+ PREFIX pr: <https://fashionwiki.wikibase.cloud/prop/reference/>
462
+ PREFIX ps: <https://fashionwiki.wikibase.cloud/prop/statement/>
463
+ PREFIX p: <https://fashionwiki.wikibase.cloud/prop/>
464
+ PREFIX prov: <http://www.w3.org/ns/prov#>
465
+
466
+ SELECT ?schoolLabel (COUNT(?fashion_designer) AS ?designer_count) WHERE {
467
+ # Retrieve all fashion designers and their schools
468
+ ?fashion_designer wbt:P9 ?school.
469
+
470
+ SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
471
+ }
472
+ GROUP BY ?schoolLabel
473
+ ORDER BY DESC(?designer_count) """
474
+
475
+ brands_founded_question = Template("Which fashion houses were founded in $x")
476
+ brands_founded_query = Template(""" PREFIX wbt: <https://fashionwiki.wikibase.cloud/prop/direct/>
477
+ PREFIX wb: <https://fashionwiki.wikibase.cloud/entity/>
478
+ PREFIX p: <https://fashionwiki.wikibase.cloud/prop/>
479
+
480
+ SELECT ?fashion_houseLabel ?inception
481
+ WHERE {
482
+ ?fashion_house wbt:P2 wb:Q1.
483
+ ?fashion_house wbt:P11 ?inception.
484
+
485
+
486
+ FILTER(YEAR(?inception) = $x)
487
+
488
+ SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
489
+ }""")
490
+
491
+ how_many_directors_per_fashion_house_question = "How many designers have worked for each fashion house as creative directors?"
492
+ how_many_directors_per_fashion_house_query = """ PREFIX wbt: <https://fashionwiki.wikibase.cloud/prop/direct/>
493
+ PREFIX wb: <https://fashionwiki.wikibase.cloud/entity/>
494
+ PREFIX pq: <https://fashionwiki.wikibase.cloud/prop/qualifier/>
495
+ PREFIX pr: <https://fashionwiki.wikibase.cloud/prop/reference/>
496
+ PREFIX ps: <https://fashionwiki.wikibase.cloud/prop/statement/>
497
+ PREFIX p: <https://fashionwiki.wikibase.cloud/prop/>
498
+ PREFIX prov: <http://www.w3.org/ns/prov#>
499
+
500
+ SELECT ?fashion_houseLabel (COUNT(DISTINCT ?fashion_designer) AS ?creative_director_count) WHERE {
501
+ # Match fashion houses linked to designers via employer property
502
+ ?fashion_designer p:P10 ?statement.
503
+ ?statement ps:P10 ?fashion_house.
504
+
505
+ # Filter for roles related to creative direction
506
+ OPTIONAL { ?statement pq:P25 ?title. }
507
+ FILTER (
508
+ REGEX(?title, "creative director", "i") ||
509
+ REGEX(?title, "head designer", "i") ||
510
+ REGEX(?title, "chief", "i") ||
511
+ REGEX(?title, "founder", "i")
512
+ )
513
+
514
+ SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
515
+ }
516
+ GROUP BY ?fashion_houseLabel
517
+ ORDER BY DESC(?creative_director_count)
518
+ """
519
+
520
+ how_many_designers_per_fashion_house_question = "How many designers have worked for each fashion house?"
521
+ how_many_designers_per_fashion_house_query = """ PREFIX wbt: <https://fashionwiki.wikibase.cloud/prop/direct/>
522
+ PREFIX wb: <https://fashionwiki.wikibase.cloud/entity/>
523
+ PREFIX pq: <https://fashionwiki.wikibase.cloud/prop/qualifier/>
524
+ PREFIX pr: <https://fashionwiki.wikibase.cloud/prop/reference/>
525
+ PREFIX ps: <https://fashionwiki.wikibase.cloud/prop/statement/>
526
+ PREFIX p: <https://fashionwiki.wikibase.cloud/prop/>
527
+ PREFIX prov: <http://www.w3.org/ns/prov#>
528
+
529
+ SELECT ?fashion_houseLabel (COUNT(?designer) AS ?designer_count) WHERE {
530
+ ?fashion_house wbt:P29 ?designer .
531
+
532
+ SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
533
+ }
534
+ GROUP BY ?fashion_houseLabel
535
+ ORDER BY DESC(?designer_count) """
536
+
537
+
538
+ designers_multiple_houses_question = "Which designers have worked for more than one fashion house?"
539
+ designers_multiple_houses_query = """PREFIX wbt: <https://fashionwiki.wikibase.cloud/prop/direct/>
540
+ PREFIX wb: <https://fashionwiki.wikibase.cloud/entity/>
541
+ PREFIX pq: <https://fashionwiki.wikibase.cloud/prop/qualifier/>
542
+ PREFIX pr: <https://fashionwiki.wikibase.cloud/prop/reference/>
543
+ PREFIX ps: <https://fashionwiki.wikibase.cloud/prop/statement/>
544
+ PREFIX p: <https://fashionwiki.wikibase.cloud/prop/>
545
+ PREFIX prov: <http://www.w3.org/ns/prov#>
546
+
547
+ SELECT ?designerLabel WHERE {
548
+ ?designer wbt:P10 ?house .
549
+ ?designer wbt:P10 ?anotherHouse .
550
+ SERVICE wikibase:label { bd:serviceParam wikibase:language 'en'. }
551
+ }
552
+ GROUP BY ?designerLabel
553
+ HAVING (COUNT(?house) > 1)"""
554
+
555
+ award_question = "Which designers won which awards?"
556
+ award_query = """ PREFIX wbt: <https://fashionwiki.wikibase.cloud/prop/direct/>
557
+ PREFIX wb: <https://fashionwiki.wikibase.cloud/entity/>
558
+ PREFIX pq: <https://fashionwiki.wikibase.cloud/prop/qualifier/>
559
+ PREFIX pr: <https://fashionwiki.wikibase.cloud/prop/reference/>
560
+ PREFIX ps: <https://fashionwiki.wikibase.cloud/prop/statement/>
561
+ PREFIX p: <https://fashionwiki.wikibase.cloud/prop/>
562
+ PREFIX prov: <http://www.w3.org/ns/prov#>
563
+
564
+ SELECT ?designerLabel ?awardLabel WHERE {
565
+ ?designer wbt:P18 ?award .
566
+ SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
567
+ }"""
568
+
569
+ fashion_houses_with_collections_question ="Which distinct fashion houses have at least a fashion collection?"
570
+ fashion_houses_with_collections_query = """PREFIX wbt: <https://fashionwiki.wikibase.cloud/prop/direct/>
571
+ PREFIX wb: <https://fashionwiki.wikibase.cloud/entity/>
572
+ PREFIX pq: <https://fashionwiki.wikibase.cloud/prop/qualifier/>
573
+ PREFIX pr: <https://fashionwiki.wikibase.cloud/prop/reference/>
574
+ PREFIX ps: <https://fashionwiki.wikibase.cloud/prop/statement/>
575
+ PREFIX p: <https://fashionwiki.wikibase.cloud/prop/>
576
+ PREFIX prov: <http://www.w3.org/ns/prov#>
577
+
578
+ SELECT DISTINCT ?houseLabel WHERE {
579
+ ?house wbt:P31 ?collection .
580
+ SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
581
+ } """
582
+
583
+ popular_year_inception_question = "In which years were the most fashion houses founded?"
584
+ popular_year_inception_query = """PREFIX wbt: <https://fashionwiki.wikibase.cloud/prop/direct/>
585
+ PREFIX wb: <https://fashionwiki.wikibase.cloud/entity/>
586
+ PREFIX pq: <https://fashionwiki.wikibase.cloud/prop/qualifier/>
587
+ PREFIX pr: <https://fashionwiki.wikibase.cloud/prop/reference/>
588
+ PREFIX ps: <https://fashionwiki.wikibase.cloud/prop/statement/>
589
+ PREFIX p: <https://fashionwiki.wikibase.cloud/prop/>
590
+
591
+ SELECT ?year_inception (COUNT(DISTINCT ?fashion_house) AS ?count)
592
+ WHERE {
593
+ ?fashion_house wbt:P11 ?year.
594
+ BIND(YEAR(?year) AS ?year_inception)
595
+ }
596
+ GROUP BY ?year_inception
597
+ ORDER BY DESC(?count) """
598
+
599
+
600
+ longest_serving_director_question = "Which fashion houses have had the longest-serving creative director?"
601
+ longest_serving_director_query = """ PREFIX wbt: <https://fashionwiki.wikibase.cloud/prop/direct/>
602
+ PREFIX wb: <https://fashionwiki.wikibase.cloud/entity/>
603
+ PREFIX pq: <https://fashionwiki.wikibase.cloud/prop/qualifier/>
604
+ PREFIX pr: <https://fashionwiki.wikibase.cloud/prop/reference/>
605
+ PREFIX ps: <https://fashionwiki.wikibase.cloud/prop/statement/>
606
+ PREFIX p: <https://fashionwiki.wikibase.cloud/prop/>
607
+ PREFIX prov: <http://www.w3.org/ns/prov#>
608
+ PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>
609
+ PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
610
+
611
+ SELECT ?fashion_houseLabel ?duration ?designerLabel
612
+ WHERE {
613
+ ?fashion_house p:P29 ?statement.
614
+ ?statement ps:P29 ?designer.
615
+ OPTIONAL { ?statement pq:P15 ?startTime. }
616
+ OPTIONAL { ?statement pq:P16 ?endTime. }
617
+
618
+ # Ensure we only calculate when both dates exist
619
+ FILTER(BOUND(?startTime) && BOUND(?endTime))
620
+
621
+ # Compute duration safely
622
+ BIND(YEAR(?endTime) - YEAR(?startTime) AS ?duration)
623
+
624
+ SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
625
+ }
626
+ ORDER BY DESC(?duration)"""
627
+
628
+ houses_most_collections_question = "Which fashion houses have the most collections recorded in the database?"
629
+ houses_most_collections_query = """ PREFIX wbt: <https://fashionwiki.wikibase.cloud/prop/direct/>
630
+ PREFIX wb: <https://fashionwiki.wikibase.cloud/entity/>
631
+ PREFIX pq: <https://fashionwiki.wikibase.cloud/prop/qualifier/>
632
+ PREFIX pr: <https://fashionwiki.wikibase.cloud/prop/reference/>
633
+ PREFIX ps: <https://fashionwiki.wikibase.cloud/prop/statement/>
634
+ PREFIX p: <https://fashionwiki.wikibase.cloud/prop/>
635
+ PREFIX prov: <http://www.w3.org/ns/prov#>
636
+
637
+ SELECT ?fashionHouseLabel (COUNT(?collection) AS ?collection_count) WHERE {
638
+ ?fashionHouse wbt:P31 ?collection .
639
+ SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
640
+ }
641
+ GROUP BY ?fashionHouseLabel
642
+ ORDER BY DESC(?collection_count)"""
643
+
644
+
645
+ collections_sustainability_theme_question = "Which collections include sustainability as a key theme?"
646
+ collections_sustainability_theme_query = """PREFIX wbt: <https://fashionwiki.wikibase.cloud/prop/direct/>
647
+ PREFIX wb: <https://fashionwiki.wikibase.cloud/entity/>
648
+ PREFIX pq: <https://fashionwiki.wikibase.cloud/prop/qualifier/>
649
+ PREFIX pr: <https://fashionwiki.wikibase.cloud/prop/reference/>
650
+ PREFIX ps: <https://fashionwiki.wikibase.cloud/prop/statement/>
651
+ PREFIX p: <https://fashionwiki.wikibase.cloud/prop/>
652
+ PREFIX prov: <http://www.w3.org/ns/prov#>
653
+
654
+ SELECT ?collectionLabel ?fashion_houseLabel ?reference_URL WHERE {
655
+ ?fashion_house p:P31 ?statement.
656
+ ?statement ps:P31 ?collection.
657
+ ?statement pq:P34 ?description .
658
+ FILTER (regex(?description, "sustainability", "i"))
659
+ # Retrieve references for the statement
660
+ OPTIONAL {
661
+ ?statement prov:wasDerivedFrom ?reference.
662
+ ?reference pr:P24 ?reference_URL.
663
+ }
664
+ SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
665
+ } """
666
+
667
+
668
+ collections_jeans_question = "Which collections showcase products made with jeans?"
669
+ collections_jeans_query = """PREFIX wbt: <https://fashionwiki.wikibase.cloud/prop/direct/>
670
+ PREFIX wb: <https://fashionwiki.wikibase.cloud/entity/>
671
+ PREFIX pq: <https://fashionwiki.wikibase.cloud/prop/qualifier/>
672
+ PREFIX pr: <https://fashionwiki.wikibase.cloud/prop/reference/>
673
+ PREFIX ps: <https://fashionwiki.wikibase.cloud/prop/statement/>
674
+ PREFIX p: <https://fashionwiki.wikibase.cloud/prop/>
675
+ PREFIX prov: <http://www.w3.org/ns/prov#>
676
+
677
+ SELECT ?collectionLabel ?fashion_houseLabel ?reference_URL WHERE {
678
+ ?fashion_house p:P31 ?statement.
679
+ ?statement ps:P31 ?collection.
680
+ ?statement pq:P34 ?description .
681
+ FILTER (regex(?description, "jeans", "i"))
682
+ # Retrieve references for the statement
683
+ OPTIONAL {
684
+ ?statement prov:wasDerivedFrom ?reference.
685
+ ?reference pr:P24 ?reference_URL.
686
+ }
687
+ SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
688
+ } """
689
+
690
+
691
+ creative_directors_school_question = "To which school went most designers who later became creative directors of fashion houses?"
692
+ creative_directors_school_query = """ PREFIX wbt: <https://fashionwiki.wikibase.cloud/prop/direct/>
693
+ PREFIX wb: <https://fashionwiki.wikibase.cloud/entity/>
694
+ PREFIX pq: <https://fashionwiki.wikibase.cloud/prop/qualifier/>
695
+ PREFIX pr: <https://fashionwiki.wikibase.cloud/prop/reference/>
696
+ PREFIX ps: <https://fashionwiki.wikibase.cloud/prop/statement/>
697
+ PREFIX p: <https://fashionwiki.wikibase.cloud/prop/>
698
+ PREFIX prov: <http://www.w3.org/ns/prov#>
699
+
700
+ SELECT ?schoolLabel (COUNT(DISTINCT ?designer) AS ?designer_count) WHERE {
701
+ ?designer p:P10 ?fashion_house .
702
+
703
+ OPTIONAL { ?fashion_house pq:P25 ?title. }
704
+ FILTER (
705
+ REGEX(?title, "creative director", "i") ||
706
+ REGEX(?title, "head designer", "i") ||
707
+ REGEX(?title, "chief", "i") ||
708
+ REGEX(?title, "founder", "i")
709
+ )
710
+
711
+ OPTIONAL { ?designer wbt:P9 ?school . }
712
+ SERVICE wikibase:label { bd:serviceParam wikibase:language 'en'. }
713
+ }
714
+ GROUP BY ?schoolLabel
715
+ ORDER BY DESC(?designer_count)"""
716
+
717
+ fashion_houses_thematic_collection_question = "Which fashion houses had collections with a sustainability theme, and how many of them?"
718
+ fashion_houses_thematic_collection_query = """PREFIX wbt: <https://fashionwiki.wikibase.cloud/prop/direct/>
719
+ PREFIX wb: <https://fashionwiki.wikibase.cloud/entity/>
720
+ PREFIX pq: <https://fashionwiki.wikibase.cloud/prop/qualifier/>
721
+ PREFIX pr: <https://fashionwiki.wikibase.cloud/prop/reference/>
722
+ PREFIX ps: <https://fashionwiki.wikibase.cloud/prop/statement/>
723
+ PREFIX p: <https://fashionwiki.wikibase.cloud/prop/>
724
+ PREFIX prov: <http://www.w3.org/ns/prov#>
725
+
726
+ SELECT ?fashion_houseLabel (COUNT(DISTINCT ?collection) AS ?collection_count) WHERE {
727
+ ?fashion_house p:P31 ?statement.
728
+ ?statement ps:P31 ?collection.
729
+ ?statement pq:P34 ?description .
730
+ FILTER (regex(?description, "sustainability", "i"))
731
+ # Retrieve references for the statement
732
+ OPTIONAL {
733
+ ?statement prov:wasDerivedFrom ?reference.
734
+ ?reference pr:P24 ?reference_URL.
735
+ }
736
+ SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
737
+ } GROUP BY ?fashion_houseLabel
738
+ ORDER BY DESC(?collection_count) """
739
+
740
+
741
+ questions_queries_dict = [ { "question": education_most_popular_question, "query": education_most_popular_query},
742
+ { "question": how_many_designers_per_fashion_house_question, "query": how_many_designers_per_fashion_house_query},
743
+ {"question": how_many_directors_per_fashion_house_question, "query": how_many_directors_per_fashion_house_query},
744
+ {"question": designers_multiple_houses_question, "query":designers_multiple_houses_query },
745
+ {"question": award_question, "query": award_question},
746
+ {"question": fashion_houses_with_collections_question, "query": fashion_houses_with_collections_query},
747
+ {"question": popular_year_inception_question, "query": popular_year_inception_query},
748
+ {"question": longest_serving_director_question, "query": longest_serving_director_query},
749
+ {"question": houses_most_collections_question, "query": houses_most_collections_query},
750
+ {"question": collections_sustainability_theme_question, "query": collections_sustainability_theme_query},
751
+ ]
752
+
753
+ questions_queries_dict_entity = [{"question": fashion_house_directors_question.substitute({ "x": f"{"Chanel"}"}), "query": fashion_house_directors_query},
754
+ { "question": designer_fashion_house_directors_question.substitute({ "x": f"{"Alexander McQueen"}"}), "query": designer_fashion_house_directors_query},
755
+ { "question": country_designer_question.substitute({ "x": f"{"Italy"}"}), "query": country_designer_query},
756
+ { "question": designer_order_fashion_collection_question.substitute({ "x": f"{"Alexander McQueen"}"}), "query": designer_order_fashion_collection_query},
757
+ { "question": designer_fashion_director_question2.substitute({ "x": f"{"Alexander McQueen"}"}), "query": designer_fashion_director_query2},
758
+ { "question": year_designers_birth_question.substitute({ "x": f"{"1970"}"}), "query": year_designers_birth_query}]
759
+
760
+
761
+ # Designers
762
+ designers_born_in_year_question = "Which designers were born in year $x?"
763
+ creative_directors_of_house_question = "Which designers have been creative directors of $x?"
764
+ designers_multiple_houses_question = "Which designers have worked for more than one fashion house?"
765
+ educated_at_school_question = "Which designers were educated at $x fashion school?"
766
+ won_award_question = "Which designers have won the $x award?"
767
+ launched_own_label_question = "Which designers launched their own fashion label?"
768
+ worked_at_x_between_years_question = "Which designers worked at $x between year $y and $z?"
769
+ designers_multiple_collaborations_question = "Which designers have collaborated with multiple fashion houses?"
770
+ designers_lived_in_city_question = "Which designers have lived in $x city?"
771
+ designers_active_decade_question = "Which designers were active during the $x decade?"
772
+
773
+ # Fashion Houses
774
+ designers_worked_for_house_question = "Which designers have worked for fashion house $x?"
775
+ creative_directors_per_house_question = "How many designers have worked for each fashion house as creative directors?"
776
+ houses_founded_in_year_question = "Which fashion houses were founded in year $x?"
777
+ houses_most_director_changes_question = "Which fashion houses have undergone the most creative director changes?"
778
+ longest_serving_director_question = "Which fashion houses have had the longest-serving creative director?"
779
+ houses_collaborations_question = "Which fashion houses have collaborated with other fashion houses or brands?"
780
+ houses_haute_couture_question = "Which fashion houses have produced haute couture collections?"
781
+ houses_active_decade_question = "Which fashion houses were active during the $x decade?"
782
+ houses_most_collections_question = "Which fashion houses have the most collections recorded in the database?"
783
+
784
+ # Fashion Collections
785
+ designer_worked_on_collections_question = "Which fashion collections did $x work on?"
786
+ collections_inspired_by_theme_question = "Which fashion house produced a collection inspired by $x theme?"
787
+ collections_high_critical_acclaim_question = "Which collections received the highest critical acclaim?"
788
+ collections_historical_references_question = "Which collections feature references to historical fashion styles?"
789
+ collections_sustainability_theme_question = "Which collections include sustainability as a key theme?"
790
+ collections_per_house_per_year_question = "How many collections did each fashion house produce in year $x?"
791
+ collections_avant_garde_question = "Which collections have been described as avant-garde?"
792
+ collections_stylistic_similarity_question = "Which collections share stylistic similarities with $x?"
793
+ collections_evolution_over_time_question = "How has the style of $x fashion house evolved over the years?"
794
+ collections_shown_at_fashion_week_question = "Which collections were showcased at $x fashion week?"
795
+
796
+ # Designers & Fashion Houses
797
+ studied_then_director_question = "Which designers who studied at $x fashion school later became creative directors at $y fashion house?"
798
+ worked_at_both_houses_question = "Which designers have worked at both $x and $y fashion houses?"
799
+ launched_label_after_working_question = "Which designers who launched their own fashion labels had previously worked at $x fashion house?"
800
+ won_award_then_worked_question = "Which designers who won the $x award also worked for $y fashion house?"
801
+ lived_in_city_and_director_question = "Which designers who lived in $x city have worked as creative directors for $y fashion house?"
802
+ worked_for_three_houses_question = "Which designers have worked for at least three different fashion houses during their career?"
803
+ designed_for_two_brands_same_year_question = "Which designers who were creative directors at $x fashion house also designed collections for another brand in the same year?"
804
+ creative_director_and_label_founder_question = "Which designers were both fashion house creative directors and independent label founders at the same time?"
805
+ collaborated_with_two_houses_question = "Which designers have collaborated with both $x and $y fashion houses?"
806
+ worked_at_x_before_y_question = "Which designers worked at $x fashion house before moving to $y?"
807
+
808
+ # Designers & Collections
809
+ designed_for_multiple_houses_same_season_question = "Which designers have designed collections for multiple fashion houses in the same season?"
810
+ couture_and_ready_to_wear_question = "Which designers who specialized in haute couture have also designed ready-to-wear collections?"
811
+ similar_theme_collections_question = "Which designers who worked on $x collection had previously worked on a similar-themed collection for another brand?"
812
+ award_winner_inspired_by_history_question = "Which designers who have won an award have produced a collection inspired by $x historical period?"
813
+ alma_mater_referenced_in_collection_question = "Which designers who studied at $x school designed a collection that referenced their alma mater?"
814
+
815
+ # Fashion Houses & Collections
816
+ same_historical_period_collections_question = "Which fashion houses have produced collections inspired by the same historical period?"
817
+ collaborations_with_artists_question = "Which fashion houses have produced collections featuring collaborations with artists from $x field (e.g., photography, sculpture, film)?"
818
+ change_director_different_collection_question = "Which fashion houses have changed creative directors and immediately released a significantly different collection?"
819
+ avant_garde_and_minimalist_question = "Which fashion houses have produced both avant-garde and minimalist collections?"
820
+ inspired_by_other_brands_question = "Which fashion houses have produced a collection inspired by a previous designer’s work from another brand?"
821
+
822
+ # Multi-Category (Designers, Houses, Collections)
823
+ designer_worked_house_then_influenced_question = "Which designers who worked for $x fashion house also designed a collection influenced by $y movement?"
824
+ designer_lived_in_city_referenced_collection_question = "Which designers who lived in $x city during year $y produced a collection with references to that place?"
825
+ multiple_designers_same_collection_question = "Which fashion houses have had at least three designers contribute to the same collection?"
826
+ worked_elsewhere_during_collection_question = "Which collections were created by a designer who was also working at another fashion house at the time?"
827
+ education_influenced_collection_question = "Which fashion collections were influenced by a designer’s education at $x fashion school?"
828
+
829
+ # Designers & Fashion Houses
830
+ studied_then_director_question = "Which designers who studied at $x fashion school later became creative directors at $y fashion house?"
831
+ worked_at_both_houses_question = "Which designers have worked at both $x and $y fashion houses?"
832
+ launched_label_after_working_question = "Which designers who launched their own fashion labels had previously worked at $x fashion house?"
833
+ won_award_then_worked_question = "Which designers who won the $x award also worked for $y fashion house?"
834
+ lived_in_city_and_director_question = "Which designers who lived in $x city have worked as creative directors for $y fashion house?"
835
+ worked_for_three_houses_question = "Which designers have worked for at least three different fashion houses during their career?"
836
+ designed_for_two_brands_same_year_question = "Which designers who were creative directors at $x fashion house also designed collections for another brand in the same year?"
837
+ creative_director_and_label_founder_question = "Which designers were both fashion house creative directors and independent label founders at the same time?"
838
+ collaborated_with_two_houses_question = "Which designers have collaborated with both $x and $y fashion houses?"
839
+ worked_at_x_before_y_question = "Which designers worked at $x fashion house before moving to $y?"
840
+
841
+ # Designers & Collections
842
+ designed_for_multiple_houses_same_season_question = "Which designers have designed collections for multiple fashion houses in the same season?"
843
+ couture_and_ready_to_wear_question = "Which designers who specialized in haute couture have also designed ready-to-wear collections?"
844
+ similar_theme_collections_question = "Which designers who worked on $x collection had previously worked on a similar-themed collection for another brand?"
845
+ award_winner_inspired_by_history_question = "Which designers who have won an award have produced a collection inspired by $x historical period?"
846
+ alma_mater_referenced_in_collection_question = "Which designers who studied at $x school designed a collection that referenced their alma mater?"
847
+
848
+ # Fashion Houses & Collections
849
+ same_historical_period_collections_question = "Which fashion houses have produced collections inspired by the same historical period?"
850
+ collaborations_with_artists_question = "Which fashion houses have produced collections featuring collaborations with artists from $x field (e.g., photography, sculpture, film)?"
851
+ change_director_different_collection_question = "Which fashion houses have changed creative directors and immediately released a significantly different collection?"
852
+ avant_garde_and_minimalist_question = "Which fashion houses have produced both avant-garde and minimalist collections?"
853
+ inspired_by_other_brands_question = "Which fashion houses have produced a collection inspired by a previous designer’s work from another brand?"
854
+
855
+ # Multi-Category (Designers, Houses, Collections)
856
+ designer_worked_house_then_influenced_question = "Which designers who worked for $x fashion house also designed a collection influenced by $y movement?"
857
+ designer_lived_in_city_referenced_collection_question = "Which designers who lived in $x city during year $y produced a collection with references to that place?"
858
+ multiple_designers_same_collection_question = "Which fashion houses have had at least three designers contribute to the same collection?"
859
+ worked_elsewhere_during_collection_question = "Which collections were created by a designer who was also working at another fashion house at the time?"
860
+ education_influenced_collection_question = "Which fashion collections were influenced by a designer’s education at $x fashion school?"
861
+
862
+
863
+
src1/visual_qa.py ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import json
3
+ import pandas as pd
4
+ from transformers import CLIPProcessor, CLIPModel
5
+ import torch
6
+ import os
7
+ os.environ["TOKENIZERS_PARALLELISM"] = "false"
8
+
9
+ import pandas as pd
10
+ import chromadb
11
+ import os
12
+ from transformers import CLIPProcessor, CLIPModel
13
+ import torch
14
+ from datetime import datetime
15
+ from datasets import load_dataset
16
+
17
+
18
+ def initialize_collection(collection_name="clip_image_embeddings"):
19
+ # Initialize ChromaDB client (PersistentClient stores embeddings between runs)
20
+ client = chromadb.PersistentClient(path="./chroma_db") # Change path if needed
21
+
22
+ # Get a list of existing collection names
23
+ existing_collections = [col for col in client.list_collections()] # v0.6.0 change
24
+
25
+ if collection_name in existing_collections:
26
+ collection = client.get_collection(name=collection_name)
27
+ print(f"Using existing collection: {collection_name}")
28
+ else:
29
+ collection = client.create_collection(name=collection_name)
30
+
31
+ return collection
32
+
33
+
34
+
35
+
36
+ def main_create_image_collection(df_emb, collection_name="clip_image_embeddings"):
37
+ documents = []
38
+ embeddings_all = df_emb["fashion_clip_image"].tolist()
39
+
40
+ for i in range(len(df_emb)):
41
+ if i >= len(df_emb["image_url"]):
42
+ print(f"Index {i} out of range for image_url column")
43
+ continue
44
+
45
+ image_url = df_emb["image_url"].iloc[i]
46
+ if image_url is not None:
47
+ documents.append(image_url)
48
+ else:
49
+ documents.append(None)
50
+
51
+ collection = initialize_collection(collection_name)
52
+
53
+ for i, d in enumerate(documents):
54
+ embeddings = embeddings_all[i]
55
+ embedding_id = str(i) # Convert index to string
56
+
57
+ if embeddings is None:
58
+ continue # Skip if no embedding
59
+
60
+ # Check if ID already exists
61
+ existing_entry = collection.get(ids=[embedding_id])
62
+
63
+ if existing_entry and existing_entry["ids"]: # If the ID is found, skip adding
64
+ continue
65
+
66
+ collection.add(
67
+ ids=[embedding_id],
68
+ embeddings=embeddings,
69
+ documents=[d]
70
+ )
71
+
72
+ return collection
73
+
74
+
75
+
76
+ model_name = "patrickjohncyh/fashion-clip"
77
+ device = "mps"
78
+ model = CLIPModel.from_pretrained(model_name).to(device)
79
+ processor = CLIPProcessor.from_pretrained(model_name)
80
+
81
+ def main_text_retrieve_images(text, result_query=None, n_retrieved=5):
82
+ #df_emb = pd.read_json("data/fashion_show_data_all_embeddings.json", lines=True)
83
+
84
+ dataset = load_dataset("traopia/fashion_show_data_all_embeddings.json")
85
+ # This returns a DatasetDict with splits as keys (usually 'train' by default).
86
+ # To get the whole dataset, you can access the first split like this:
87
+ split_name = list(dataset.keys())[0]
88
+ full_dataset = dataset[split_name]
89
+
90
+ # Convert to pandas DataFrame
91
+ df_emb = full_dataset.to_pandas()
92
+ df_emb = df_emb.drop_duplicates(subset='image_urls')
93
+ df_emb['fashion_clip_image'] = df_emb['fashion_clip_image'].apply(lambda x: x[0] if type(x) == list else None)
94
+ df_emb['image_url'] = df_emb['image_urls'].apply(lambda x: x[0] if x else None)
95
+ df_emb = df_emb.drop_duplicates(subset='image_url')
96
+
97
+ #print("DataFrame head:", df_emb.head()) # Debugging statement
98
+
99
+ if result_query:
100
+ df_small = pd.DataFrame(result_query, columns=["image_url"])
101
+ df_filtered = df_emb.merge(df_small[['image_url']], on='image_url', how='inner')
102
+ df_emb = df_filtered
103
+ # Generate a collection name based on the current timestamp
104
+ collection_name = f"collection_{datetime.now().strftime('%Y%m%d_%H%M%S')}"
105
+ collection = main_create_image_collection(df_emb, collection_name=collection_name)
106
+ else:
107
+ collection = main_create_image_collection(df_emb)
108
+
109
+ inputs = processor(text=[text], return_tensors="pt", padding=True, truncation=True, max_length=77).to(device)
110
+
111
+ with torch.no_grad():
112
+ text_features = model.get_text_features(**inputs).cpu().numpy() # Should work without crashing
113
+
114
+ results = collection.query(
115
+ query_embeddings=text_features[0],
116
+ n_results=n_retrieved
117
+ )
118
+ #print(results)
119
+ result_doc = pd.DataFrame(results['documents'][0], columns=["image_url"])
120
+ df_result = df_emb.merge(result_doc[['image_url']], on='image_url', how='inner')
121
+ # Remove columns fashion_clip_image, image_urls, and description
122
+ df_result = df_result.drop(columns=['fashion_clip_image', 'description', 'editor', 'publish_date', 'image_urls'])
123
+ return df_result.to_dict(orient='records')
124
+
125
+ if __name__ == "__main__":
126
+ text = "dress"
127
+ result = main_text_retrieve_images(text)
128
+ print(result)