Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat/units_from_session #22

Merged
merged 7 commits into from
Apr 26, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
69 changes: 35 additions & 34 deletions __init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,28 +13,27 @@

import tempfile
from os.path import join, isfile

from typing import Optional
import requests
from ovos_backend_client.api import WolframAlphaApi as _WA
from ovos_bus_client import Message
from ovos_bus_client.session import SessionManager
from ovos_config import Configuration
from ovos_plugin_manager.templates.solvers import QuestionSolver
from ovos_utils import classproperty
from ovos_utils.gui import can_use_gui
from ovos_utils.process_utils import RuntimeRequirements
from ovos_workshop.decorators import intent_handler
from ovos_workshop.skills.common_query_skill import CommonQuerySkill, CQSMatchLevel


class WolframAlphaApi(_WA):
def get_image(self, query):
def get_image(self, query: str, units: Optional[str] = None):
"""
query assured to be in self.default_lang
return path/url to a single image to acompany spoken_answer
"""
# TODO - extend backend-client method for picture
units = Configuration().get("system_unit", "metric")
units = units or Configuration().get("system_unit", "metric")
url = 'http://api.wolframalpha.com/v1/simple'
params = {"appid": self.credentials["wolfram"],
"i": query,
Expand All @@ -51,7 +50,7 @@ def get_image(self, query):

class WolframAlphaSolver(QuestionSolver):
priority = 25
enable_cache = True
enable_cache = False
enable_tx = True

def __init__(self, config=None):
Expand Down Expand Up @@ -123,7 +122,7 @@ def get_data(self, query, context=None):
query assured to be in self.default_lang
return a dict response
"""
units = Configuration().get("system_unit", "metric")
units = context.get("units") or Configuration().get("system_unit", "metric")
return self.api.full_results(query, units=units)

# image api (simple)
Expand All @@ -132,15 +131,16 @@ def get_image(self, query, context=None):
query assured to be in self.default_lang
return path/url to a single image to acompany spoken_answer
"""
return self.api.get_image(query)
units = context.get("units") or Configuration().get("system_unit", "metric")
return self.api.get_image(query, units)

# spoken answers api (spoken)
def get_spoken_answer(self, query, context):
"""
query assured to be in self.default_lang
return a single sentence text response
"""
units = Configuration().get("system_unit", "metric")
units = context.get("units") or Configuration().get("system_unit", "metric")
answer = self.api.spoken(query, units=units)
bad_answers = ["no spoken result available",
"wolfram alpha did not understand your input"]
Expand All @@ -158,7 +158,6 @@ def get_expanded_answer(self, query, context=None):
"summary": "speak this",
"img": "optional/path/or/url
}

"""
data = self.get_data(query, context)
# these are returned in spoken answer or otherwise unwanted
Expand Down Expand Up @@ -213,12 +212,12 @@ def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.session_results = {} # session_id: {}
self.wolfie = WolframAlphaSolver({
"units": self.config_core['system_unit'],
"appid": self.settings.get("api_key")
})

@classproperty
def runtime_requirements(self):
"""this skill requires internet"""
return RuntimeRequirements(internet_before_load=True,
network_before_load=True,
gui_before_load=False,
Expand All @@ -236,8 +235,10 @@ def handle_search(self, message: Message):
sess = SessionManager.get(message)
self.session_results[sess.session_id] = {"phrase": query,
"image": None,
"lang": sess.lang,
"system_unit": sess.system_unit,
"spoken_answer": ""}
response = self.ask_the_wolf(query)
response = self.ask_the_wolf(query, sess.lang, sess.system_unit)
if response:
self.session_results[sess.session_id]["spoken_answer"] = response
self.speak(response)
Expand All @@ -254,9 +255,11 @@ def CQS_match_query_phrase(self, phrase: str):
sess = SessionManager.get()
self.session_results[sess.session_id] = {"phrase": phrase,
"image": None,
"lang": sess.lang,
"system_unit": sess.system_unit,
"spoken_answer": None}

response = self.ask_the_wolf(phrase, sess.lang)
response = self.ask_the_wolf(phrase, sess.lang, sess.system_unit)
if response:
self.session_results[sess.session_id]["spoken_answer"] = response
self.log.debug(f"WolframAlpha response: {response}")
Expand All @@ -265,10 +268,20 @@ def CQS_match_query_phrase(self, phrase: str):

def CQS_action(self, phrase: str, data: dict):
""" If selected show gui """
self.display_wolfie()
# generate image for the query after skill was selected for speed
image = self.wolfie.visual_answer(phrase, context=data)
self.gui["wolfram_image"] = image or f"{self.root_dir}/res/logo.png"
# scrollable full result page
self.gui.show_page("wolf", override_idle=45)

# wolfram integration
def ask_the_wolf(self, query: str, lang: str = None):
def ask_the_wolf(self, query: str,
lang: Optional[str] = None,
units: Optional[str] = None):
units = units or self.system_unit
if units != "metric":
units = "nonmetric" # what wolfram api expects

lang = lang or self.lang
if lang.startswith("en"):
self.log.debug(f"skipping auto translation for wolfram alpha, "
Expand All @@ -278,25 +291,8 @@ def ask_the_wolf(self, query: str, lang: str = None):
self.log.info(f"enabling auto translation for wolfram alpha, "
f"{lang} is not supported internally")
WolframAlphaSolver.enable_tx = True
return self.wolfie.spoken_answer(query, context={"lang": lang})

def display_wolfie(self):
if not can_use_gui(self.bus):
return

# generate image for the last query this session made
# only after skill was selected for speed
sess = SessionManager.get()
res = self.session_results.get(sess.session_id)
if not res or not res["spoken_response"]:
return

image = res.get("image") or self.wolfie.visual_answer(res["phrase"],
context={"lang": self.lang})
if image:
self.gui["wolfram_image"] = image
# scrollable full result page
self.gui.show_page(join(self.root_dir, "ui", "wolf"), override_idle=45)
return self.wolfie.spoken_answer(query,
context={"lang": lang, "units": units})

def stop_session(self, sess):
if sess.session_id in self.session_results:
Expand All @@ -308,7 +304,12 @@ def stop_session(self, sess):

d = WolframAlphaSkill(bus=FakeBus(), skill_id="fake.wolf")

print(d.ask_the_wolf("what is the speed of light"))
print(d.ask_the_wolf("what is the speed of light", units="nonmetric")) # SI units regardless
# The speed of light has a value of about 300 million meters per second
print(d.ask_the_wolf("how tall is the eiffel tower", units="metric"))
print(d.ask_the_wolf("how tall is the eiffel tower", units="nonmetric"))
# The total height of the Eiffel Tower is 330 meters
# The total height of the Eiffel Tower is about 1083 feet

exit()

Expand Down
File renamed without changes.
2 changes: 1 addition & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
ovos-translate-server-plugin
ovos-config>=0.0.12
ovos-utils~=0.0, >=0.0.38
ovos_workshop~=0.0, >=0.0.15
ovos_workshop~=0.0, >=0.0.16a25
ovos-plugin-manager
File renamed without changes
2 changes: 1 addition & 1 deletion scripts/prepare_skillstore.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@

base_dir = dirname(dirname(__file__))
desktop_dir = join(base_dir, "res", "desktop")
android_ui = join(base_dir, "ui", "+android")
android_ui = join(base_dir, "qt5", "+android")
makedirs(desktop_dir, exist_ok=True)

readme = join(base_dir, "README.md")
Expand Down
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ def get_requirements(requirements_filename: str):


def find_resource_files():
resource_base_dirs = ("locale", "ui", "vocab", "dialog", "regex", "skill")
resource_base_dirs = ("locale", "qt5", "res")
base_dir = path.dirname(__file__)
package_data = ["*.json"]
for res in resource_base_dirs:
Expand Down
Loading