text_prompt
stringlengths 100
17.7k
⌀ | code_prompt
stringlengths 7
9.86k
⌀ |
---|---|
<SYSTEM_TASK:>
Touch and scroll, moving by xoffset and yoffset.
<END_TASK>
<USER_TASK:>
Description:
def scroll(self, xoffset, yoffset):
"""
Touch and scroll, moving by xoffset and yoffset.
:Args:
- xoffset: X offset to scroll to.
- yoffset: Y offset to scroll to.
""" |
self._actions.append(lambda: self._driver.execute(
Command.TOUCH_SCROLL, {
'xoffset': int(xoffset),
'yoffset': int(yoffset)}))
return self |
<SYSTEM_TASK:>
Touch and scroll starting at on_element, moving by xoffset and yoffset.
<END_TASK>
<USER_TASK:>
Description:
def scroll_from_element(self, on_element, xoffset, yoffset):
"""
Touch and scroll starting at on_element, moving by xoffset and yoffset.
:Args:
- on_element: The element where scroll starts.
- xoffset: X offset to scroll to.
- yoffset: Y offset to scroll to.
""" |
self._actions.append(lambda: self._driver.execute(
Command.TOUCH_SCROLL, {
'element': on_element.id,
'xoffset': int(xoffset),
'yoffset': int(yoffset)}))
return self |
<SYSTEM_TASK:>
Flicks, starting anywhere on the screen.
<END_TASK>
<USER_TASK:>
Description:
def flick(self, xspeed, yspeed):
"""
Flicks, starting anywhere on the screen.
:Args:
- xspeed: The X speed in pixels per second.
- yspeed: The Y speed in pixels per second.
""" |
self._actions.append(lambda: self._driver.execute(
Command.FLICK, {
'xspeed': int(xspeed),
'yspeed': int(yspeed)}))
return self |
<SYSTEM_TASK:>
Flick starting at on_element, and moving by the xoffset and yoffset
<END_TASK>
<USER_TASK:>
Description:
def flick_element(self, on_element, xoffset, yoffset, speed):
"""
Flick starting at on_element, and moving by the xoffset and yoffset
with specified speed.
:Args:
- on_element: Flick will start at center of element.
- xoffset: X offset to flick to.
- yoffset: Y offset to flick to.
- speed: Pixels per second to flick.
""" |
self._actions.append(lambda: self._driver.execute(
Command.FLICK, {
'element': on_element.id,
'xoffset': int(xoffset),
'yoffset': int(yoffset),
'speed': int(speed)}))
return self |
<SYSTEM_TASK:>
Returns the element with focus, or BODY if nothing has focus.
<END_TASK>
<USER_TASK:>
Description:
def active_element(self):
"""
Returns the element with focus, or BODY if nothing has focus.
:Usage:
::
element = driver.switch_to.active_element
""" |
if self._driver.w3c:
return self._driver.execute(Command.W3C_GET_ACTIVE_ELEMENT)['value']
else:
return self._driver.execute(Command.GET_ACTIVE_ELEMENT)['value'] |
<SYSTEM_TASK:>
Switches focus to the specified frame, by index, name, or webelement.
<END_TASK>
<USER_TASK:>
Description:
def frame(self, frame_reference):
"""
Switches focus to the specified frame, by index, name, or webelement.
:Args:
- frame_reference: The name of the window to switch to, an integer representing the index,
or a webelement that is an (i)frame to switch to.
:Usage:
::
driver.switch_to.frame('frame_name')
driver.switch_to.frame(1)
driver.switch_to.frame(driver.find_elements_by_tag_name("iframe")[0])
""" |
if isinstance(frame_reference, basestring) and self._driver.w3c:
try:
frame_reference = self._driver.find_element(By.ID, frame_reference)
except NoSuchElementException:
try:
frame_reference = self._driver.find_element(By.NAME, frame_reference)
except NoSuchElementException:
raise NoSuchFrameException(frame_reference)
self._driver.execute(Command.SWITCH_TO_FRAME, {'id': frame_reference}) |
<SYSTEM_TASK:>
Switches to a new top-level browsing context.
<END_TASK>
<USER_TASK:>
Description:
def new_window(self, type_hint=None):
"""Switches to a new top-level browsing context.
The type hint can be one of "tab" or "window". If not specified the
browser will automatically select it.
:Usage:
::
driver.switch_to.new_window('tab')
""" |
value = self._driver.execute(Command.NEW_WINDOW, {'type': type_hint})['value']
self._w3c_window(value['handle']) |
<SYSTEM_TASK:>
Switches focus to the specified window.
<END_TASK>
<USER_TASK:>
Description:
def window(self, window_name):
"""
Switches focus to the specified window.
:Args:
- window_name: The name or window handle of the window to switch to.
:Usage:
::
driver.switch_to.window('main')
""" |
if self._driver.w3c:
self._w3c_window(window_name)
return
data = {'name': window_name}
self._driver.execute(Command.SWITCH_TO_WINDOW, data) |
<SYSTEM_TASK:>
Performs all stored actions.
<END_TASK>
<USER_TASK:>
Description:
def perform(self):
"""
Performs all stored actions.
""" |
if self._driver.w3c:
self.w3c_actions.perform()
else:
for action in self._actions:
action() |
<SYSTEM_TASK:>
Clears actions that are already stored locally and on the remote end
<END_TASK>
<USER_TASK:>
Description:
def reset_actions(self):
"""
Clears actions that are already stored locally and on the remote end
""" |
if self._driver.w3c:
self.w3c_actions.clear_actions()
self._actions = [] |
<SYSTEM_TASK:>
Holds down the left mouse button on an element.
<END_TASK>
<USER_TASK:>
Description:
def click_and_hold(self, on_element=None):
"""
Holds down the left mouse button on an element.
:Args:
- on_element: The element to mouse down.
If None, clicks on current mouse position.
""" |
if on_element:
self.move_to_element(on_element)
if self._driver.w3c:
self.w3c_actions.pointer_action.click_and_hold()
self.w3c_actions.key_action.pause()
else:
self._actions.append(lambda: self._driver.execute(
Command.MOUSE_DOWN, {}))
return self |
<SYSTEM_TASK:>
Double-clicks an element.
<END_TASK>
<USER_TASK:>
Description:
def double_click(self, on_element=None):
"""
Double-clicks an element.
:Args:
- on_element: The element to double-click.
If None, clicks on current mouse position.
""" |
if on_element:
self.move_to_element(on_element)
if self._driver.w3c:
self.w3c_actions.pointer_action.double_click()
for _ in range(4):
self.w3c_actions.key_action.pause()
else:
self._actions.append(lambda: self._driver.execute(
Command.DOUBLE_CLICK, {}))
return self |
<SYSTEM_TASK:>
Holds down the left mouse button on the source element,
<END_TASK>
<USER_TASK:>
Description:
def drag_and_drop(self, source, target):
"""
Holds down the left mouse button on the source element,
then moves to the target element and releases the mouse button.
:Args:
- source: The element to mouse down.
- target: The element to mouse up.
""" |
self.click_and_hold(source)
self.release(target)
return self |
<SYSTEM_TASK:>
Holds down the left mouse button on the source element,
<END_TASK>
<USER_TASK:>
Description:
def drag_and_drop_by_offset(self, source, xoffset, yoffset):
"""
Holds down the left mouse button on the source element,
then moves to the target offset and releases the mouse button.
:Args:
- source: The element to mouse down.
- xoffset: X offset to move to.
- yoffset: Y offset to move to.
""" |
self.click_and_hold(source)
self.move_by_offset(xoffset, yoffset)
self.release()
return self |
<SYSTEM_TASK:>
Moving the mouse to an offset from current mouse position.
<END_TASK>
<USER_TASK:>
Description:
def move_by_offset(self, xoffset, yoffset):
"""
Moving the mouse to an offset from current mouse position.
:Args:
- xoffset: X offset to move to, as a positive or negative integer.
- yoffset: Y offset to move to, as a positive or negative integer.
""" |
if self._driver.w3c:
self.w3c_actions.pointer_action.move_by(xoffset, yoffset)
self.w3c_actions.key_action.pause()
else:
self._actions.append(lambda: self._driver.execute(
Command.MOVE_TO, {
'xoffset': int(xoffset),
'yoffset': int(yoffset)}))
return self |
<SYSTEM_TASK:>
Moving the mouse to the middle of an element.
<END_TASK>
<USER_TASK:>
Description:
def move_to_element(self, to_element):
"""
Moving the mouse to the middle of an element.
:Args:
- to_element: The WebElement to move to.
""" |
if self._driver.w3c:
self.w3c_actions.pointer_action.move_to(to_element)
self.w3c_actions.key_action.pause()
else:
self._actions.append(lambda: self._driver.execute(
Command.MOVE_TO, {'element': to_element.id}))
return self |
<SYSTEM_TASK:>
Move the mouse by an offset of the specified element.
<END_TASK>
<USER_TASK:>
Description:
def move_to_element_with_offset(self, to_element, xoffset, yoffset):
"""
Move the mouse by an offset of the specified element.
Offsets are relative to the top-left corner of the element.
:Args:
- to_element: The WebElement to move to.
- xoffset: X offset to move to.
- yoffset: Y offset to move to.
""" |
if self._driver.w3c:
self.w3c_actions.pointer_action.move_to(to_element, xoffset, yoffset)
self.w3c_actions.key_action.pause()
else:
self._actions.append(
lambda: self._driver.execute(Command.MOVE_TO, {
'element': to_element.id,
'xoffset': int(xoffset),
'yoffset': int(yoffset)}))
return self |
<SYSTEM_TASK:>
Pause all inputs for the specified duration in seconds
<END_TASK>
<USER_TASK:>
Description:
def pause(self, seconds):
""" Pause all inputs for the specified duration in seconds """ |
if self._driver.w3c:
self.w3c_actions.pointer_action.pause(seconds)
self.w3c_actions.key_action.pause(seconds)
else:
self._actions.append(lambda: time.sleep(seconds))
return self |
<SYSTEM_TASK:>
Releasing a held mouse button on an element.
<END_TASK>
<USER_TASK:>
Description:
def release(self, on_element=None):
"""
Releasing a held mouse button on an element.
:Args:
- on_element: The element to mouse up.
If None, releases on current mouse position.
""" |
if on_element:
self.move_to_element(on_element)
if self._driver.w3c:
self.w3c_actions.pointer_action.release()
self.w3c_actions.key_action.pause()
else:
self._actions.append(lambda: self._driver.execute(Command.MOUSE_UP, {}))
return self |
<SYSTEM_TASK:>
Sends keys to current focused element.
<END_TASK>
<USER_TASK:>
Description:
def send_keys(self, *keys_to_send):
"""
Sends keys to current focused element.
:Args:
- keys_to_send: The keys to send. Modifier keys constants can be found in the
'Keys' class.
""" |
typing = keys_to_typing(keys_to_send)
if self._driver.w3c:
for key in typing:
self.key_down(key)
self.key_up(key)
else:
self._actions.append(lambda: self._driver.execute(
Command.SEND_KEYS_TO_ACTIVE_ELEMENT, {'value': typing}))
return self |
<SYSTEM_TASK:>
Sends keys to an element.
<END_TASK>
<USER_TASK:>
Description:
def send_keys_to_element(self, element, *keys_to_send):
"""
Sends keys to an element.
:Args:
- element: The element to send keys.
- keys_to_send: The keys to send. Modifier keys constants can be found in the
'Keys' class.
""" |
self.click(element)
self.send_keys(*keys_to_send)
return self |
<SYSTEM_TASK:>
Marshals the IE options to the correct object.
<END_TASK>
<USER_TASK:>
Description:
def to_capabilities(self):
"""Marshals the IE options to the correct object.""" |
caps = self._caps
opts = self._options.copy()
if len(self._arguments) > 0:
opts[self.SWITCHES] = ' '.join(self._arguments)
if len(self._additional) > 0:
opts.update(self._additional)
if len(opts) > 0:
caps[Options.KEY] = opts
return caps |
<SYSTEM_TASK:>
Adds the path to the extension to a list that will be used to extract it
<END_TASK>
<USER_TASK:>
Description:
def add_extension(self, extension):
"""
Adds the path to the extension to a list that will be used to extract it
to the ChromeDriver
:Args:
- extension: path to the \\*.crx file
""" |
if extension:
extension_to_add = os.path.abspath(os.path.expanduser(extension))
if os.path.exists(extension_to_add):
self._extension_files.append(extension_to_add)
else:
raise IOError("Path to the extension doesn't exist")
else:
raise ValueError("argument can not be null") |
<SYSTEM_TASK:>
Creates a capabilities with all the options that have been set
<END_TASK>
<USER_TASK:>
Description:
def to_capabilities(self):
"""
Creates a capabilities with all the options that have been set
:Returns: A dictionary with everything
""" |
caps = self._caps
chrome_options = self.experimental_options.copy()
chrome_options["extensions"] = self.extensions
if self.binary_location:
chrome_options["binary"] = self.binary_location
chrome_options["args"] = self.arguments
if self.debugger_address:
chrome_options["debuggerAddress"] = self.debugger_address
caps[self.KEY] = chrome_options
return caps |
<SYSTEM_TASK:>
Dismisses the alert available.
<END_TASK>
<USER_TASK:>
Description:
def dismiss(self):
"""
Dismisses the alert available.
""" |
if self.driver.w3c:
self.driver.execute(Command.W3C_DISMISS_ALERT)
else:
self.driver.execute(Command.DISMISS_ALERT) |
<SYSTEM_TASK:>
Accepts the alert available.
<END_TASK>
<USER_TASK:>
Description:
def accept(self):
"""
Accepts the alert available.
Usage::
Alert(driver).accept() # Confirm a alert dialog.
""" |
if self.driver.w3c:
self.driver.execute(Command.W3C_ACCEPT_ALERT)
else:
self.driver.execute(Command.ACCEPT_ALERT) |
<SYSTEM_TASK:>
Send Keys to the Alert.
<END_TASK>
<USER_TASK:>
Description:
def send_keys(self, keysToSend):
"""
Send Keys to the Alert.
:Args:
- keysToSend: The text to be sent to Alert.
""" |
if self.driver.w3c:
self.driver.execute(Command.W3C_SET_ALERT_VALUE, {'value': keys_to_typing(keysToSend),
'text': keysToSend})
else:
self.driver.execute(Command.SET_ALERT_VALUE, {'text': keysToSend}) |
<SYSTEM_TASK:>
Sets the port that WebDriver will be running on
<END_TASK>
<USER_TASK:>
Description:
def port(self, port):
"""
Sets the port that WebDriver will be running on
""" |
if not isinstance(port, int):
raise WebDriverException("Port needs to be an integer")
try:
port = int(port)
if port < 1 or port > 65535:
raise WebDriverException("Port number must be in the range 1..65535")
except (ValueError, TypeError):
raise WebDriverException("Port needs to be an integer")
self._port = port
self.set_preference("webdriver_firefox_port", self._port) |
<SYSTEM_TASK:>
A zipped, base64 encoded string of profile directory
<END_TASK>
<USER_TASK:>
Description:
def encoded(self):
"""
A zipped, base64 encoded string of profile directory
for use with remote WebDriver JSON wire protocol
""" |
self.update_preferences()
fp = BytesIO()
zipped = zipfile.ZipFile(fp, 'w', zipfile.ZIP_DEFLATED)
path_root = len(self.path) + 1 # account for trailing slash
for base, dirs, files in os.walk(self.path):
for fyle in files:
filename = os.path.join(base, fyle)
zipped.write(filename, filename[path_root:])
zipped.close()
return base64.b64encode(fp.getvalue()).decode('UTF-8') |
<SYSTEM_TASK:>
writes the current user prefs dictionary to disk
<END_TASK>
<USER_TASK:>
Description:
def _write_user_prefs(self, user_prefs):
"""
writes the current user prefs dictionary to disk
""" |
with open(self.userPrefs, "w") as f:
for key, value in user_prefs.items():
f.write('user_pref("%s", %s);\n' % (key, json.dumps(value))) |
<SYSTEM_TASK:>
Gets the given property of the element.
<END_TASK>
<USER_TASK:>
Description:
def get_property(self, name):
"""
Gets the given property of the element.
:Args:
- name - Name of the property to retrieve.
:Usage:
::
text_length = target_element.get_property("text_length")
""" |
try:
return self._execute(Command.GET_ELEMENT_PROPERTY, {"name": name})["value"]
except WebDriverException:
# if we hit an end point that doesnt understand getElementProperty lets fake it
return self.parent.execute_script('return arguments[0][arguments[1]]', self, name) |
<SYSTEM_TASK:>
Gets the given attribute or property of the element.
<END_TASK>
<USER_TASK:>
Description:
def get_attribute(self, name):
"""Gets the given attribute or property of the element.
This method will first try to return the value of a property with the
given name. If a property with that name doesn't exist, it returns the
value of the attribute with the same name. If there's no attribute with
that name, ``None`` is returned.
Values which are considered truthy, that is equals "true" or "false",
are returned as booleans. All other non-``None`` values are returned
as strings. For attributes or properties which do not exist, ``None``
is returned.
:Args:
- name - Name of the attribute/property to retrieve.
Example::
# Check if the "active" CSS class is applied to an element.
is_active = "active" in target_element.get_attribute("class")
""" |
attributeValue = ''
if self._w3c:
attributeValue = self.parent.execute_script(
"return (%s).apply(null, arguments);" % getAttribute_js,
self, name)
else:
resp = self._execute(Command.GET_ELEMENT_ATTRIBUTE, {'name': name})
attributeValue = resp.get('value')
if attributeValue is not None:
if name != 'value' and attributeValue.lower() in ('true', 'false'):
attributeValue = attributeValue.lower()
return attributeValue |
<SYSTEM_TASK:>
Simulates typing into the element.
<END_TASK>
<USER_TASK:>
Description:
def send_keys(self, *value):
"""Simulates typing into the element.
:Args:
- value - A string for typing, or setting form fields. For setting
file inputs, this could be a local file path.
Use this to send simple key events or to fill out form fields::
form_textfield = driver.find_element_by_name('username')
form_textfield.send_keys("admin")
This can also be used to set file inputs.
::
file_input = driver.find_element_by_name('profilePic')
file_input.send_keys("path/to/profilepic.gif")
# Generally it's better to wrap the file path in one of the methods
# in os.path to return the actual path to support cross OS testing.
# file_input.send_keys(os.path.abspath("path/to/profilepic.gif"))
""" |
# transfer file to another machine only if remote driver is used
# the same behaviour as for java binding
if self.parent._is_remote:
local_file = self.parent.file_detector.is_local_file(*value)
if local_file is not None:
value = self._upload(local_file)
self._execute(Command.SEND_KEYS_TO_ELEMENT,
{'text': "".join(keys_to_typing(value)),
'value': keys_to_typing(value)}) |
<SYSTEM_TASK:>
Whether the element is visible to a user.
<END_TASK>
<USER_TASK:>
Description:
def is_displayed(self):
"""Whether the element is visible to a user.""" |
# Only go into this conditional for browsers that don't use the atom themselves
if self._w3c:
return self.parent.execute_script(
"return (%s).apply(null, arguments);" % isDisplayed_js,
self)
else:
return self._execute(Command.IS_ELEMENT_DISPLAYED)['value'] |
<SYSTEM_TASK:>
THIS PROPERTY MAY CHANGE WITHOUT WARNING. Use this to discover
<END_TASK>
<USER_TASK:>
Description:
def location_once_scrolled_into_view(self):
"""THIS PROPERTY MAY CHANGE WITHOUT WARNING. Use this to discover
where on the screen an element is so that we can click it. This method
should cause the element to be scrolled into view.
Returns the top lefthand corner location on the screen, or ``None`` if
the element is not visible.
""" |
if self._w3c:
old_loc = self._execute(Command.W3C_EXECUTE_SCRIPT, {
'script': "arguments[0].scrollIntoView(true); return arguments[0].getBoundingClientRect()",
'args': [self]})['value']
return {"x": round(old_loc['x']),
"y": round(old_loc['y'])}
else:
return self._execute(Command.GET_ELEMENT_LOCATION_ONCE_SCROLLED_INTO_VIEW)['value'] |
<SYSTEM_TASK:>
The location of the element in the renderable canvas.
<END_TASK>
<USER_TASK:>
Description:
def location(self):
"""The location of the element in the renderable canvas.""" |
if self._w3c:
old_loc = self._execute(Command.GET_ELEMENT_RECT)['value']
else:
old_loc = self._execute(Command.GET_ELEMENT_LOCATION)['value']
new_loc = {"x": round(old_loc['x']),
"y": round(old_loc['y'])}
return new_loc |
<SYSTEM_TASK:>
A dictionary with the size and location of the element.
<END_TASK>
<USER_TASK:>
Description:
def rect(self):
"""A dictionary with the size and location of the element.""" |
if self._w3c:
return self._execute(Command.GET_ELEMENT_RECT)['value']
else:
rect = self.size.copy()
rect.update(self.location)
return rect |
<SYSTEM_TASK:>
Saves a screenshot of the current element to a PNG image file. Returns
<END_TASK>
<USER_TASK:>
Description:
def screenshot(self, filename):
"""
Saves a screenshot of the current element to a PNG image file. Returns
False if there is any IOError, else returns True. Use full paths in
your filename.
:Args:
- filename: The full path you wish to save your screenshot to. This
should end with a `.png` extension.
:Usage:
::
element.screenshot('/Screenshots/foo.png')
""" |
if not filename.lower().endswith('.png'):
warnings.warn("name used for saved screenshot does not match file "
"type. It should end with a `.png` extension", UserWarning)
png = self.screenshot_as_png
try:
with open(filename, 'wb') as f:
f.write(png)
except IOError:
return False
finally:
del png
return True |
<SYSTEM_TASK:>
Executes a command against the underlying HTML element.
<END_TASK>
<USER_TASK:>
Description:
def _execute(self, command, params=None):
"""Executes a command against the underlying HTML element.
Args:
command: The name of the command to _execute as a string.
params: A dictionary of named parameters to send with the command.
Returns:
The command's JSON response loaded into a dictionary object.
""" |
if not params:
params = {}
params['id'] = self._id
return self._parent.execute(command, params) |
<SYSTEM_TASK:>
Closes the browser and shuts down the WebKitGTKDriver executable
<END_TASK>
<USER_TASK:>
Description:
def quit(self):
"""
Closes the browser and shuts down the WebKitGTKDriver executable
that is started when starting the WebKitGTKDriver
""" |
try:
RemoteWebDriver.quit(self)
except http_client.BadStatusLine:
pass
finally:
self.service.stop() |
<SYSTEM_TASK:>
Starts the Service.
<END_TASK>
<USER_TASK:>
Description:
def start(self):
"""
Starts the Service.
:Exceptions:
- WebDriverException : Raised either when it can't start the service
or when it can't connect to the service
""" |
try:
cmd = [self.path]
cmd.extend(self.command_line_args())
self.process = subprocess.Popen(cmd, env=self.env,
close_fds=platform.system() != 'Windows',
stdout=self.log_file,
stderr=self.log_file,
stdin=PIPE)
except TypeError:
raise
except OSError as err:
if err.errno == errno.ENOENT:
raise WebDriverException(
"'%s' executable needs to be in PATH. %s" % (
os.path.basename(self.path), self.start_error_message)
)
elif err.errno == errno.EACCES:
raise WebDriverException(
"'%s' executable may have wrong permissions. %s" % (
os.path.basename(self.path), self.start_error_message)
)
else:
raise
except Exception as e:
raise WebDriverException(
"The executable %s needs to be available in the path. %s\n%s" %
(os.path.basename(self.path), self.start_error_message, str(e)))
count = 0
while True:
self.assert_process_still_running()
if self.is_connectable():
break
count += 1
time.sleep(1)
if count == 30:
raise WebDriverException("Can not connect to the Service %s" % self.path) |
<SYSTEM_TASK:>
Launches the browser for the given profile name.
<END_TASK>
<USER_TASK:>
Description:
def launch_browser(self, profile, timeout=30):
"""Launches the browser for the given profile name.
It is assumed the profile already exists.
""" |
self.profile = profile
self._start_from_profile_path(self.profile.path)
self._wait_until_connectable(timeout=timeout) |
<SYSTEM_TASK:>
Kill the browser.
<END_TASK>
<USER_TASK:>
Description:
def kill(self):
"""Kill the browser.
This is useful when the browser is stuck.
""" |
if self.process:
self.process.kill()
self.process.wait() |
<SYSTEM_TASK:>
Blocks until the extension is connectable in the firefox.
<END_TASK>
<USER_TASK:>
Description:
def _wait_until_connectable(self, timeout=30):
"""Blocks until the extension is connectable in the firefox.""" |
count = 0
while not utils.is_connectable(self.profile.port):
if self.process.poll() is not None:
# Browser has exited
raise WebDriverException(
"The browser appears to have exited "
"before we could connect. If you specified a log_file in "
"the FirefoxBinary constructor, check it for details.")
if count >= timeout:
self.kill()
raise WebDriverException(
"Can't load the profile. Possible firefox version mismatch. "
"You must use GeckoDriver instead for Firefox 48+. Profile "
"Dir: %s If you specified a log_file in the "
"FirefoxBinary constructor, check it for details."
% (self.profile.path))
count += 1
time.sleep(1)
return True |
<SYSTEM_TASK:>
Return the command to start firefox.
<END_TASK>
<USER_TASK:>
Description:
def _get_firefox_start_cmd(self):
"""Return the command to start firefox.""" |
start_cmd = ""
if platform.system() == "Darwin":
start_cmd = "/Applications/Firefox.app/Contents/MacOS/firefox-bin"
# fallback to homebrew installation for mac users
if not os.path.exists(start_cmd):
start_cmd = os.path.expanduser("~") + start_cmd
elif platform.system() == "Windows":
start_cmd = (self._find_exe_in_registry() or self._default_windows_location())
elif platform.system() == 'Java' and os._name == 'nt':
start_cmd = self._default_windows_location()
else:
for ffname in ["firefox", "iceweasel"]:
start_cmd = self.which(ffname)
if start_cmd is not None:
break
else:
# couldn't find firefox on the system path
raise RuntimeError(
"Could not find firefox in your system PATH." +
" Please specify the firefox binary location or install firefox")
return start_cmd |
<SYSTEM_TASK:>
Returns the fully qualified path by searching Path of the given
<END_TASK>
<USER_TASK:>
Description:
def which(self, fname):
"""Returns the fully qualified path by searching Path of the given
name""" |
for pe in os.environ['PATH'].split(os.pathsep):
checkname = os.path.join(pe, fname)
if os.access(checkname, os.X_OK) and not os.path.isdir(checkname):
return checkname
return None |
<SYSTEM_TASK:>
Get headers for remote request.
<END_TASK>
<USER_TASK:>
Description:
def get_remote_connection_headers(cls, parsed_url, keep_alive=False):
"""
Get headers for remote request.
:Args:
- parsed_url - The parsed url
- keep_alive (Boolean) - Is this a keep-alive connection (default: False)
""" |
system = platform.system().lower()
if system == "darwin":
system = "mac"
headers = {
'Accept': 'application/json',
'Content-Type': 'application/json;charset=UTF-8',
'User-Agent': 'selenium/{} (python {})'.format(__version__, system)
}
if parsed_url.username:
base64string = base64.b64encode('{0.username}:{0.password}'.format(parsed_url).encode())
headers.update({
'Authorization': 'Basic {}'.format(base64string.decode())
})
if keep_alive:
headers.update({
'Connection': 'keep-alive'
})
return headers |
<SYSTEM_TASK:>
Send a command to the remote server.
<END_TASK>
<USER_TASK:>
Description:
def execute(self, command, params):
"""
Send a command to the remote server.
Any path subtitutions required for the URL mapped to the command should be
included in the command parameters.
:Args:
- command - A string specifying the command to execute.
- params - A dictionary of named parameters to send with the command as
its JSON payload.
""" |
command_info = self._commands[command]
assert command_info is not None, 'Unrecognised command %s' % command
path = string.Template(command_info[1]).substitute(params)
if hasattr(self, 'w3c') and self.w3c and isinstance(params, dict) and 'sessionId' in params:
del params['sessionId']
data = utils.dump_json(params)
url = '%s%s' % (self._url, path)
return self._request(command_info[0], url, body=data) |
<SYSTEM_TASK:>
Send an HTTP request to the remote server.
<END_TASK>
<USER_TASK:>
Description:
def _request(self, method, url, body=None):
"""
Send an HTTP request to the remote server.
:Args:
- method - A string for the HTTP method to send the request with.
- url - A string for the URL to send the request to.
- body - A string for request body. Ignored unless method is POST or PUT.
:Returns:
A dictionary with the server's parsed JSON response.
""" |
LOGGER.debug('%s %s %s' % (method, url, body))
parsed_url = parse.urlparse(url)
headers = self.get_remote_connection_headers(parsed_url, self.keep_alive)
resp = None
if body and method != 'POST' and method != 'PUT':
body = None
if self.keep_alive:
resp = self._conn.request(method, url, body=body, headers=headers)
statuscode = resp.status
else:
http = urllib3.PoolManager(timeout=self._timeout)
resp = http.request(method, url, body=body, headers=headers)
statuscode = resp.status
if not hasattr(resp, 'getheader'):
if hasattr(resp.headers, 'getheader'):
resp.getheader = lambda x: resp.headers.getheader(x)
elif hasattr(resp.headers, 'get'):
resp.getheader = lambda x: resp.headers.get(x)
data = resp.data.decode('UTF-8')
try:
if 300 <= statuscode < 304:
return self._request('GET', resp.getheader('location'))
if 399 < statuscode <= 500:
return {'status': statuscode, 'value': data}
content_type = []
if resp.getheader('Content-Type') is not None:
content_type = resp.getheader('Content-Type').split(';')
if not any([x.startswith('image/png') for x in content_type]):
try:
data = utils.load_json(data.strip())
except ValueError:
if 199 < statuscode < 300:
status = ErrorCode.SUCCESS
else:
status = ErrorCode.UNKNOWN_ERROR
return {'status': status, 'value': data.strip()}
# Some of the drivers incorrectly return a response
# with no 'value' field when they should return null.
if 'value' not in data:
data['value'] = None
return data
else:
data = {'status': 0, 'value': data}
return data
finally:
LOGGER.debug("Finished Request")
resp.close() |
<SYSTEM_TASK:>
Returns a list of all selected options belonging to this select tag
<END_TASK>
<USER_TASK:>
Description:
def all_selected_options(self):
"""Returns a list of all selected options belonging to this select tag""" |
ret = []
for opt in self.options:
if opt.is_selected():
ret.append(opt)
return ret |
<SYSTEM_TASK:>
Select the option at the given index. This is done by examing the "index" attribute of an
<END_TASK>
<USER_TASK:>
Description:
def select_by_index(self, index):
"""Select the option at the given index. This is done by examing the "index" attribute of an
element, and not merely by counting.
:Args:
- index - The option at this index will be selected
throws NoSuchElementException If there is no option with specified index in SELECT
""" |
match = str(index)
for opt in self.options:
if opt.get_attribute("index") == match:
self._setSelected(opt)
return
raise NoSuchElementException("Could not locate element with index %d" % index) |
<SYSTEM_TASK:>
Clear all selected entries. This is only valid when the SELECT supports multiple selections.
<END_TASK>
<USER_TASK:>
Description:
def deselect_all(self):
"""Clear all selected entries. This is only valid when the SELECT supports multiple selections.
throws NotImplementedError If the SELECT does not support multiple selections
""" |
if not self.is_multiple:
raise NotImplementedError("You may only deselect all options of a multi-select")
for opt in self.options:
self._unsetSelected(opt) |
<SYSTEM_TASK:>
Deselect the option at the given index. This is done by examing the "index" attribute of an
<END_TASK>
<USER_TASK:>
Description:
def deselect_by_index(self, index):
"""Deselect the option at the given index. This is done by examing the "index" attribute of an
element, and not merely by counting.
:Args:
- index - The option at this index will be deselected
throws NoSuchElementException If there is no option with specified index in SELECT
""" |
if not self.is_multiple:
raise NotImplementedError("You may only deselect options of a multi-select")
for opt in self.options:
if opt.get_attribute("index") == str(index):
self._unsetSelected(opt)
return
raise NoSuchElementException("Could not locate element with index %d" % index) |
<SYSTEM_TASK:>
Uploads a file to Google Cloud Storage.
<END_TASK>
<USER_TASK:>
Description:
def _upload(auth_http, project_id, bucket_name, file_path, object_name, acl):
"""Uploads a file to Google Cloud Storage.
Args:
auth_http: An authorized httplib2.Http instance.
project_id: The project to upload to.
bucket_name: The bucket to upload to.
file_path: Path to the file to upload.
object_name: The name within the bucket to upload to.
acl: The ACL to assign to the uploaded file.
""" |
with open(file_path, 'rb') as f:
data = f.read()
content_type, content_encoding = mimetypes.guess_type(file_path)
headers = {
'x-goog-project-id': project_id,
'x-goog-api-version': API_VERSION,
'x-goog-acl': acl,
'Content-Length': '%d' % len(data)
}
if content_type: headers['Content-Type'] = content_type
if content_type: headers['Content-Encoding'] = content_encoding
try:
response, content = auth_http.request(
'http://%s.storage.googleapis.com/%s' % (bucket_name, object_name),
method='PUT',
headers=headers,
body=data)
except httplib2.ServerNotFoundError, se:
raise Error(404, 'Server not found.')
if response.status >= 300:
raise Error(response.status, response.reason)
return content |
<SYSTEM_TASK:>
Runs the OAuth 2.0 installed application flow.
<END_TASK>
<USER_TASK:>
Description:
def _authenticate(secrets_file):
"""Runs the OAuth 2.0 installed application flow.
Returns:
An authorized httplib2.Http instance.
""" |
flow = oauthclient.flow_from_clientsecrets(
secrets_file,
scope=OAUTH_SCOPE,
message=('Failed to initialized OAuth 2.0 flow with secrets '
'file: %s' % secrets_file))
storage = oauthfile.Storage(OAUTH_CREDENTIALS_FILE)
credentials = storage.get()
if credentials is None or credentials.invalid:
credentials = oauthtools.run_flow(flow, storage, oauthtools.argparser.parse_args(args=[]))
http = httplib2.Http()
return credentials.authorize(http) |
<SYSTEM_TASK:>
Sets autodetect setting.
<END_TASK>
<USER_TASK:>
Description:
def auto_detect(self, value):
"""
Sets autodetect setting.
:Args:
- value: The autodetect value.
""" |
if isinstance(value, bool):
if self.autodetect is not value:
self._verify_proxy_type_compatibility(ProxyType.AUTODETECT)
self.proxyType = ProxyType.AUTODETECT
self.autodetect = value
else:
raise ValueError("Autodetect proxy value needs to be a boolean") |
<SYSTEM_TASK:>
Sets socks proxy username setting.
<END_TASK>
<USER_TASK:>
Description:
def socks_username(self, value):
"""
Sets socks proxy username setting.
:Args:
- value: The socks proxy username value.
""" |
self._verify_proxy_type_compatibility(ProxyType.MANUAL)
self.proxyType = ProxyType.MANUAL
self.socksUsername = value |
<SYSTEM_TASK:>
Sets socks proxy password setting.
<END_TASK>
<USER_TASK:>
Description:
def socks_password(self, value):
"""
Sets socks proxy password setting.
:Args:
- value: The socks proxy password value.
""" |
self._verify_proxy_type_compatibility(ProxyType.MANUAL)
self.proxyType = ProxyType.MANUAL
self.socksPassword = value |
<SYSTEM_TASK:>
Adds proxy information as capability in specified capabilities.
<END_TASK>
<USER_TASK:>
Description:
def add_to_capabilities(self, capabilities):
"""
Adds proxy information as capability in specified capabilities.
:Args:
- capabilities: The capabilities to which proxy will be added.
""" |
proxy_caps = {}
proxy_caps['proxyType'] = self.proxyType['string']
if self.autodetect:
proxy_caps['autodetect'] = self.autodetect
if self.ftpProxy:
proxy_caps['ftpProxy'] = self.ftpProxy
if self.httpProxy:
proxy_caps['httpProxy'] = self.httpProxy
if self.proxyAutoconfigUrl:
proxy_caps['proxyAutoconfigUrl'] = self.proxyAutoconfigUrl
if self.sslProxy:
proxy_caps['sslProxy'] = self.sslProxy
if self.noProxy:
proxy_caps['noProxy'] = self.noProxy
if self.socksProxy:
proxy_caps['socksProxy'] = self.socksProxy
if self.socksUsername:
proxy_caps['socksUsername'] = self.socksUsername
if self.socksPassword:
proxy_caps['socksPassword'] = self.socksPassword
capabilities['proxy'] = proxy_caps |
<SYSTEM_TASK:>
Resolve a hostname to an IP, preferring IPv4 addresses.
<END_TASK>
<USER_TASK:>
Description:
def find_connectable_ip(host, port=None):
"""Resolve a hostname to an IP, preferring IPv4 addresses.
We prefer IPv4 so that we don't change behavior from previous IPv4-only
implementations, and because some drivers (e.g., FirefoxDriver) do not
support IPv6 connections.
If the optional port number is provided, only IPs that listen on the given
port are considered.
:Args:
- host - A hostname.
- port - Optional port number.
:Returns:
A single IP address, as a string. If any IPv4 address is found, one is
returned. Otherwise, if any IPv6 address is found, one is returned. If
neither, then None is returned.
""" |
try:
addrinfos = socket.getaddrinfo(host, None)
except socket.gaierror:
return None
ip = None
for family, _, _, _, sockaddr in addrinfos:
connectable = True
if port:
connectable = is_connectable(port, sockaddr[0])
if connectable and family == socket.AF_INET:
return sockaddr[0]
if connectable and not ip and family == socket.AF_INET6:
ip = sockaddr[0]
return ip |
<SYSTEM_TASK:>
Joins a hostname and port together.
<END_TASK>
<USER_TASK:>
Description:
def join_host_port(host, port):
"""Joins a hostname and port together.
This is a minimal implementation intended to cope with IPv6 literals. For
example, _join_host_port('::1', 80) == '[::1]:80'.
:Args:
- host - A hostname.
- port - An integer port.
""" |
if ':' in host and not host.startswith('['):
return '[%s]:%d' % (host, port)
return '%s:%d' % (host, port) |
<SYSTEM_TASK:>
Tries to connect to the server at port to see if it is running.
<END_TASK>
<USER_TASK:>
Description:
def is_connectable(port, host="localhost"):
"""
Tries to connect to the server at port to see if it is running.
:Args:
- port - The port to connect.
""" |
socket_ = None
try:
socket_ = socket.create_connection((host, port), 1)
result = True
except _is_connectable_exceptions:
result = False
finally:
if socket_:
socket_.close()
return result |
<SYSTEM_TASK:>
Processes the values that will be typed in the element.
<END_TASK>
<USER_TASK:>
Description:
def keys_to_typing(value):
"""Processes the values that will be typed in the element.""" |
typing = []
for val in value:
if isinstance(val, Keys):
typing.append(val)
elif isinstance(val, int):
val = str(val)
for i in range(len(val)):
typing.append(val[i])
else:
for i in range(len(val)):
typing.append(val[i])
return typing |
<SYSTEM_TASK:>
Doc method extension for saving the current state as a displaCy
<END_TASK>
<USER_TASK:>
Description:
def to_html(doc, output="/tmp", style="dep"):
"""Doc method extension for saving the current state as a displaCy
visualization.
""" |
# generate filename from first six non-punct tokens
file_name = "-".join([w.text for w in doc[:6] if not w.is_punct]) + ".html"
html = displacy.render(doc, style=style, page=True) # render markup
if output is not None:
output_path = Path(output)
if not output_path.exists():
output_path.mkdir()
output_file = Path(output) / file_name
output_file.open("w", encoding="utf-8").write(html) # save to file
print("Saved HTML to {}".format(output_file))
else:
print(html) |
<SYSTEM_TASK:>
Get the tokens from the original Doc that are also in the comparison Doc.
<END_TASK>
<USER_TASK:>
Description:
def overlap_tokens(doc, other_doc):
"""Get the tokens from the original Doc that are also in the comparison Doc.
""" |
overlap = []
other_tokens = [token.text for token in other_doc]
for token in doc:
if token.text in other_tokens:
overlap.append(token)
return overlap |
<SYSTEM_TASK:>
Convert IOB files into JSON format for use with train cli.
<END_TASK>
<USER_TASK:>
Description:
def iob2json(input_data, n_sents=10, *args, **kwargs):
"""
Convert IOB files into JSON format for use with train cli.
""" |
docs = []
for group in minibatch(docs, n_sents):
group = list(group)
first = group.pop(0)
to_extend = first["paragraphs"][0]["sentences"]
for sent in group[1:]:
to_extend.extend(sent["paragraphs"][0]["sentences"])
docs.append(first)
return docs |
<SYSTEM_TASK:>
Render displaCy visualisation.
<END_TASK>
<USER_TASK:>
Description:
def render(
docs, style="dep", page=False, minify=False, jupyter=None, options={}, manual=False
):
"""Render displaCy visualisation.
docs (list or Doc): Document(s) to visualise.
style (unicode): Visualisation style, 'dep' or 'ent'.
page (bool): Render markup as full HTML page.
minify (bool): Minify HTML markup.
jupyter (bool): Override Jupyter auto-detection.
options (dict): Visualiser-specific options, e.g. colors.
manual (bool): Don't parse `Doc` and instead expect a dict/list of dicts.
RETURNS (unicode): Rendered HTML markup.
DOCS: https://spacy.io/api/top-level#displacy.render
USAGE: https://spacy.io/usage/visualizers
""" |
factories = {
"dep": (DependencyRenderer, parse_deps),
"ent": (EntityRenderer, parse_ents),
}
if style not in factories:
raise ValueError(Errors.E087.format(style=style))
if isinstance(docs, (Doc, Span, dict)):
docs = [docs]
docs = [obj if not isinstance(obj, Span) else obj.as_doc() for obj in docs]
if not all(isinstance(obj, (Doc, Span, dict)) for obj in docs):
raise ValueError(Errors.E096)
renderer, converter = factories[style]
renderer = renderer(options=options)
parsed = [converter(doc, options) for doc in docs] if not manual else docs
_html["parsed"] = renderer.render(parsed, page=page, minify=minify).strip()
html = _html["parsed"]
if RENDER_WRAPPER is not None:
html = RENDER_WRAPPER(html)
if jupyter or (jupyter is None and is_in_jupyter()):
# return HTML rendered by IPython display()
from IPython.core.display import display, HTML
return display(HTML(html))
return html |
<SYSTEM_TASK:>
Serve displaCy visualisation.
<END_TASK>
<USER_TASK:>
Description:
def serve(
docs,
style="dep",
page=True,
minify=False,
options={},
manual=False,
port=5000,
host="0.0.0.0",
):
"""Serve displaCy visualisation.
docs (list or Doc): Document(s) to visualise.
style (unicode): Visualisation style, 'dep' or 'ent'.
page (bool): Render markup as full HTML page.
minify (bool): Minify HTML markup.
options (dict): Visualiser-specific options, e.g. colors.
manual (bool): Don't parse `Doc` and instead expect a dict/list of dicts.
port (int): Port to serve visualisation.
host (unicode): Host to serve visualisation.
DOCS: https://spacy.io/api/top-level#displacy.serve
USAGE: https://spacy.io/usage/visualizers
""" |
from wsgiref import simple_server
if is_in_jupyter():
user_warning(Warnings.W011)
render(docs, style=style, page=page, minify=minify, options=options, manual=manual)
httpd = simple_server.make_server(host, port, app)
print("\nUsing the '{}' visualizer".format(style))
print("Serving on http://{}:{} ...\n".format(host, port))
try:
httpd.serve_forever()
except KeyboardInterrupt:
print("Shutting down server on port {}.".format(port))
finally:
httpd.server_close() |
<SYSTEM_TASK:>
Set an optional wrapper function that is called around the generated
<END_TASK>
<USER_TASK:>
Description:
def set_render_wrapper(func):
"""Set an optional wrapper function that is called around the generated
HTML markup on displacy.render. This can be used to allow integration into
other platforms, similar to Jupyter Notebooks that require functions to be
called around the HTML. It can also be used to implement custom callbacks
on render, or to embed the visualization in a custom page.
func (callable): Function to call around markup before rendering it. Needs
to take one argument, the HTML markup, and should return the desired
output of displacy.render.
""" |
global RENDER_WRAPPER
if not hasattr(func, "__call__"):
raise ValueError(Errors.E110.format(obj=type(func)))
RENDER_WRAPPER = func |
<SYSTEM_TASK:>
Evaluate a model. To render a sample of parses in a HTML file, set an
<END_TASK>
<USER_TASK:>
Description:
def evaluate(
model,
data_path,
gpu_id=-1,
gold_preproc=False,
displacy_path=None,
displacy_limit=25,
return_scores=False,
):
"""
Evaluate a model. To render a sample of parses in a HTML file, set an
output directory as the displacy_path argument.
""" |
msg = Printer()
util.fix_random_seed()
if gpu_id >= 0:
util.use_gpu(gpu_id)
util.set_env_log(False)
data_path = util.ensure_path(data_path)
displacy_path = util.ensure_path(displacy_path)
if not data_path.exists():
msg.fail("Evaluation data not found", data_path, exits=1)
if displacy_path and not displacy_path.exists():
msg.fail("Visualization output directory not found", displacy_path, exits=1)
corpus = GoldCorpus(data_path, data_path)
nlp = util.load_model(model)
dev_docs = list(corpus.dev_docs(nlp, gold_preproc=gold_preproc))
begin = timer()
scorer = nlp.evaluate(dev_docs, verbose=False)
end = timer()
nwords = sum(len(doc_gold[0]) for doc_gold in dev_docs)
results = {
"Time": "%.2f s" % (end - begin),
"Words": nwords,
"Words/s": "%.0f" % (nwords / (end - begin)),
"TOK": "%.2f" % scorer.token_acc,
"POS": "%.2f" % scorer.tags_acc,
"UAS": "%.2f" % scorer.uas,
"LAS": "%.2f" % scorer.las,
"NER P": "%.2f" % scorer.ents_p,
"NER R": "%.2f" % scorer.ents_r,
"NER F": "%.2f" % scorer.ents_f,
}
msg.table(results, title="Results")
if displacy_path:
docs, golds = zip(*dev_docs)
render_deps = "parser" in nlp.meta.get("pipeline", [])
render_ents = "ner" in nlp.meta.get("pipeline", [])
render_parses(
docs,
displacy_path,
model_name=model,
limit=displacy_limit,
deps=render_deps,
ents=render_ents,
)
msg.good("Generated {} parses as HTML".format(displacy_limit), displacy_path)
if return_scores:
return scorer.scores |
<SYSTEM_TASK:>
Profile a spaCy pipeline, to find out which functions take the most time.
<END_TASK>
<USER_TASK:>
Description:
def profile(model, inputs=None, n_texts=10000):
"""
Profile a spaCy pipeline, to find out which functions take the most time.
Input should be formatted as one JSON object per line with a key "text".
It can either be provided as a JSONL file, or be read from sys.sytdin.
If no input file is specified, the IMDB dataset is loaded via Thinc.
""" |
msg = Printer()
if inputs is not None:
inputs = _read_inputs(inputs, msg)
if inputs is None:
n_inputs = 25000
with msg.loading("Loading IMDB dataset via Thinc..."):
imdb_train, _ = thinc.extra.datasets.imdb()
inputs, _ = zip(*imdb_train)
msg.info("Loaded IMDB dataset and using {} examples".format(n_inputs))
inputs = inputs[:n_inputs]
with msg.loading("Loading model '{}'...".format(model)):
nlp = load_model(model)
msg.good("Loaded model '{}'".format(model))
texts = list(itertools.islice(inputs, n_texts))
cProfile.runctx("parse_texts(nlp, texts)", globals(), locals(), "Profile.prof")
s = pstats.Stats("Profile.prof")
msg.divider("Profile stats")
s.strip_dirs().sort_stats("time").print_stats() |
<SYSTEM_TASK:>
Format Mecab output into a nice data structure, based on Janome.
<END_TASK>
<USER_TASK:>
Description:
def detailed_tokens(tokenizer, text):
"""Format Mecab output into a nice data structure, based on Janome.""" |
node = tokenizer.parseToNode(text)
node = node.next # first node is beginning of sentence and empty, skip it
words = []
while node.posid != 0:
surface = node.surface
base = surface # a default value. Updated if available later.
parts = node.feature.split(",")
pos = ",".join(parts[0:4])
if len(parts) > 7:
# this information is only available for words in the tokenizer
# dictionary
base = parts[7]
words.append(ShortUnitWord(surface, base, pos))
node = node.next
return words |
<SYSTEM_TASK:>
Check if a specific configuration of Python version and operating system
<END_TASK>
<USER_TASK:>
Description:
def is_config(python2=None, python3=None, windows=None, linux=None, osx=None):
"""Check if a specific configuration of Python version and operating system
matches the user's setup. Mostly used to display targeted error messages.
python2 (bool): spaCy is executed with Python 2.x.
python3 (bool): spaCy is executed with Python 3.x.
windows (bool): spaCy is executed on Windows.
linux (bool): spaCy is executed on Linux.
osx (bool): spaCy is executed on OS X or macOS.
RETURNS (bool): Whether the configuration matches the user's platform.
DOCS: https://spacy.io/api/top-level#compat.is_config
""" |
return (
python2 in (None, is_python2)
and python3 in (None, is_python3)
and windows in (None, is_windows)
and linux in (None, is_linux)
and osx in (None, is_osx)
) |
<SYSTEM_TASK:>
Import module from a file. Used to load models from a directory.
<END_TASK>
<USER_TASK:>
Description:
def import_file(name, loc):
"""Import module from a file. Used to load models from a directory.
name (unicode): Name of module to load.
loc (unicode / Path): Path to the file.
RETURNS: The loaded module.
""" |
loc = path2str(loc)
if is_python_pre_3_5:
import imp
return imp.load_source(name, loc)
else:
import importlib.util
spec = importlib.util.spec_from_file_location(name, str(loc))
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module |
<SYSTEM_TASK:>
Import and load a Language class.
<END_TASK>
<USER_TASK:>
Description:
def get_lang_class(lang):
"""Import and load a Language class.
lang (unicode): Two-letter language code, e.g. 'en'.
RETURNS (Language): Language class.
""" |
global LANGUAGES
# Check if an entry point is exposed for the language code
entry_point = get_entry_point("spacy_languages", lang)
if entry_point is not None:
LANGUAGES[lang] = entry_point
return entry_point
if lang not in LANGUAGES:
try:
module = importlib.import_module(".lang.%s" % lang, "spacy")
except ImportError as err:
raise ImportError(Errors.E048.format(lang=lang, err=err))
LANGUAGES[lang] = getattr(module, module.__all__[0])
return LANGUAGES[lang] |
<SYSTEM_TASK:>
Load a model from a shortcut link, package or data path.
<END_TASK>
<USER_TASK:>
Description:
def load_model(name, **overrides):
"""Load a model from a shortcut link, package or data path.
name (unicode): Package name, shortcut link or model path.
**overrides: Specific overrides, like pipeline components to disable.
RETURNS (Language): `Language` class with the loaded model.
""" |
data_path = get_data_path()
if not data_path or not data_path.exists():
raise IOError(Errors.E049.format(path=path2str(data_path)))
if isinstance(name, basestring_): # in data dir / shortcut
if name in set([d.name for d in data_path.iterdir()]):
return load_model_from_link(name, **overrides)
if is_package(name): # installed as package
return load_model_from_package(name, **overrides)
if Path(name).exists(): # path to model data directory
return load_model_from_path(Path(name), **overrides)
elif hasattr(name, "exists"): # Path or Path-like to model data
return load_model_from_path(name, **overrides)
raise IOError(Errors.E050.format(name=name)) |
<SYSTEM_TASK:>
Load a model from a shortcut link, or directory in spaCy data path.
<END_TASK>
<USER_TASK:>
Description:
def load_model_from_link(name, **overrides):
"""Load a model from a shortcut link, or directory in spaCy data path.""" |
path = get_data_path() / name / "__init__.py"
try:
cls = import_file(name, path)
except AttributeError:
raise IOError(Errors.E051.format(name=name))
return cls.load(**overrides) |
<SYSTEM_TASK:>
Load a model from an installed package.
<END_TASK>
<USER_TASK:>
Description:
def load_model_from_package(name, **overrides):
"""Load a model from an installed package.""" |
cls = importlib.import_module(name)
return cls.load(**overrides) |
<SYSTEM_TASK:>
Get model meta.json from a directory path and validate its contents.
<END_TASK>
<USER_TASK:>
Description:
def get_model_meta(path):
"""Get model meta.json from a directory path and validate its contents.
path (unicode or Path): Path to model directory.
RETURNS (dict): The model's meta data.
""" |
model_path = ensure_path(path)
if not model_path.exists():
raise IOError(Errors.E052.format(path=path2str(model_path)))
meta_path = model_path / "meta.json"
if not meta_path.is_file():
raise IOError(Errors.E053.format(path=meta_path))
meta = srsly.read_json(meta_path)
for setting in ["lang", "name", "version"]:
if setting not in meta or not meta[setting]:
raise ValueError(Errors.E054.format(setting=setting))
return meta |
<SYSTEM_TASK:>
Get the path to an installed package.
<END_TASK>
<USER_TASK:>
Description:
def get_package_path(name):
"""Get the path to an installed package.
name (unicode): Package name.
RETURNS (Path): Path to installed package.
""" |
name = name.lower() # use lowercase version to be safe
# Here we're importing the module just to find it. This is worryingly
# indirect, but it's otherwise very difficult to find the package.
pkg = importlib.import_module(name)
return Path(pkg.__file__).parent |
<SYSTEM_TASK:>
Check if registered entry point is available for a given name and
<END_TASK>
<USER_TASK:>
Description:
def get_entry_point(key, value):
"""Check if registered entry point is available for a given name and
load it. Otherwise, return None.
key (unicode): Entry point name.
value (unicode): Name of entry point to load.
RETURNS: The loaded entry point or None.
""" |
for entry_point in pkg_resources.iter_entry_points(key):
if entry_point.name == value:
return entry_point.load() |
<SYSTEM_TASK:>
Compile a sequence of suffix rules into a regex object.
<END_TASK>
<USER_TASK:>
Description:
def compile_suffix_regex(entries):
"""Compile a sequence of suffix rules into a regex object.
entries (tuple): The suffix rules, e.g. spacy.lang.punctuation.TOKENIZER_SUFFIXES.
RETURNS (regex object): The regex object. to be used for Tokenizer.suffix_search.
""" |
expression = "|".join([piece + "$" for piece in entries if piece.strip()])
return re.compile(expression) |
<SYSTEM_TASK:>
Compile a sequence of infix rules into a regex object.
<END_TASK>
<USER_TASK:>
Description:
def compile_infix_regex(entries):
"""Compile a sequence of infix rules into a regex object.
entries (tuple): The infix rules, e.g. spacy.lang.punctuation.TOKENIZER_INFIXES.
RETURNS (regex object): The regex object. to be used for Tokenizer.infix_finditer.
""" |
expression = "|".join([piece for piece in entries if piece.strip()])
return re.compile(expression) |
<SYSTEM_TASK:>
Find string in tokenizer exceptions, duplicate entry and replace string.
<END_TASK>
<USER_TASK:>
Description:
def expand_exc(excs, search, replace):
"""Find string in tokenizer exceptions, duplicate entry and replace string.
For example, to add additional versions with typographic apostrophes.
excs (dict): Tokenizer exceptions.
search (unicode): String to find and replace.
replace (unicode): Replacement.
RETURNS (dict): Combined tokenizer exceptions.
""" |
def _fix_token(token, search, replace):
fixed = dict(token)
fixed[ORTH] = fixed[ORTH].replace(search, replace)
return fixed
new_excs = dict(excs)
for token_string, tokens in excs.items():
if search in token_string:
new_key = token_string.replace(search, replace)
new_value = [_fix_token(t, search, replace) for t in tokens]
new_excs[new_key] = new_value
return new_excs |
<SYSTEM_TASK:>
Iterate over batches of items. `size` may be an iterator,
<END_TASK>
<USER_TASK:>
Description:
def minibatch(items, size=8):
"""Iterate over batches of items. `size` may be an iterator,
so that batch-size can vary on each step.
""" |
if isinstance(size, int):
size_ = itertools.repeat(size)
else:
size_ = size
items = iter(items)
while True:
batch_size = next(size_)
batch = list(itertools.islice(items, int(batch_size)))
if len(batch) == 0:
break
yield list(batch) |
<SYSTEM_TASK:>
Create minibatches of a given number of words.
<END_TASK>
<USER_TASK:>
Description:
def minibatch_by_words(items, size, tuples=True, count_words=len):
"""Create minibatches of a given number of words.""" |
if isinstance(size, int):
size_ = itertools.repeat(size)
else:
size_ = size
items = iter(items)
while True:
batch_size = next(size_)
batch = []
while batch_size >= 0:
try:
if tuples:
doc, gold = next(items)
else:
doc = next(items)
except StopIteration:
if batch:
yield batch
return
batch_size -= count_words(doc)
if tuples:
batch.append((doc, gold))
else:
batch.append(doc)
if batch:
yield batch |
<SYSTEM_TASK:>
All labels present in the match patterns.
<END_TASK>
<USER_TASK:>
Description:
def labels(self):
"""All labels present in the match patterns.
RETURNS (set): The string labels.
DOCS: https://spacy.io/api/entityruler#labels
""" |
all_labels = set(self.token_patterns.keys())
all_labels.update(self.phrase_patterns.keys())
return tuple(all_labels) |
<SYSTEM_TASK:>
Get all patterns that were added to the entity ruler.
<END_TASK>
<USER_TASK:>
Description:
def patterns(self):
"""Get all patterns that were added to the entity ruler.
RETURNS (list): The original patterns, one dictionary per pattern.
DOCS: https://spacy.io/api/entityruler#patterns
""" |
all_patterns = []
for label, patterns in self.token_patterns.items():
for pattern in patterns:
all_patterns.append({"label": label, "pattern": pattern})
for label, patterns in self.phrase_patterns.items():
for pattern in patterns:
all_patterns.append({"label": label, "pattern": pattern.text})
return all_patterns |
<SYSTEM_TASK:>
Load the entity ruler from a bytestring.
<END_TASK>
<USER_TASK:>
Description:
def from_bytes(self, patterns_bytes, **kwargs):
"""Load the entity ruler from a bytestring.
patterns_bytes (bytes): The bytestring to load.
**kwargs: Other config paramters, mostly for consistency.
RETURNS (EntityRuler): The loaded entity ruler.
DOCS: https://spacy.io/api/entityruler#from_bytes
""" |
patterns = srsly.msgpack_loads(patterns_bytes)
self.add_patterns(patterns)
return self |
<SYSTEM_TASK:>
Get out the annoying 'tuples' format used by begin_training, given the
<END_TASK>
<USER_TASK:>
Description:
def golds_to_gold_tuples(docs, golds):
"""Get out the annoying 'tuples' format used by begin_training, given the
GoldParse objects.""" |
tuples = []
for doc, gold in zip(docs, golds):
text = doc.text
ids, words, tags, heads, labels, iob = zip(*gold.orig_annot)
sents = [((ids, words, tags, heads, labels, iob), [])]
tuples.append((text, sents))
return tuples |
<SYSTEM_TASK:>
Concatenate multiple serialized binders into one byte string.
<END_TASK>
<USER_TASK:>
Description:
def merge_bytes(binder_strings):
"""Concatenate multiple serialized binders into one byte string.""" |
output = None
for byte_string in binder_strings:
binder = Binder().from_bytes(byte_string)
if output is None:
output = binder
else:
output.merge(binder)
return output.to_bytes() |
<SYSTEM_TASK:>
Add a doc's annotations to the binder for serialization.
<END_TASK>
<USER_TASK:>
Description:
def add(self, doc):
"""Add a doc's annotations to the binder for serialization.""" |
array = doc.to_array(self.attrs)
if len(array.shape) == 1:
array = array.reshape((array.shape[0], 1))
self.tokens.append(array)
spaces = doc.to_array(SPACY)
assert array.shape[0] == spaces.shape[0]
spaces = spaces.reshape((spaces.shape[0], 1))
self.spaces.append(numpy.asarray(spaces, dtype=bool))
self.strings.update(w.text for w in doc) |
<SYSTEM_TASK:>
Recover Doc objects from the annotations, using the given vocab.
<END_TASK>
<USER_TASK:>
Description:
def get_docs(self, vocab):
"""Recover Doc objects from the annotations, using the given vocab.""" |
for string in self.strings:
vocab[string]
orth_col = self.attrs.index(ORTH)
for tokens, spaces in zip(self.tokens, self.spaces):
words = [vocab.strings[orth] for orth in tokens[:, orth_col]]
doc = Doc(vocab, words=words, spaces=spaces)
doc = doc.from_array(self.attrs, tokens)
yield doc |
<SYSTEM_TASK:>
Extend the annotations of this binder with the annotations from another.
<END_TASK>
<USER_TASK:>
Description:
def merge(self, other):
"""Extend the annotations of this binder with the annotations from another.""" |
assert self.attrs == other.attrs
self.tokens.extend(other.tokens)
self.spaces.extend(other.spaces)
self.strings.update(other.strings) |
<SYSTEM_TASK:>
Serialize the binder's annotations into a byte string.
<END_TASK>
<USER_TASK:>
Description:
def to_bytes(self):
"""Serialize the binder's annotations into a byte string.""" |
for tokens in self.tokens:
assert len(tokens.shape) == 2, tokens.shape
lengths = [len(tokens) for tokens in self.tokens]
msg = {
"attrs": self.attrs,
"tokens": numpy.vstack(self.tokens).tobytes("C"),
"spaces": numpy.vstack(self.spaces).tobytes("C"),
"lengths": numpy.asarray(lengths, dtype="int32").tobytes("C"),
"strings": list(self.strings),
}
return gzip.compress(srsly.msgpack_dumps(msg)) |
<SYSTEM_TASK:>
Deserialize the binder's annotations from a byte string.
<END_TASK>
<USER_TASK:>
Description:
def from_bytes(self, string):
"""Deserialize the binder's annotations from a byte string.""" |
msg = srsly.msgpack_loads(gzip.decompress(string))
self.attrs = msg["attrs"]
self.strings = set(msg["strings"])
lengths = numpy.fromstring(msg["lengths"], dtype="int32")
flat_spaces = numpy.fromstring(msg["spaces"], dtype=bool)
flat_tokens = numpy.fromstring(msg["tokens"], dtype="uint64")
shape = (flat_tokens.size // len(self.attrs), len(self.attrs))
flat_tokens = flat_tokens.reshape(shape)
flat_spaces = flat_spaces.reshape((flat_spaces.size, 1))
self.tokens = NumpyOps().unflatten(flat_tokens, lengths)
self.spaces = NumpyOps().unflatten(flat_spaces, lengths)
for tokens in self.tokens:
assert len(tokens.shape) == 2, tokens.shape
return self |
<SYSTEM_TASK:>
Check whether we're dealing with an uninflected paradigm, so we can
<END_TASK>
<USER_TASK:>
Description:
def is_base_form(self, univ_pos, morphology=None):
"""
Check whether we're dealing with an uninflected paradigm, so we can
avoid lemmatization entirely.
""" |
morphology = {} if morphology is None else morphology
others = [key for key in morphology
if key not in (POS, 'Number', 'POS', 'VerbForm', 'Tense')]
if univ_pos == 'noun' and morphology.get('Number') == 'sing':
return True
elif univ_pos == 'verb' and morphology.get('VerbForm') == 'inf':
return True
# This maps 'VBP' to base form -- probably just need 'IS_BASE'
# morphology
elif univ_pos == 'verb' and (morphology.get('VerbForm') == 'fin' and
morphology.get('Tense') == 'pres' and
morphology.get('Number') is None and
not others):
return True
elif univ_pos == 'adj' and morphology.get('Degree') == 'pos':
return True
elif VerbForm_inf in morphology:
return True
elif VerbForm_none in morphology:
return True
elif Number_sing in morphology:
return True
elif Degree_pos in morphology:
return True
else:
return False |
<SYSTEM_TASK:>
Set up the pipeline and entity recognizer, and train the new entity.
<END_TASK>
<USER_TASK:>
Description:
def main(model=None, new_model_name="animal", output_dir=None, n_iter=30):
"""Set up the pipeline and entity recognizer, and train the new entity.""" |
random.seed(0)
if model is not None:
nlp = spacy.load(model) # load existing spaCy model
print("Loaded model '%s'" % model)
else:
nlp = spacy.blank("en") # create blank Language class
print("Created blank 'en' model")
# Add entity recognizer to model if it's not in the pipeline
# nlp.create_pipe works for built-ins that are registered with spaCy
if "ner" not in nlp.pipe_names:
ner = nlp.create_pipe("ner")
nlp.add_pipe(ner)
# otherwise, get it, so we can add labels to it
else:
ner = nlp.get_pipe("ner")
ner.add_label(LABEL) # add new entity label to entity recognizer
# Adding extraneous labels shouldn't mess anything up
ner.add_label("VEGETABLE")
if model is None:
optimizer = nlp.begin_training()
else:
optimizer = nlp.resume_training()
move_names = list(ner.move_names)
# get names of other pipes to disable them during training
other_pipes = [pipe for pipe in nlp.pipe_names if pipe != "ner"]
with nlp.disable_pipes(*other_pipes): # only train NER
sizes = compounding(1.0, 4.0, 1.001)
# batch up the examples using spaCy's minibatch
for itn in range(n_iter):
random.shuffle(TRAIN_DATA)
batches = minibatch(TRAIN_DATA, size=sizes)
losses = {}
for batch in batches:
texts, annotations = zip(*batch)
nlp.update(texts, annotations, sgd=optimizer, drop=0.35, losses=losses)
print("Losses", losses)
# test the trained model
test_text = "Do you like horses?"
doc = nlp(test_text)
print("Entities in '%s'" % test_text)
for ent in doc.ents:
print(ent.label_, ent.text)
# save model to output directory
if output_dir is not None:
output_dir = Path(output_dir)
if not output_dir.exists():
output_dir.mkdir()
nlp.meta["name"] = new_model_name # rename model
nlp.to_disk(output_dir)
print("Saved model to", output_dir)
# test the saved model
print("Loading from", output_dir)
nlp2 = spacy.load(output_dir)
# Check the classes have loaded back consistently
assert nlp2.get_pipe("ner").move_names == move_names
doc2 = nlp2(test_text)
for ent in doc2.ents:
print(ent.label_, ent.text) |
<SYSTEM_TASK:>
Convert files in the CoNLL-2003 NER format into JSON format for use with
<END_TASK>
<USER_TASK:>
Description:
def conll_ner2json(input_data, **kwargs):
"""
Convert files in the CoNLL-2003 NER format into JSON format for use with
train cli.
""" |
delimit_docs = "-DOCSTART- -X- O O"
output_docs = []
for doc in input_data.strip().split(delimit_docs):
doc = doc.strip()
if not doc:
continue
output_doc = []
for sent in doc.split("\n\n"):
sent = sent.strip()
if not sent:
continue
lines = [line.strip() for line in sent.split("\n") if line.strip()]
words, tags, chunks, iob_ents = zip(*[line.split() for line in lines])
biluo_ents = iob_to_biluo(iob_ents)
output_doc.append(
{
"tokens": [
{"orth": w, "tag": tag, "ner": ent}
for (w, tag, ent) in zip(words, tags, biluo_ents)
]
}
)
output_docs.append(
{"id": len(output_docs), "paragraphs": [{"sentences": output_doc}]}
)
output_doc = []
return output_docs |
<SYSTEM_TASK:>
Create a new model, set up the pipeline and train the tagger. In order to
<END_TASK>
<USER_TASK:>
Description:
def main(lang="en", output_dir=None, n_iter=25):
"""Create a new model, set up the pipeline and train the tagger. In order to
train the tagger with a custom tag map, we're creating a new Language
instance with a custom vocab.
""" |
nlp = spacy.blank(lang)
# add the tagger to the pipeline
# nlp.create_pipe works for built-ins that are registered with spaCy
tagger = nlp.create_pipe("tagger")
# Add the tags. This needs to be done before you start training.
for tag, values in TAG_MAP.items():
tagger.add_label(tag, values)
nlp.add_pipe(tagger)
optimizer = nlp.begin_training()
for i in range(n_iter):
random.shuffle(TRAIN_DATA)
losses = {}
# batch up the examples using spaCy's minibatch
batches = minibatch(TRAIN_DATA, size=compounding(4.0, 32.0, 1.001))
for batch in batches:
texts, annotations = zip(*batch)
nlp.update(texts, annotations, sgd=optimizer, losses=losses)
print("Losses", losses)
# test the trained model
test_text = "I like blue eggs"
doc = nlp(test_text)
print("Tags", [(t.text, t.tag_, t.pos_) for t in doc])
# save model to output directory
if output_dir is not None:
output_dir = Path(output_dir)
if not output_dir.exists():
output_dir.mkdir()
nlp.to_disk(output_dir)
print("Saved model to", output_dir)
# test the save model
print("Loading from", output_dir)
nlp2 = spacy.load(output_dir)
doc = nlp2(test_text)
print("Tags", [(t.text, t.tag_, t.pos_) for t in doc]) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.