Skip to content

Commit

Permalink
Improvements to the English to Graql code
Browse files Browse the repository at this point in the history
  • Loading branch information
neomatrix369 committed Feb 6, 2020
1 parent 4b7132f commit 24cf0cd
Show file tree
Hide file tree
Showing 2 changed files with 109 additions and 119 deletions.
169 changes: 70 additions & 99 deletions examples/data/databases/graph/grakn/graql/english-graql-queries.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,86 +4,70 @@
main_queries_in_english = {
'SCHEMA': ['List the schema in this keyspace'],
'CUSTOMERS_CALLED_SINCE': ['From 2018-09-10 onwards, which customers called the person with phone number +86 921 547 9004?'
],
],
'CUSTOMERS_CALLED_SINCE': ['Since September 10th, which customers called the person with phone number +86 921 547 9004?'
],
],
'CUSTOMERS_CALLED_SINCE': ['Get me the customers of company "Telecom" who called the target person with phone number +86 921 547 9004 from September 14th onwards.'
],
],
'CUSTOMERS_CALLED_SINCE': ['Get me the customers of company "Telecom" who called the target person with phone number +86 921 547 9004 from September 10th onwards.'
],
],
'OVER_50_PHONE_CALLS_CAMBRIDGE': ['Who are the people aged under 20 who have received at least one phone call from a Cambridge customer aged over 50?'
],
],
'UNDER_20_PHONE_CALLS_LONDON': ['Who are the people who have received a call from a London customer aged over 50 who has previously called someone aged under 20?'
],
],
'OVER_50_UNDER_20_PHONE_CALLS': ['Get me the phone number of people who have received a call from a customer aged over 50 after this customer (potential person) made a call to another customer aged under 20.'
],
'COMMON_CUSTOMERS_MULTIPLE_NUMBERS': ['Who are the common contacts of customers with phone numbers +7 171 898 0853 and +370 351 224 5176?'
],
],
'COMMON_CUSTOMERS_SINGLE_NUMBER': ['Who are the customers who 1) have all called each other and 2) have all called person with phone number +48 894 777 5173 at least once?'
],
'COMMON_CUSTOMERS_MULTIPLE_NUMBERS': ['Get me the phone number of people who have received calls from both customer with phone number +7 171 898 0853 and customer with phone number +370 351 224 5176.'
],
],
'COMMON_CUSTOMERS_MULTIPLE_NUMBERS': ['Who are the common contacts of customers with phone numbers +7 171 898 0853 and +370 351 224 5176?'
],
'CALL_DURATION_COMPARISON': ['How does the average call duration among customers aged under 20 compare those aged over 40?'
],
],
}

alternative_queries_in_english = {
'SCHEMA': [
'Show me the schema',
'List the schema',
'List schema keyspace',
'What is the schema here',
'What is the schema',
'What is the schema here?',
'What is the schema?',
'Schema?',
'Schema please'
],
'CUSTOMERS_CALLED_SINCE': [
'From a date onwards which customers called another person with phone number'
],
'CUSTOMERS_CALLED_SINCE': [
'Since a date which customers called a person with phone number'
],

'CUSTOMERS_CALLED_SINCE': [
'Get customers of company Telecom who called target person with phone number from a date onwards'
],
'CUSTOMERS_CALLED_SINCE': [
'Get customers of company Telecom who called target person with phone number from a date onwards'
],
'OVER_50_PHONE_CALLS_CAMBRIDGE': [
'People aged under certain age received at least one phone call from a place customer from customer aged over certain age',
'Get phone number of people received calls from customer aged customer potential person who made calls to another customer aged under certain age'
],
'UNDER_20_PHONE_CALLS_LONDON?': [
'Who people received call from customer of certain place aged over certain age also called by someone aged under certain age',
'Get phone number of people received calls from customer aged customer potential person who made calls to another customer aged under certain age'
],
'COMMON_CUSTOMERS_MULTIPLE_NUMBERS': [
'Who are common contacts of customers with certain phone numbers'
],
'COMMON_CUSTOMERS_SINGLE_NUMBER': [
'Who are customers called other persons phone number least once',
'Who are customers one another phone',
"called atleast once"
],
'COMMON_CUSTOMERS_SINGLE_NUMBER': [
'Get phone number of people received calls from customer of certain age'
],
'CALL_DURATION_COMPARISON': [
'How average call duration among customers aged compare aged',
"how long did the call last"
]
}

graql_queries = {
'SCHEMA': [
"""match $x sub thing; get;""",
'The schema of the keyspace is as shown'],
'Show me the schema',
'List the schema',
'List schema keyspace',
'What is the schema here',
'What is the schema',
'What is the schema here?',
'What is the schema?',
'Schema?',
'Schema please',
],
'CUSTOMERS_CALLED_SINCE': ['From a date onwards which customers called another person with phone number'
,
'Since a date which customers called a person with phone number'
,
'Get customers of company Telecom who called target person with phone number from a date onwards'
],
'OVER_50_PHONE_CALLS_CAMBRIDGE': ['People aged under certain age received at least one phone call from a place customer from customer aged over certain age'
,
'Get phone number of people received calls from customer aged customer potential person who made calls to another customer aged under certain age'
],
'UNDER_20_PHONE_CALLS_LONDON?': ['Who people received call from customer of certain place aged over certain age also called by someone aged under certain age'
,
'Get phone number of people received calls from customer aged customer potential person who made calls to another customer aged under certain age'
],
'COMMON_CUSTOMERS_MULTIPLE_NUMBERS': ['Who are common contacts of customers with certain phone numbers'
,
'Get me the phone number of people who have received calls from both customer with phone number +7 171 898 0853 and customer with phone number +370 351 224 5176.'
],
'COMMON_CUSTOMERS_SINGLE_NUMBER': ['Who are customers called other persons phone number least once'
, "Who are customers who call one another's phone",
'Customers who have called each other atleast once',
'Get phone number of people received calls from customer of certain age'
],
'CALL_DURATION_COMPARISON': ['How average call duration among customers compared between ages'
, 'how long did the call last'],
}

'CUSTOMERS_CALLED_SINCE': [
"""
graql_queries = {
'SCHEMA': ["""match $x sub thing; get;""",
'The schema of the keyspace is as shown'],
'CUSTOMERS_CALLED_SINCE': ["""
match
$customer isa person, has phone-number $phone-number;
$company isa company, has name "Telecom";
Expand All @@ -93,11 +77,9 @@
$min-date == 2018-09-10T00:00:00; $started-at > $min-date;
get $phone-number;
""",
'These are numbers of the customers who called +86 921 547 9004 since 2018-09-10T00:00:00'
],

'UNDER_20_PHONE_CALLS_LONDON': [
"""
'These are numbers of the customers who called +86 921 547 9004 since 2018-09-10T00:00:00'
],
'UNDER_20_PHONE_CALLS_LONDON': ["""
match
$potential_caller isa person, has city "London", has age > 50;
$company isa company, has name "Telecom";
Expand All @@ -110,10 +92,9 @@
$target-call-date > $pattern-call-date;
get $phone-number;
""",
'Here are the phone numbers of the people (London calls)'],

'OVER_50_PHONE_CALLS_CAMBRIDGE': [
"""
'Here are the phone numbers of the people (London calls)'
],
'OVER_50_PHONE_CALLS_CAMBRIDGE': ["""
match
$potential_caller isa person, has city "Cambridge", has age > 50;
$company isa company, has name "Telecom";
Expand All @@ -126,10 +107,9 @@
$target-call-date > $pattern-call-date;
get $phone-number;
""",
'Here are the phone numbers of the people (Cambridge calls)'],

'COMMON_CUSTOMERS_MULTIPLE_NUMBERS': [
"""
'Here are the phone numbers of the people (Cambridge calls)'
],
'COMMON_CUSTOMERS_MULTIPLE_NUMBERS': ["""
match
$common-contact isa person, has phone-number $phone-number;
$customer-a isa person, has phone-number "+7 171 898 0853";
Expand All @@ -138,10 +118,8 @@
(caller: $customer-b, callee: $common-contact) isa call;
get $phone-number;
""",
'Here are the numbers of the common customers'],

'COMMON_CUSTOMERS_SINGLE_NUMBER': [
"""
'Here are the numbers of the common customers'],
'COMMON_CUSTOMERS_SINGLE_NUMBER': ["""
match
$target isa person, has phone-number "+48 894 777 5173";
$company isa company, has name "Telecom";
Expand All @@ -154,32 +132,25 @@
(caller: $customer-a, callee: $customer-b) isa call;
get $phone-number-a, $phone-number-b;
""",
'The customers who have called the single number are'
],

'CALL_DURATION_COMPARISON': [
[
"""
'The customers who have called the single number are'],
'CALL_DURATION_COMPARISON': [["""
match
$customer isa person, has age < 20;
$company isa company, has name "Telecom";
(customer: $customer, provider: $company) isa contract;
(caller: $customer, callee: $anyone) isa call, has duration $duration;
get $duration; mean $duration;
""",
'The average call duration between customers have been'
],

[
"""
'The average call duration between customers have been'
],
["""
match
$customer isa person, has age > 40;
$company isa company, has name "Telecom";
(customer: $customer, provider: $company) isa contract;
(caller: $customer, callee: $anyone) isa call, has duration $duration;
get $duration; mean $duration;
""",
'The average call duration between customers have been'
]
]
}
'The average call duration between customers have been'
]],
}
59 changes: 39 additions & 20 deletions examples/data/databases/graph/grakn/graql/grakn_console_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
warnings.filterwarnings('ignore')

from random import randint
import os
import sys

import time
Expand All @@ -25,7 +26,6 @@

pattern_matching=importlib.import_module("pattern-matching")


GRAQL_BOT = f"{Fore.GREEN}GraqlBot:{Style.RESET_ALL}"

# results from graql_query
Expand All @@ -34,12 +34,15 @@

keyspace_name = "phone_calls"

connection_to_grakn_exists = False
client = None
session = None
transaction = None

results_cache = {}

error_message_decorators = [
f"{GRAQL_BOT} Argh! We have an issue, but don't fret! It end ups up well",
f"{GRAQL_BOT} Argh! We have an issue, but don't fret! It will end ups fine though, trust me!",
f"{GRAQL_BOT} Oh no! Houston, we are not in Texas anymore!",
f"{GRAQL_BOT} Cow patter! Now this is not so cool. But I will get through fine!",
f"{GRAQL_BOT} Hallo, Hallo! Fawlty towers again!",
Expand All @@ -50,17 +53,19 @@
f"{GRAQL_BOT} Even though it's been a long day, and I'm a bit lazy today!",
f"{GRAQL_BOT} I could things faster if you like! I'm practising for the performance Olympics",
f"{GRAQL_BOT} Cow patter! Was I so slow? Could I have been faster",
f"{GRAQL_BOT} Thats faster than Usain Bolt",\
f"{GRAQL_BOT} Mo Farah couldn't do it as fast could he now?",
f"{GRAQL_BOT} That's faster than Usain Bolt",\
f"{GRAQL_BOT} Mo Farah couldn't do it as fast, could he now?",
]

def create_grakn_connection():
global client, session, transaction
global client, session, transaction, connection_to_grakn_exists

client = GraknClient(uri="localhost:48555")
session = client.session(keyspace=keyspace_name)
## create a transaction to talk to the Grakn server
transaction = session.transaction().read()
if not connection_to_grakn_exists:
client = GraknClient(uri="localhost:48555")
session = client.session(keyspace=keyspace_name)
## create a transaction to talk to the Grakn server
transaction = session.transaction().read()
connection_to_grakn_exists = True

def print_to_log(title, content):
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
Expand All @@ -82,7 +87,11 @@ def execute_user_query(query_code, query_response, transaction):
print(f"{GRAQL_BOT} Let me think, will take a moment, please be patient...")
iterator = transaction.query(graql_query)
answers = iterator.collect_concepts()
result = [answer.value() for answer in answers]
if hasattr(answers[0], 'value'):
result = [answer.value() for answer in answers]
else:
print(f"{GRAQL_BOT} 😲 Schema found, 😩 we don't have the expertise to build it at the moment, your best bet it to use Graql Console or Workbase")
return
results_cache.update({query_code: []})
results_cache[query_code] = result

Expand All @@ -100,6 +109,7 @@ def get_random_message(messages):
return messages[a_random_number]

def process_user_input(user_input):
create_grakn_connection()
try:
responses = pattern_matching.get_filtered_responses(user_input)
rows_returned = responses.shape[0] # 0=col count, 0=row count
Expand All @@ -116,7 +126,7 @@ def process_user_input(user_input):
q_numbers = []
for index, row in responses.iterrows():
q_numbers.append(index)
print(f" {Style.BRIGHT}{index}{Style.RESET_ALL} ---> {row['query_in_english']}")
print(f" q{Style.BRIGHT}{index}{Style.RESET_ALL} ---> {row['query_in_english']}")
meta_info = f" Code: {Fore.BLUE}{Style.BRIGHT}{row['query_code']} {Style.RESET_ALL} | Confidence: {Fore.GREEN}{row['confidence']}{Style.RESET_ALL}, {Fore.GREEN}{row['ratio']}%{Style.RESET_ALL})"
print(meta_info)
print("")
Expand All @@ -132,36 +142,43 @@ def process_user_input(user_input):
q_number_entered = int(q_number_entered)
query_code = responses['query_code'][q_number_entered]
graql_query_response = graql_queries.get(query_code)
execute_user_query(query_code, graql_query_response, transaction)
results = execute_user_query(query_code, graql_query_response, transaction)
print(f"{GRAQL_BOT} The above is based on your original input: '{user_input}'")
return results
except Exception as ex:
print("")
print(get_random_message(error_message_decorators))
print("")
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print(f"{GRAQL_BOT} {Fore.RED} Execution halted, due to an error:")
print(f"{GRAQL_BOT} {Fore.RED}{Style.BRIGHT} Execution halted, due to an error:")
print(ex)
print(Style.RESET_ALL)
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
create_grakn_connection()

def does_user_want_to_stop(user_input):
if user_input.lower().strip() == "exit":
print(f"{GRAQL_BOT} {Fore.YELLOW} Hastla vista! See you soon! {Style.RESET_ALL}")
sys.exit(0)

if __name__ == "__main__":
def does_user_want_to_clear_screen(user_input):
return user_input.lower().strip() == "cls" or user_input.lower().strip() == "clear"

def clear_screen():
if sys.platform == "win32":
os.system('cls')
else:
# Linux of OS X
os.system('clear')

if __name__ == "__main__":
'''
The code below:
- creates a Grakn client > session > transaction connected to the phone_calls keyspace
- runs a query based on the user's input
- closes the session
'''

create_grakn_connection()

results_cache = {}
clear_screen()

## get user's question selection
user_input = ""
Expand All @@ -173,5 +190,7 @@ def does_user_want_to_stop(user_input):
user_input = user_input.replace("\t", " ")

does_user_want_to_stop(user_input)

process_user_input(user_input)
if does_user_want_to_clear_screen(user_input):
clear_screen()
else:
process_user_input(user_input)

0 comments on commit 24cf0cd

Please sign in to comment.