code
stringlengths 26
870k
| docstring
stringlengths 1
65.6k
| func_name
stringlengths 1
194
| language
stringclasses 1
value | repo
stringlengths 8
68
| path
stringlengths 5
194
| url
stringlengths 46
254
| license
stringclasses 4
values |
---|---|---|---|---|---|---|---|
def set_debug(self, debug):
"""Set the debug mode (off by default).
Set to True to enable debug mode. When active, some actions
will launch a browser on the current page on failure to let
you inspect the page content.
"""
self.__debug = debug | Set the debug mode (off by default).
Set to True to enable debug mode. When active, some actions
will launch a browser on the current page on failure to let
you inspect the page content. | set_debug | python | MechanicalSoup/MechanicalSoup | mechanicalsoup/stateful_browser.py | https://github.com/MechanicalSoup/MechanicalSoup/blob/master/mechanicalsoup/stateful_browser.py | MIT |
def get_debug(self):
"""Get the debug mode (off by default)."""
return self.__debug | Get the debug mode (off by default). | get_debug | python | MechanicalSoup/MechanicalSoup | mechanicalsoup/stateful_browser.py | https://github.com/MechanicalSoup/MechanicalSoup/blob/master/mechanicalsoup/stateful_browser.py | MIT |
def set_verbose(self, verbose):
"""Set the verbosity level (an integer).
* 0 means no verbose output.
* 1 shows one dot per visited page (looks like a progress bar)
* >= 2 shows each visited URL.
"""
self.__verbose = verbose | Set the verbosity level (an integer).
* 0 means no verbose output.
* 1 shows one dot per visited page (looks like a progress bar)
* >= 2 shows each visited URL. | set_verbose | python | MechanicalSoup/MechanicalSoup | mechanicalsoup/stateful_browser.py | https://github.com/MechanicalSoup/MechanicalSoup/blob/master/mechanicalsoup/stateful_browser.py | MIT |
def get_verbose(self):
"""Get the verbosity level. See :func:`set_verbose()`."""
return self.__verbose | Get the verbosity level. See :func:`set_verbose()`. | get_verbose | python | MechanicalSoup/MechanicalSoup | mechanicalsoup/stateful_browser.py | https://github.com/MechanicalSoup/MechanicalSoup/blob/master/mechanicalsoup/stateful_browser.py | MIT |
def page(self):
"""Get the current page as a soup object."""
return self.__state.page | Get the current page as a soup object. | page | python | MechanicalSoup/MechanicalSoup | mechanicalsoup/stateful_browser.py | https://github.com/MechanicalSoup/MechanicalSoup/blob/master/mechanicalsoup/stateful_browser.py | MIT |
def url(self):
"""Get the URL of the currently visited page."""
return self.__state.url | Get the URL of the currently visited page. | url | python | MechanicalSoup/MechanicalSoup | mechanicalsoup/stateful_browser.py | https://github.com/MechanicalSoup/MechanicalSoup/blob/master/mechanicalsoup/stateful_browser.py | MIT |
def form(self):
"""Get the currently selected form as a :class:`Form` object.
See :func:`select_form`.
"""
if self.__state.form is None:
raise AttributeError("No form has been selected yet on this page.")
return self.__state.form | Get the currently selected form as a :class:`Form` object.
See :func:`select_form`. | form | python | MechanicalSoup/MechanicalSoup | mechanicalsoup/stateful_browser.py | https://github.com/MechanicalSoup/MechanicalSoup/blob/master/mechanicalsoup/stateful_browser.py | MIT |
def __setitem__(self, name, value):
"""Call item assignment on the currently selected form.
See :func:`Form.__setitem__`.
"""
self.form[name] = value | Call item assignment on the currently selected form.
See :func:`Form.__setitem__`. | __setitem__ | python | MechanicalSoup/MechanicalSoup | mechanicalsoup/stateful_browser.py | https://github.com/MechanicalSoup/MechanicalSoup/blob/master/mechanicalsoup/stateful_browser.py | MIT |
def new_control(self, type, name, value, **kwargs):
"""Call :func:`Form.new_control` on the currently selected form."""
return self.form.new_control(type, name, value, **kwargs) | Call :func:`Form.new_control` on the currently selected form. | new_control | python | MechanicalSoup/MechanicalSoup | mechanicalsoup/stateful_browser.py | https://github.com/MechanicalSoup/MechanicalSoup/blob/master/mechanicalsoup/stateful_browser.py | MIT |
def absolute_url(self, url):
"""Return the absolute URL made from the current URL and ``url``.
The current URL is only used to provide any missing components of
``url``, as in the `.urljoin() method of urllib.parse
<https://docs.python.org/3/library/urllib.parse.html#urllib.parse.urljoin>`__.
"""
return urllib.parse.urljoin(self.url, url) | Return the absolute URL made from the current URL and ``url``.
The current URL is only used to provide any missing components of
``url``, as in the `.urljoin() method of urllib.parse
<https://docs.python.org/3/library/urllib.parse.html#urllib.parse.urljoin>`__. | absolute_url | python | MechanicalSoup/MechanicalSoup | mechanicalsoup/stateful_browser.py | https://github.com/MechanicalSoup/MechanicalSoup/blob/master/mechanicalsoup/stateful_browser.py | MIT |
def open(self, url, *args, **kwargs):
"""Open the URL and store the Browser's state in this object.
All arguments are forwarded to :func:`Browser.get`.
:return: Forwarded from :func:`Browser.get`.
"""
if self.__verbose == 1:
sys.stdout.write('.')
sys.stdout.flush()
elif self.__verbose >= 2:
print(url)
resp = self.get(url, *args, **kwargs)
self.__state = _BrowserState(page=resp.soup, url=resp.url,
request=resp.request)
return resp | Open the URL and store the Browser's state in this object.
All arguments are forwarded to :func:`Browser.get`.
:return: Forwarded from :func:`Browser.get`. | open | python | MechanicalSoup/MechanicalSoup | mechanicalsoup/stateful_browser.py | https://github.com/MechanicalSoup/MechanicalSoup/blob/master/mechanicalsoup/stateful_browser.py | MIT |
def open_fake_page(self, page_text, url=None, soup_config=None):
"""Mock version of :func:`open`.
Behave as if opening a page whose text is ``page_text``, but do not
perform any network access. If ``url`` is set, pretend it is the page's
URL. Useful mainly for testing.
"""
soup_config = soup_config or self.soup_config
self.__state = _BrowserState(
page=bs4.BeautifulSoup(page_text, **soup_config),
url=url) | Mock version of :func:`open`.
Behave as if opening a page whose text is ``page_text``, but do not
perform any network access. If ``url`` is set, pretend it is the page's
URL. Useful mainly for testing. | open_fake_page | python | MechanicalSoup/MechanicalSoup | mechanicalsoup/stateful_browser.py | https://github.com/MechanicalSoup/MechanicalSoup/blob/master/mechanicalsoup/stateful_browser.py | MIT |
def open_relative(self, url, *args, **kwargs):
"""Like :func:`open`, but ``url`` can be relative to the currently
visited page.
"""
return self.open(self.absolute_url(url), *args, **kwargs) | Like :func:`open`, but ``url`` can be relative to the currently
visited page. | open_relative | python | MechanicalSoup/MechanicalSoup | mechanicalsoup/stateful_browser.py | https://github.com/MechanicalSoup/MechanicalSoup/blob/master/mechanicalsoup/stateful_browser.py | MIT |
def refresh(self):
"""Reload the current page with the same request as originally done.
Any change (`select_form`, or any value filled-in in the form) made to
the current page before refresh is discarded.
:raise ValueError: Raised if no refreshable page is loaded, e.g., when
using the shallow ``Browser`` wrapper functions.
:return: Response of the request."""
old_request = self.__state.request
if old_request is None:
raise ValueError('The current page is not refreshable. Either no '
'page is opened or low-level browser methods '
'were used to do so')
resp = self.session.send(old_request)
Browser.add_soup(resp, self.soup_config)
self.__state = _BrowserState(page=resp.soup, url=resp.url,
request=resp.request)
return resp | Reload the current page with the same request as originally done.
Any change (`select_form`, or any value filled-in in the form) made to
the current page before refresh is discarded.
:raise ValueError: Raised if no refreshable page is loaded, e.g., when
using the shallow ``Browser`` wrapper functions.
:return: Response of the request. | refresh | python | MechanicalSoup/MechanicalSoup | mechanicalsoup/stateful_browser.py | https://github.com/MechanicalSoup/MechanicalSoup/blob/master/mechanicalsoup/stateful_browser.py | MIT |
def find_associated_elements(form_id):
"""Find all elements associated to a form
(i.e. an element with a form attribute -> ``form=form_id``)
"""
# Elements which can have a form owner
elements_with_owner_form = ("input", "button", "fieldset",
"object", "output", "select",
"textarea")
found_elements = []
for element in elements_with_owner_form:
found_elements.extend(
self.page.find_all(element, form=form_id)
)
return found_elements | Find all elements associated to a form
(i.e. an element with a form attribute -> ``form=form_id``) | select_form.find_associated_elements | python | MechanicalSoup/MechanicalSoup | mechanicalsoup/stateful_browser.py | https://github.com/MechanicalSoup/MechanicalSoup/blob/master/mechanicalsoup/stateful_browser.py | MIT |
def select_form(self, selector="form", nr=0):
"""Select a form in the current page.
:param selector: CSS selector or a bs4.element.Tag object to identify
the form to select.
If not specified, ``selector`` defaults to "form", which is
useful if, e.g., there is only one form on the page.
For ``selector`` syntax, see the `.select() method in BeautifulSoup
<https://www.crummy.com/software/BeautifulSoup/bs4/doc/#css-selectors>`__.
:param nr: A zero-based index specifying which form among those that
match ``selector`` will be selected. Useful when one or more forms
have the same attributes as the form you want to select, and its
position on the page is the only way to uniquely identify it.
Default is the first matching form (``nr=0``).
:return: The selected form as a soup object. It can also be
retrieved later with the :attr:`form` attribute.
"""
def find_associated_elements(form_id):
"""Find all elements associated to a form
(i.e. an element with a form attribute -> ``form=form_id``)
"""
# Elements which can have a form owner
elements_with_owner_form = ("input", "button", "fieldset",
"object", "output", "select",
"textarea")
found_elements = []
for element in elements_with_owner_form:
found_elements.extend(
self.page.find_all(element, form=form_id)
)
return found_elements
if isinstance(selector, bs4.element.Tag):
if selector.name != "form":
raise LinkNotFoundError
form = selector
else:
# nr is a 0-based index for consistency with mechanize
found_forms = self.page.select(selector,
limit=nr + 1)
if len(found_forms) != nr + 1:
if self.__debug:
print('select_form failed for', selector)
self.launch_browser()
raise LinkNotFoundError()
form = found_forms[-1]
if form and form.has_attr('id'):
form_id = form["id"]
new_elements = find_associated_elements(form_id)
form.extend(new_elements)
self.__state.form = Form(form)
return self.form | Select a form in the current page.
:param selector: CSS selector or a bs4.element.Tag object to identify
the form to select.
If not specified, ``selector`` defaults to "form", which is
useful if, e.g., there is only one form on the page.
For ``selector`` syntax, see the `.select() method in BeautifulSoup
<https://www.crummy.com/software/BeautifulSoup/bs4/doc/#css-selectors>`__.
:param nr: A zero-based index specifying which form among those that
match ``selector`` will be selected. Useful when one or more forms
have the same attributes as the form you want to select, and its
position on the page is the only way to uniquely identify it.
Default is the first matching form (``nr=0``).
:return: The selected form as a soup object. It can also be
retrieved later with the :attr:`form` attribute. | select_form | python | MechanicalSoup/MechanicalSoup | mechanicalsoup/stateful_browser.py | https://github.com/MechanicalSoup/MechanicalSoup/blob/master/mechanicalsoup/stateful_browser.py | MIT |
def _merge_referer(self, **kwargs):
"""Helper function to set the Referer header in kwargs passed to
requests, if it has not already been overridden by the user."""
referer = self.url
headers = CaseInsensitiveDict(kwargs.get('headers', {}))
if referer is not None and 'Referer' not in headers:
headers['Referer'] = referer
kwargs['headers'] = headers
return kwargs | Helper function to set the Referer header in kwargs passed to
requests, if it has not already been overridden by the user. | _merge_referer | python | MechanicalSoup/MechanicalSoup | mechanicalsoup/stateful_browser.py | https://github.com/MechanicalSoup/MechanicalSoup/blob/master/mechanicalsoup/stateful_browser.py | MIT |
def submit_selected(self, btnName=None, update_state=True,
**kwargs):
"""Submit the form that was selected with :func:`select_form`.
:return: Forwarded from :func:`Browser.submit`.
:param btnName: Passed to :func:`Form.choose_submit` to choose the
element of the current form to use for submission. If ``None``,
will choose the first valid submit element in the form, if one
exists. If ``False``, will not use any submit element; this is
useful for simulating AJAX requests, for example.
:param update_state: If False, the form will be submitted but the
browser state will remain unchanged; this is useful for forms that
result in a download of a file, for example.
All other arguments are forwarded to :func:`Browser.submit`.
"""
self.form.choose_submit(btnName)
kwargs = self._merge_referer(**kwargs)
resp = self.submit(self.__state.form, url=self.__state.url,
**kwargs)
if update_state:
self.__state = _BrowserState(page=resp.soup, url=resp.url,
request=resp.request)
return resp | Submit the form that was selected with :func:`select_form`.
:return: Forwarded from :func:`Browser.submit`.
:param btnName: Passed to :func:`Form.choose_submit` to choose the
element of the current form to use for submission. If ``None``,
will choose the first valid submit element in the form, if one
exists. If ``False``, will not use any submit element; this is
useful for simulating AJAX requests, for example.
:param update_state: If False, the form will be submitted but the
browser state will remain unchanged; this is useful for forms that
result in a download of a file, for example.
All other arguments are forwarded to :func:`Browser.submit`. | submit_selected | python | MechanicalSoup/MechanicalSoup | mechanicalsoup/stateful_browser.py | https://github.com/MechanicalSoup/MechanicalSoup/blob/master/mechanicalsoup/stateful_browser.py | MIT |
def list_links(self, *args, **kwargs):
"""Display the list of links in the current page. Arguments are
forwarded to :func:`links`.
"""
print("Links in the current page:")
for link in self.links(*args, **kwargs):
print(" ", link) | Display the list of links in the current page. Arguments are
forwarded to :func:`links`. | list_links | python | MechanicalSoup/MechanicalSoup | mechanicalsoup/stateful_browser.py | https://github.com/MechanicalSoup/MechanicalSoup/blob/master/mechanicalsoup/stateful_browser.py | MIT |
def links(self, url_regex=None, link_text=None, *args, **kwargs):
"""Return links in the page, as a list of bs4.element.Tag objects.
To return links matching specific criteria, specify ``url_regex``
to match the *href*-attribute, or ``link_text`` to match the
*text*-attribute of the Tag. All other arguments are forwarded to
the `.find_all() method in BeautifulSoup
<https://www.crummy.com/software/BeautifulSoup/bs4/doc/#find-all>`__.
"""
all_links = self.page.find_all(
'a', href=True, *args, **kwargs)
if url_regex is not None:
all_links = [a for a in all_links
if re.search(url_regex, a['href'])]
if link_text is not None:
all_links = [a for a in all_links
if a.text == link_text]
return all_links | Return links in the page, as a list of bs4.element.Tag objects.
To return links matching specific criteria, specify ``url_regex``
to match the *href*-attribute, or ``link_text`` to match the
*text*-attribute of the Tag. All other arguments are forwarded to
the `.find_all() method in BeautifulSoup
<https://www.crummy.com/software/BeautifulSoup/bs4/doc/#find-all>`__. | links | python | MechanicalSoup/MechanicalSoup | mechanicalsoup/stateful_browser.py | https://github.com/MechanicalSoup/MechanicalSoup/blob/master/mechanicalsoup/stateful_browser.py | MIT |
def find_link(self, *args, **kwargs):
"""Find and return a link, as a bs4.element.Tag object.
The search can be refined by specifying any argument that is accepted
by :func:`links`. If several links match, return the first one found.
If no link is found, raise :class:`LinkNotFoundError`.
"""
links = self.links(*args, **kwargs)
if len(links) == 0:
raise LinkNotFoundError()
else:
return links[0] | Find and return a link, as a bs4.element.Tag object.
The search can be refined by specifying any argument that is accepted
by :func:`links`. If several links match, return the first one found.
If no link is found, raise :class:`LinkNotFoundError`. | find_link | python | MechanicalSoup/MechanicalSoup | mechanicalsoup/stateful_browser.py | https://github.com/MechanicalSoup/MechanicalSoup/blob/master/mechanicalsoup/stateful_browser.py | MIT |
def _find_link_internal(self, link, args, kwargs):
"""Wrapper around find_link that deals with convenience special-cases:
* If ``link`` has an *href*-attribute, then return it. If not,
consider it as a ``url_regex`` argument.
* If searching for the link fails and debug is active, launch
a browser.
"""
if hasattr(link, 'attrs') and 'href' in link.attrs:
return link
# Check if "link" parameter should be treated as "url_regex"
# but reject obtaining it from both places.
if link and 'url_regex' in kwargs:
raise ValueError('link parameter cannot be treated as '
'url_regex because url_regex is already '
'present in keyword arguments')
elif link:
kwargs['url_regex'] = link
try:
return self.find_link(*args, **kwargs)
except LinkNotFoundError:
if self.get_debug():
print('find_link failed for', kwargs)
self.list_links()
self.launch_browser()
raise | Wrapper around find_link that deals with convenience special-cases:
* If ``link`` has an *href*-attribute, then return it. If not,
consider it as a ``url_regex`` argument.
* If searching for the link fails and debug is active, launch
a browser. | _find_link_internal | python | MechanicalSoup/MechanicalSoup | mechanicalsoup/stateful_browser.py | https://github.com/MechanicalSoup/MechanicalSoup/blob/master/mechanicalsoup/stateful_browser.py | MIT |
def follow_link(self, link=None, *bs4_args, bs4_kwargs={},
requests_kwargs={}, **kwargs):
"""Follow a link.
If ``link`` is a bs4.element.Tag (i.e. from a previous call to
:func:`links` or :func:`find_link`), then follow the link.
If ``link`` doesn't have a *href*-attribute or is None, treat
``link`` as a url_regex and look it up with :func:`find_link`.
``bs4_kwargs`` are forwarded to :func:`find_link`.
For backward compatibility, any excess keyword arguments
(aka ``**kwargs``)
are also forwarded to :func:`find_link`.
If the link is not found, raise :class:`LinkNotFoundError`.
Before raising, if debug is activated, list available links in the
page and launch a browser.
``requests_kwargs`` are forwarded to :func:`open_relative`.
:return: Forwarded from :func:`open_relative`.
"""
link = self._find_link_internal(link, bs4_args,
{**bs4_kwargs, **kwargs})
requests_kwargs = self._merge_referer(**requests_kwargs)
return self.open_relative(link['href'], **requests_kwargs) | Follow a link.
If ``link`` is a bs4.element.Tag (i.e. from a previous call to
:func:`links` or :func:`find_link`), then follow the link.
If ``link`` doesn't have a *href*-attribute or is None, treat
``link`` as a url_regex and look it up with :func:`find_link`.
``bs4_kwargs`` are forwarded to :func:`find_link`.
For backward compatibility, any excess keyword arguments
(aka ``**kwargs``)
are also forwarded to :func:`find_link`.
If the link is not found, raise :class:`LinkNotFoundError`.
Before raising, if debug is activated, list available links in the
page and launch a browser.
``requests_kwargs`` are forwarded to :func:`open_relative`.
:return: Forwarded from :func:`open_relative`. | follow_link | python | MechanicalSoup/MechanicalSoup | mechanicalsoup/stateful_browser.py | https://github.com/MechanicalSoup/MechanicalSoup/blob/master/mechanicalsoup/stateful_browser.py | MIT |
def download_link(self, link=None, file=None, *bs4_args, bs4_kwargs={},
requests_kwargs={}, **kwargs):
"""Downloads the contents of a link to a file. This function behaves
similarly to :func:`follow_link`, but the browser state will
not change when calling this function.
:param file: Filesystem path where the page contents will be
downloaded. If the file already exists, it will be overwritten.
Other arguments are the same as :func:`follow_link` (``link``
can either be a bs4.element.Tag or a URL regex.
``bs4_kwargs`` arguments are forwarded to :func:`find_link`,
as are any excess keyword arguments (aka ``**kwargs``) for backwards
compatibility).
:return: `requests.Response
<http://docs.python-requests.org/en/master/api/#requests.Response>`__
object.
"""
link = self._find_link_internal(link, bs4_args,
{**bs4_kwargs, **kwargs})
url = self.absolute_url(link['href'])
requests_kwargs = self._merge_referer(**requests_kwargs)
response = self.session.get(url, **requests_kwargs)
if self.raise_on_404 and response.status_code == 404:
raise LinkNotFoundError()
# Save the response content to file
if file is not None:
with open(file, 'wb') as f:
f.write(response.content)
return response | Downloads the contents of a link to a file. This function behaves
similarly to :func:`follow_link`, but the browser state will
not change when calling this function.
:param file: Filesystem path where the page contents will be
downloaded. If the file already exists, it will be overwritten.
Other arguments are the same as :func:`follow_link` (``link``
can either be a bs4.element.Tag or a URL regex.
``bs4_kwargs`` arguments are forwarded to :func:`find_link`,
as are any excess keyword arguments (aka ``**kwargs``) for backwards
compatibility).
:return: `requests.Response
<http://docs.python-requests.org/en/master/api/#requests.Response>`__
object. | download_link | python | MechanicalSoup/MechanicalSoup | mechanicalsoup/stateful_browser.py | https://github.com/MechanicalSoup/MechanicalSoup/blob/master/mechanicalsoup/stateful_browser.py | MIT |
def launch_browser(self, soup=None):
"""Launch a browser to display a page, for debugging purposes.
:param: soup: Page contents to display, supplied as a bs4 soup object.
Defaults to the current page of the ``StatefulBrowser`` instance.
"""
if soup is None:
soup = self.page
super().launch_browser(soup) | Launch a browser to display a page, for debugging purposes.
:param: soup: Page contents to display, supplied as a bs4 soup object.
Defaults to the current page of the ``StatefulBrowser`` instance. | launch_browser | python | MechanicalSoup/MechanicalSoup | mechanicalsoup/stateful_browser.py | https://github.com/MechanicalSoup/MechanicalSoup/blob/master/mechanicalsoup/stateful_browser.py | MIT |
def open_legacy_httpbin(browser, httpbin):
"""Opens the start page of httpbin (given as a fixture). Tries the
legacy page (available only on recent versions of httpbin), and if
it fails fall back to the main page (which is JavaScript-only in
recent versions of httpbin hence usable for us only on old
versions).
"""
try:
response = browser.open(httpbin + "/legacy")
if response.status_code == 404:
# The line above may or may not have raised the exception
# depending on raise_on_404. Raise it unconditionally now.
raise mechanicalsoup.LinkNotFoundError()
return response
except mechanicalsoup.LinkNotFoundError:
return browser.open(httpbin.url) | Opens the start page of httpbin (given as a fixture). Tries the
legacy page (available only on recent versions of httpbin), and if
it fails fall back to the main page (which is JavaScript-only in
recent versions of httpbin hence usable for us only on old
versions). | open_legacy_httpbin | python | MechanicalSoup/MechanicalSoup | tests/utils.py | https://github.com/MechanicalSoup/MechanicalSoup/blob/master/tests/utils.py | MIT |
def test_submit_online(httpbin):
"""Complete and submit the pizza form at http://httpbin.org/forms/post """
browser = mechanicalsoup.Browser()
page = browser.get(httpbin + "/forms/post")
form = page.soup.form
form.find("input", {"name": "custname"})["value"] = "Philip J. Fry"
# leave custtel blank without value
assert "value" not in form.find("input", {"name": "custtel"}).attrs
form.find("input", {"name": "size", "value": "medium"})["checked"] = ""
form.find("input", {"name": "topping", "value": "cheese"})["checked"] = ""
form.find("input", {"name": "topping", "value": "onion"})["checked"] = ""
form.find("textarea", {"name": "comments"}).insert(0, "freezer")
response = browser.submit(form, page.url)
# helpfully the form submits to http://httpbin.org/post which simply
# returns the request headers in json format
json = response.json()
data = json["form"]
assert data["custname"] == "Philip J. Fry"
assert data["custtel"] == "" # web browser submits "" for input left blank
assert data["size"] == "medium"
assert data["topping"] == ["cheese", "onion"]
assert data["comments"] == "freezer"
assert json["headers"]["User-Agent"].startswith('python-requests/')
assert 'MechanicalSoup' in json["headers"]["User-Agent"] | Complete and submit the pizza form at http://httpbin.org/forms/post | test_submit_online | python | MechanicalSoup/MechanicalSoup | tests/test_browser.py | https://github.com/MechanicalSoup/MechanicalSoup/blob/master/tests/test_browser.py | MIT |
def test_get_request_kwargs(httpbin):
"""Return kwargs without a submit"""
browser = mechanicalsoup.Browser()
page = browser.get(httpbin + "/forms/post")
form = page.soup.form
form.find("input", {"name": "custname"})["value"] = "Philip J. Fry"
request_kwargs = browser.get_request_kwargs(form, page.url)
assert "method" in request_kwargs
assert "url" in request_kwargs
assert "data" in request_kwargs
assert ("custname", "Philip J. Fry") in request_kwargs["data"] | Return kwargs without a submit | test_get_request_kwargs | python | MechanicalSoup/MechanicalSoup | tests/test_browser.py | https://github.com/MechanicalSoup/MechanicalSoup/blob/master/tests/test_browser.py | MIT |
def test_get_request_kwargs_when_method_is_in_kwargs(httpbin):
"""Raise TypeError exception"""
browser = mechanicalsoup.Browser()
page = browser.get(httpbin + "/forms/post")
form = page.soup.form
kwargs = {"method": "post"}
with pytest.raises(TypeError):
browser.get_request_kwargs(form, page.url, **kwargs) | Raise TypeError exception | test_get_request_kwargs_when_method_is_in_kwargs | python | MechanicalSoup/MechanicalSoup | tests/test_browser.py | https://github.com/MechanicalSoup/MechanicalSoup/blob/master/tests/test_browser.py | MIT |
def test_get_request_kwargs_when_url_is_in_kwargs(httpbin):
"""Raise TypeError exception"""
browser = mechanicalsoup.Browser()
page = browser.get(httpbin + "/forms/post")
form = page.soup.form
kwargs = {"url": httpbin + "/forms/post"}
with pytest.raises(TypeError):
# pylint: disable=redundant-keyword-arg
browser.get_request_kwargs(form, page.url, **kwargs) | Raise TypeError exception | test_get_request_kwargs_when_url_is_in_kwargs | python | MechanicalSoup/MechanicalSoup | tests/test_browser.py | https://github.com/MechanicalSoup/MechanicalSoup/blob/master/tests/test_browser.py | MIT |
def test__request_select_none(httpbin):
"""Make sure that a <select> with no options selected
submits the first option, as it does in a browser."""
form_html = f"""
<form method="post" action={httpbin.url}/post>
<select name="shape">
<option value="round">Round</option>
<option value="square">Square</option>
</select>
</form>"""
form = BeautifulSoup(form_html, "lxml").form
browser = mechanicalsoup.Browser()
response = browser._request(form)
assert response.json()['form'] == {'shape': 'round'} | Make sure that a <select> with no options selected
submits the first option, as it does in a browser. | test__request_select_none | python | MechanicalSoup/MechanicalSoup | tests/test_browser.py | https://github.com/MechanicalSoup/MechanicalSoup/blob/master/tests/test_browser.py | MIT |
def test__request_disabled_attr(httpbin):
"""Make sure that disabled form controls are not submitted."""
form_html = f"""
<form method="post" action="{httpbin.url}/post">
<input disabled name="nosubmit" value="1" />
</form>"""
browser = mechanicalsoup.Browser()
response = browser._request(BeautifulSoup(form_html, "lxml").form)
assert response.json()['form'] == {} | Make sure that disabled form controls are not submitted. | test__request_disabled_attr | python | MechanicalSoup/MechanicalSoup | tests/test_browser.py | https://github.com/MechanicalSoup/MechanicalSoup/blob/master/tests/test_browser.py | MIT |
def test_request_keyword_error(keyword):
"""Make sure exception is raised if kwargs duplicates an arg."""
form_html = "<form></form>"
browser = mechanicalsoup.Browser()
with pytest.raises(TypeError, match="multiple values for"):
browser._request(BeautifulSoup(form_html, "lxml").form,
'myurl', **{keyword: 'somevalue'}) | Make sure exception is raised if kwargs duplicates an arg. | test_request_keyword_error | python | MechanicalSoup/MechanicalSoup | tests/test_browser.py | https://github.com/MechanicalSoup/MechanicalSoup/blob/master/tests/test_browser.py | MIT |
def test_set_cookiejar(httpbin):
"""Set cookies locally and test that they are received remotely."""
# construct a phony cookiejar and attach it to the session
jar = RequestsCookieJar()
jar.set('field', 'value')
assert jar.get('field') == 'value'
browser = mechanicalsoup.Browser()
browser.set_cookiejar(jar)
resp = browser.get(httpbin + "/cookies")
assert resp.json() == {'cookies': {'field': 'value'}} | Set cookies locally and test that they are received remotely. | test_set_cookiejar | python | MechanicalSoup/MechanicalSoup | tests/test_browser.py | https://github.com/MechanicalSoup/MechanicalSoup/blob/master/tests/test_browser.py | MIT |
def test_get_cookiejar(httpbin):
"""Test that cookies set by the remote host update our session."""
browser = mechanicalsoup.Browser()
resp = browser.get(httpbin + "/cookies/set?k1=v1&k2=v2")
assert resp.json() == {'cookies': {'k1': 'v1', 'k2': 'v2'}}
jar = browser.get_cookiejar()
assert jar.get('k1') == 'v1'
assert jar.get('k2') == 'v2' | Test that cookies set by the remote host update our session. | test_get_cookiejar | python | MechanicalSoup/MechanicalSoup | tests/test_browser.py | https://github.com/MechanicalSoup/MechanicalSoup/blob/master/tests/test_browser.py | MIT |
def test_construct_form_fail():
"""Form objects must be constructed from form html elements."""
soup = bs4.BeautifulSoup('<notform>This is not a form</notform>', 'lxml')
tag = soup.find('notform')
assert isinstance(tag, bs4.element.Tag)
with pytest.warns(FutureWarning, match="from a 'notform'"):
mechanicalsoup.Form(tag) | Form objects must be constructed from form html elements. | test_construct_form_fail | python | MechanicalSoup/MechanicalSoup | tests/test_form.py | https://github.com/MechanicalSoup/MechanicalSoup/blob/master/tests/test_form.py | MIT |
def test_submit_online(httpbin):
"""Complete and submit the pizza form at http://httpbin.org/forms/post """
browser = mechanicalsoup.Browser()
page = browser.get(httpbin + "/forms/post")
form = mechanicalsoup.Form(page.soup.form)
input_data = {"custname": "Philip J. Fry"}
form.input(input_data)
check_data = {"size": "large", "topping": ["cheese"]}
form.check(check_data)
check_data = {"size": "medium", "topping": "onion"}
form.check(check_data)
form.textarea({"comments": "warm"})
form.textarea({"comments": "actually, no, not warm"})
form.textarea({"comments": "freezer"})
response = browser.submit(form, page.url)
# helpfully the form submits to http://httpbin.org/post which simply
# returns the request headers in json format
json = response.json()
data = json["form"]
assert data["custname"] == "Philip J. Fry"
assert data["custtel"] == "" # web browser submits "" for input left blank
assert data["size"] == "medium"
assert data["topping"] == ["cheese", "onion"]
assert data["comments"] == "freezer" | Complete and submit the pizza form at http://httpbin.org/forms/post | test_submit_online | python | MechanicalSoup/MechanicalSoup | tests/test_form.py | https://github.com/MechanicalSoup/MechanicalSoup/blob/master/tests/test_form.py | MIT |
def test_submit_set(httpbin):
"""Complete and submit the pizza form at http://httpbin.org/forms/post """
browser = mechanicalsoup.Browser()
page = browser.get(httpbin + "/forms/post")
form = mechanicalsoup.Form(page.soup.form)
form["custname"] = "Philip J. Fry"
form["size"] = "medium"
form["topping"] = ("cheese", "onion")
form["comments"] = "freezer"
response = browser.submit(form, page.url)
# helpfully the form submits to http://httpbin.org/post which simply
# returns the request headers in json format
json = response.json()
data = json["form"]
assert data["custname"] == "Philip J. Fry"
assert data["custtel"] == "" # web browser submits "" for input left blank
assert data["size"] == "medium"
assert data["topping"] == ["cheese", "onion"]
assert data["comments"] == "freezer" | Complete and submit the pizza form at http://httpbin.org/forms/post | test_submit_set | python | MechanicalSoup/MechanicalSoup | tests/test_form.py | https://github.com/MechanicalSoup/MechanicalSoup/blob/master/tests/test_form.py | MIT |
def test_choose_submit_from_selector(value):
"""Test choose_submit by passing a CSS selector argument."""
text = """
<form method="post" action="mock://form.com/post">
<input type="submit" name="do" value="continue" />
<input type="submit" name="do" value="cancel" />
</form>"""
browser, url = setup_mock_browser(expected_post=[('do', value)], text=text)
browser.open(url)
form = browser.select_form()
submits = form.form.select(f'input[value="{value}"]')
assert len(submits) == 1
form.choose_submit(submits[0])
res = browser.submit_selected()
assert res.status_code == 200 and res.text == 'Success!' | Test choose_submit by passing a CSS selector argument. | test_choose_submit_from_selector | python | MechanicalSoup/MechanicalSoup | tests/test_form.py | https://github.com/MechanicalSoup/MechanicalSoup/blob/master/tests/test_form.py | MIT |
def test_choose_submit_twice():
"""Test that calling choose_submit twice fails."""
text = '''
<form>
<input type="submit" name="test1" value="Test1" />
<input type="submit" name="test2" value="Test2" />
</form>
'''
soup = bs4.BeautifulSoup(text, 'lxml')
form = mechanicalsoup.Form(soup.form)
form.choose_submit('test1')
expected_msg = 'Submit already chosen. Cannot change submit!'
with pytest.raises(Exception, match=expected_msg):
form.choose_submit('test2') | Test that calling choose_submit twice fails. | test_choose_submit_twice | python | MechanicalSoup/MechanicalSoup | tests/test_form.py | https://github.com/MechanicalSoup/MechanicalSoup/blob/master/tests/test_form.py | MIT |
def test_set_select(option):
'''Test the branch of Form.set that finds "select" elements.'''
browser, url = setup_mock_browser(expected_post=option['result'],
text=set_select_form)
browser.open(url)
browser.select_form('form')
if not option['default']:
browser[option['result'][0][0]] = option['result'][0][1]
res = browser.submit_selected()
assert res.status_code == 200 and res.text == 'Success!' | Test the branch of Form.set that finds "select" elements. | test_set_select | python | MechanicalSoup/MechanicalSoup | tests/test_form.py | https://github.com/MechanicalSoup/MechanicalSoup/blob/master/tests/test_form.py | MIT |
def test_set_select_multiple(options):
"""Test a <select multiple> element."""
# When a browser submits multiple selections, the qsl looks like:
# name=option1&name=option2
if not isinstance(options, list) and not isinstance(options, tuple):
expected = [('instrument', options)]
else:
expected = [('instrument', option) for option in options]
browser, url = setup_mock_browser(expected_post=expected,
text=set_select_multiple_form)
browser.open(url)
form = browser.select_form('form')
form.set_select({'instrument': options})
res = browser.submit_selected()
assert res.status_code == 200 and res.text == 'Success!' | Test a <select multiple> element. | test_set_select_multiple | python | MechanicalSoup/MechanicalSoup | tests/test_form.py | https://github.com/MechanicalSoup/MechanicalSoup/blob/master/tests/test_form.py | MIT |
def test_issue180():
"""Test that a KeyError is not raised when Form.choose_submit is called
on a form where a submit element is missing its name-attribute."""
browser = mechanicalsoup.StatefulBrowser()
html = '''
<form>
<input type="submit" value="Invalid" />
<input type="submit" name="valid" value="Valid" />
</form>
'''
browser.open_fake_page(html)
form = browser.select_form()
with pytest.raises(mechanicalsoup.utils.LinkNotFoundError):
form.choose_submit('not_found') | Test that a KeyError is not raised when Form.choose_submit is called
on a form where a submit element is missing its name-attribute. | test_issue180 | python | MechanicalSoup/MechanicalSoup | tests/test_form.py | https://github.com/MechanicalSoup/MechanicalSoup/blob/master/tests/test_form.py | MIT |
def test_issue158():
"""Test that form elements are processed in their order on the page
and that elements with duplicate name-attributes are not clobbered."""
issue158_form = '''
<form method="post" action="mock://form.com/post">
<input name="box" type="hidden" value="1"/>
<input checked="checked" name="box" type="checkbox" value="2"/>
<input name="box" type="hidden" value="0"/>
<input type="submit" value="Submit" />
</form>
'''
expected_post = [('box', '1'), ('box', '2'), ('box', '0')]
browser, url = setup_mock_browser(expected_post=expected_post,
text=issue158_form)
browser.open(url)
browser.select_form()
res = browser.submit_selected()
assert res.status_code == 200 and res.text == 'Success!'
browser.close() | Test that form elements are processed in their order on the page
and that elements with duplicate name-attributes are not clobbered. | test_issue158 | python | MechanicalSoup/MechanicalSoup | tests/test_form.py | https://github.com/MechanicalSoup/MechanicalSoup/blob/master/tests/test_form.py | MIT |
def test_duplicate_submit_buttons():
"""Tests that duplicate submits doesn't break form submissions
See issue https://github.com/MechanicalSoup/MechanicalSoup/issues/264"""
issue264_form = '''
<form method="post" action="mock://form.com/post">
<input name="box" type="hidden" value="1"/>
<input name="search" type="submit" value="Search"/>
<input name="search" type="submit" value="Search"/>
</form>
'''
expected_post = [('box', '1'), ('search', 'Search')]
browser, url = setup_mock_browser(expected_post=expected_post,
text=issue264_form)
browser.open(url)
browser.select_form()
res = browser.submit_selected()
assert res.status_code == 200 and res.text == 'Success!'
browser.close() | Tests that duplicate submits doesn't break form submissions
See issue https://github.com/MechanicalSoup/MechanicalSoup/issues/264 | test_duplicate_submit_buttons | python | MechanicalSoup/MechanicalSoup | tests/test_form.py | https://github.com/MechanicalSoup/MechanicalSoup/blob/master/tests/test_form.py | MIT |
def test_choose_submit_buttons(expected_post):
"""Buttons of type reset and button are not valid submits"""
text = """
<form method="post" action="mock://form.com/post">
<button type="butTon" name="sub1" value="val1">Val1</button>
<button type="suBmit" name="sub2" value="val2">Val2</button>
<button type="reset" name="sub3" value="val3">Val3</button>
<button name="sub4" value="val4">Val4</button>
<input type="subMit" name="sub5" value="val5">
</form>
"""
browser, url = setup_mock_browser(expected_post=expected_post, text=text)
browser.open(url)
browser.select_form()
res = browser.submit_selected(btnName=expected_post[0][0])
assert res.status_code == 200 and res.text == 'Success!' | Buttons of type reset and button are not valid submits | test_choose_submit_buttons | python | MechanicalSoup/MechanicalSoup | tests/test_form.py | https://github.com/MechanicalSoup/MechanicalSoup/blob/master/tests/test_form.py | MIT |
def test_option_without_value(fail, selected, expected_post):
"""Option tag in select can have no value option"""
text = """
<form method="post" action="mock://form.com/post">
<select name="selector">
<option value="with_value">We have a value here</option>
<option>Without value</option>
</select>
<button type="submit">Submit</button>
</form>
"""
browser, url = setup_mock_browser(expected_post=expected_post,
text=text)
browser.open(url)
browser.select_form()
if fail:
with pytest.raises(mechanicalsoup.utils.LinkNotFoundError):
browser['selector'] = selected
else:
browser['selector'] = selected
res = browser.submit_selected()
assert res.status_code == 200 and res.text == 'Success!' | Option tag in select can have no value option | test_option_without_value | python | MechanicalSoup/MechanicalSoup | tests/test_form.py | https://github.com/MechanicalSoup/MechanicalSoup/blob/master/tests/test_form.py | MIT |
def test_properties():
"""Check that properties return the same value as the getter."""
browser = mechanicalsoup.StatefulBrowser()
browser.open_fake_page('<form></form>', url="http://example.com")
assert browser.page == browser.get_current_page()
assert browser.page is not None
assert browser.url == browser.get_url()
assert browser.url is not None
browser.select_form()
assert browser.form == browser.get_current_form()
assert browser.form is not None | Check that properties return the same value as the getter. | test_properties | python | MechanicalSoup/MechanicalSoup | tests/test_stateful_browser.py | https://github.com/MechanicalSoup/MechanicalSoup/blob/master/tests/test_stateful_browser.py | MIT |
def test_submit_online(httpbin):
"""Complete and submit the pizza form at http://httpbin.org/forms/post """
browser = mechanicalsoup.StatefulBrowser()
browser.set_user_agent('testing MechanicalSoup')
browser.open(httpbin.url)
for link in browser.links():
if link["href"] == "/":
browser.follow_link(link)
break
browser.follow_link("forms/post")
assert browser.url == httpbin + "/forms/post"
browser.select_form("form")
browser["custname"] = "Customer Name Here"
browser["size"] = "medium"
browser["topping"] = ("cheese", "bacon")
# Change our mind to make sure old boxes are unticked
browser["topping"] = ("cheese", "onion")
browser["comments"] = "Some comment here"
browser.form.set("nosuchfield", "new value", True)
response = browser.submit_selected()
json = response.json()
data = json["form"]
assert data["custname"] == "Customer Name Here"
assert data["custtel"] == "" # web browser submits "" for input left blank
assert data["size"] == "medium"
assert set(data["topping"]) == {"cheese", "onion"}
assert data["comments"] == "Some comment here"
assert data["nosuchfield"] == "new value"
assert json["headers"]["User-Agent"] == 'testing MechanicalSoup'
# Ensure we haven't blown away any regular headers
expected_headers = ('Content-Length', 'Host', 'Content-Type', 'Connection',
'Accept', 'User-Agent', 'Accept-Encoding')
assert set(expected_headers).issubset(json["headers"].keys()) | Complete and submit the pizza form at http://httpbin.org/forms/post | test_submit_online | python | MechanicalSoup/MechanicalSoup | tests/test_stateful_browser.py | https://github.com/MechanicalSoup/MechanicalSoup/blob/master/tests/test_stateful_browser.py | MIT |
def test_submit_btnName(expected_post):
'''Tests that the btnName argument chooses the submit button.'''
browser, url = setup_mock_browser(expected_post=expected_post)
browser.open(url)
browser.select_form('#choose-submit-form')
browser['text'] = dict(expected_post)['text']
browser['comment'] = dict(expected_post)['comment']
initial_state = browser._StatefulBrowser__state
res = browser.submit_selected(btnName=expected_post[2][0])
assert res.status_code == 200 and res.text == 'Success!'
assert initial_state != browser._StatefulBrowser__state | Tests that the btnName argument chooses the submit button. | test_submit_btnName | python | MechanicalSoup/MechanicalSoup | tests/test_stateful_browser.py | https://github.com/MechanicalSoup/MechanicalSoup/blob/master/tests/test_stateful_browser.py | MIT |
def test_submit_no_btn(expected_post):
'''Tests that no submit inputs are posted when btnName=False.'''
browser, url = setup_mock_browser(expected_post=expected_post)
browser.open(url)
browser.select_form('#choose-submit-form')
browser['text'] = dict(expected_post)['text']
browser['comment'] = dict(expected_post)['comment']
initial_state = browser._StatefulBrowser__state
res = browser.submit_selected(btnName=False)
assert res.status_code == 200 and res.text == 'Success!'
assert initial_state != browser._StatefulBrowser__state | Tests that no submit inputs are posted when btnName=False. | test_submit_no_btn | python | MechanicalSoup/MechanicalSoup | tests/test_stateful_browser.py | https://github.com/MechanicalSoup/MechanicalSoup/blob/master/tests/test_stateful_browser.py | MIT |
def test_submit_dont_modify_kwargs():
"""Test that submit_selected() doesn't modify the caller's passed-in
kwargs, for example when adding a Referer header.
"""
kwargs = {'headers': {'Content-Type': 'text/html'}}
saved_kwargs = copy.deepcopy(kwargs)
browser, url = setup_mock_browser(expected_post=[], text='<form></form>')
browser.open(url)
browser.select_form()
browser.submit_selected(**kwargs)
assert kwargs == saved_kwargs | Test that submit_selected() doesn't modify the caller's passed-in
kwargs, for example when adding a Referer header. | test_submit_dont_modify_kwargs | python | MechanicalSoup/MechanicalSoup | tests/test_stateful_browser.py | https://github.com/MechanicalSoup/MechanicalSoup/blob/master/tests/test_stateful_browser.py | MIT |
def test_verbose(capsys):
'''Tests that the btnName argument chooses the submit button.'''
browser, url = setup_mock_browser()
browser.open(url)
out, err = capsys.readouterr()
assert out == ""
assert err == ""
assert browser.get_verbose() == 0
browser.set_verbose(1)
browser.open(url)
out, err = capsys.readouterr()
assert out == "."
assert err == ""
assert browser.get_verbose() == 1
browser.set_verbose(2)
browser.open(url)
out, err = capsys.readouterr()
assert out == "mock://form.com\n"
assert err == ""
assert browser.get_verbose() == 2 | Tests that the btnName argument chooses the submit button. | test_verbose | python | MechanicalSoup/MechanicalSoup | tests/test_stateful_browser.py | https://github.com/MechanicalSoup/MechanicalSoup/blob/master/tests/test_stateful_browser.py | MIT |
def test_upload_file_with_malicious_default(httpbin):
"""Check for CVE-2023-34457 by setting the form input value directly to a
file that the user does not explicitly consent to upload, as a malicious
server might do.
"""
browser = mechanicalsoup.StatefulBrowser()
sensitive_path = tempfile.mkstemp()[1]
with open(sensitive_path, "w") as fd:
fd.write("Some sensitive information")
url = httpbin + "/post"
malicious_html = f"""
<form method="post" action="{url}" enctype="multipart/form-data">
<input type="file" name="malicious" value="{sensitive_path}" />
</form>
"""
browser.open_fake_page(malicious_html)
browser.select_form()
response = browser.submit_selected()
assert response.json()["files"] == {"malicious": ""} | Check for CVE-2023-34457 by setting the form input value directly to a
file that the user does not explicitly consent to upload, as a malicious
server might do. | test_upload_file_with_malicious_default | python | MechanicalSoup/MechanicalSoup | tests/test_stateful_browser.py | https://github.com/MechanicalSoup/MechanicalSoup/blob/master/tests/test_stateful_browser.py | MIT |
def test_upload_file_raise_on_string_input():
"""Check for use of the file upload API that was modified to remediate
CVE-2023-34457. Users must now open files manually to upload them.
"""
browser = mechanicalsoup.StatefulBrowser()
file_input_form = """
<form enctype="multipart/form-data">
<input type="file" name="upload" />
</form>
"""
browser.open_fake_page(file_input_form)
browser.select_form()
with pytest.raises(ValueError, match="CVE-2023-34457"):
browser["upload"] = "/path/to/file"
with pytest.raises(ValueError, match="CVE-2023-34457"):
browser.new_control("file", "upload2", "/path/to/file") | Check for use of the file upload API that was modified to remediate
CVE-2023-34457. Users must now open files manually to upload them. | test_upload_file_raise_on_string_input | python | MechanicalSoup/MechanicalSoup | tests/test_stateful_browser.py | https://github.com/MechanicalSoup/MechanicalSoup/blob/master/tests/test_stateful_browser.py | MIT |
def test_with():
"""Test that __enter__/__exit__ properly create/close the browser."""
with mechanicalsoup.StatefulBrowser() as browser:
assert browser.session is not None
assert browser.session is None | Test that __enter__/__exit__ properly create/close the browser. | test_with | python | MechanicalSoup/MechanicalSoup | tests/test_stateful_browser.py | https://github.com/MechanicalSoup/MechanicalSoup/blob/master/tests/test_stateful_browser.py | MIT |
def test_select_form_nr():
"""Test the nr option of select_form."""
forms = """<form id="a"></form><form id="b"></form><form id="c"></form>"""
with mechanicalsoup.StatefulBrowser() as browser:
browser.open_fake_page(forms)
form = browser.select_form()
assert form.form['id'] == "a"
form = browser.select_form(nr=1)
assert form.form['id'] == "b"
form = browser.select_form(nr=2)
assert form.form['id'] == "c"
with pytest.raises(mechanicalsoup.LinkNotFoundError):
browser.select_form(nr=3) | Test the nr option of select_form. | test_select_form_nr | python | MechanicalSoup/MechanicalSoup | tests/test_stateful_browser.py | https://github.com/MechanicalSoup/MechanicalSoup/blob/master/tests/test_stateful_browser.py | MIT |
def test_select_form_tag_object():
"""Test tag object as selector parameter type"""
forms = """<form id="a"></form><form id="b"></form><p></p>"""
soup = BeautifulSoup(forms, "lxml")
with mechanicalsoup.StatefulBrowser() as browser:
browser.open_fake_page(forms)
form = browser.select_form(soup.find("form", {"id": "b"}))
assert form.form['id'] == "b"
with pytest.raises(mechanicalsoup.LinkNotFoundError):
browser.select_form(soup.find("p")) | Test tag object as selector parameter type | test_select_form_tag_object | python | MechanicalSoup/MechanicalSoup | tests/test_stateful_browser.py | https://github.com/MechanicalSoup/MechanicalSoup/blob/master/tests/test_stateful_browser.py | MIT |
def test_select_form_associated_elements():
"""Test associated elements outside the form tag"""
forms = """<form id="a"><input><textarea></form><input form="a">
<textarea form="a"/><input form="b">
<form id="ab" action="/test.php"><input></form>
<textarea form="ab"></textarea>
"""
with mechanicalsoup.StatefulBrowser() as browser:
browser.open_fake_page(forms)
elements_form_a = set([
"<input/>", "<textarea></textarea>",
'<input form="a"/>', '<textarea form="a"></textarea>'])
elements_form_ab = set(["<input/>", '<textarea form="ab"></textarea>'])
form_by_str = browser.select_form("#a")
form_by_tag = browser.select_form(browser.page.find("form", id='a'))
form_by_css = browser.select_form("form[action$='.php']")
assert set([str(element) for element in form_by_str.form.find_all((
"input", "textarea"))]) == elements_form_a
assert set([str(element) for element in form_by_tag.form.find_all((
"input", "textarea"))]) == elements_form_a
assert set([str(element) for element in form_by_css.form.find_all((
"input", "textarea"))]) == elements_form_ab | Test associated elements outside the form tag | test_select_form_associated_elements | python | MechanicalSoup/MechanicalSoup | tests/test_stateful_browser.py | https://github.com/MechanicalSoup/MechanicalSoup/blob/master/tests/test_stateful_browser.py | MIT |
def test_referer_submit_override(httpbin, referer_header):
"""Ensure the caller can override the Referer header that
mechanicalsoup would normally add. Because headers are case insensitive,
test with both 'Referer' and 'referer'.
"""
browser = mechanicalsoup.StatefulBrowser()
ref = "https://example.com/my-referer"
ref_override = "https://example.com/override"
page = submit_form_headers.format(httpbin.url + "/headers")
browser.open_fake_page(page, url=ref)
browser.select_form()
response = browser.submit_selected(headers={referer_header: ref_override})
headers = response.json()["headers"]
referer = headers["Referer"]
actual_ref = re.sub('/*$', '', referer)
assert actual_ref == ref_override | Ensure the caller can override the Referer header that
mechanicalsoup would normally add. Because headers are case insensitive,
test with both 'Referer' and 'referer'. | test_referer_submit_override | python | MechanicalSoup/MechanicalSoup | tests/test_stateful_browser.py | https://github.com/MechanicalSoup/MechanicalSoup/blob/master/tests/test_stateful_browser.py | MIT |
def test_follow_link_excess(httpbin):
"""Ensure that excess args are passed to BeautifulSoup"""
browser = mechanicalsoup.StatefulBrowser()
html = '<a href="/foo">Bar</a><a href="/get">Link</a>'
browser.open_fake_page(html, httpbin.url)
browser.follow_link(url_regex='get')
assert browser.url == httpbin + '/get'
browser = mechanicalsoup.StatefulBrowser()
browser.open_fake_page('<a href="/get">Link</a>', httpbin.url)
with pytest.raises(ValueError, match="link parameter cannot be .*"):
browser.follow_link('foo', url_regex='bar') | Ensure that excess args are passed to BeautifulSoup | test_follow_link_excess | python | MechanicalSoup/MechanicalSoup | tests/test_stateful_browser.py | https://github.com/MechanicalSoup/MechanicalSoup/blob/master/tests/test_stateful_browser.py | MIT |
def test_follow_link_ua(httpbin):
"""Tests passing requests parameters to follow_link() by
setting the User-Agent field."""
browser = mechanicalsoup.StatefulBrowser()
# html = '<a href="/foo">Bar</a><a href="/get">Link</a>'
# browser.open_fake_page(html, httpbin.url)
open_legacy_httpbin(browser, httpbin)
bs4_kwargs = {'url_regex': 'user-agent'}
requests_kwargs = {'headers': {"User-Agent": '007'}}
resp = browser.follow_link(bs4_kwargs=bs4_kwargs,
requests_kwargs=requests_kwargs)
assert browser.url == httpbin + '/user-agent'
assert resp.json() == {'user-agent': '007'}
assert resp.request.headers['user-agent'] == '007' | Tests passing requests parameters to follow_link() by
setting the User-Agent field. | test_follow_link_ua | python | MechanicalSoup/MechanicalSoup | tests/test_stateful_browser.py | https://github.com/MechanicalSoup/MechanicalSoup/blob/master/tests/test_stateful_browser.py | MIT |
def test_download_link(httpbin):
"""Test downloading the contents of a link to file."""
browser = mechanicalsoup.StatefulBrowser()
open_legacy_httpbin(browser, httpbin)
tmpdir = tempfile.mkdtemp()
tmpfile = tmpdir + '/nosuchfile.png'
current_url = browser.url
current_page = browser.page
response = browser.download_link(file=tmpfile, link='image/png')
# Check that the browser state has not changed
assert browser.url == current_url
assert browser.page == current_page
# Check that the file was downloaded
assert os.path.isfile(tmpfile)
assert file_get_contents(tmpfile) == response.content
# Check that we actually downloaded a PNG file
assert response.content[:4] == b'\x89PNG' | Test downloading the contents of a link to file. | test_download_link | python | MechanicalSoup/MechanicalSoup | tests/test_stateful_browser.py | https://github.com/MechanicalSoup/MechanicalSoup/blob/master/tests/test_stateful_browser.py | MIT |
def test_download_link_nofile(httpbin):
"""Test downloading the contents of a link without saving it."""
browser = mechanicalsoup.StatefulBrowser()
open_legacy_httpbin(browser, httpbin)
current_url = browser.url
current_page = browser.page
response = browser.download_link(link='image/png')
# Check that the browser state has not changed
assert browser.url == current_url
assert browser.page == current_page
# Check that we actually downloaded a PNG file
assert response.content[:4] == b'\x89PNG' | Test downloading the contents of a link without saving it. | test_download_link_nofile | python | MechanicalSoup/MechanicalSoup | tests/test_stateful_browser.py | https://github.com/MechanicalSoup/MechanicalSoup/blob/master/tests/test_stateful_browser.py | MIT |
def test_download_link_nofile_bs4(httpbin):
"""Test downloading the contents of a link without saving it."""
browser = mechanicalsoup.StatefulBrowser()
open_legacy_httpbin(browser, httpbin)
current_url = browser.url
current_page = browser.page
response = browser.download_link(bs4_kwargs={'url_regex': 'image.png'})
# Check that the browser state has not changed
assert browser.url == current_url
assert browser.page == current_page
# Check that we actually downloaded a PNG file
assert response.content[:4] == b'\x89PNG' | Test downloading the contents of a link without saving it. | test_download_link_nofile_bs4 | python | MechanicalSoup/MechanicalSoup | tests/test_stateful_browser.py | https://github.com/MechanicalSoup/MechanicalSoup/blob/master/tests/test_stateful_browser.py | MIT |
def test_download_link_nofile_excess(httpbin):
"""Test downloading the contents of a link without saving it."""
browser = mechanicalsoup.StatefulBrowser()
open_legacy_httpbin(browser, httpbin)
current_url = browser.url
current_page = browser.page
response = browser.download_link(url_regex='image.png')
# Check that the browser state has not changed
assert browser.url == current_url
assert browser.page == current_page
# Check that we actually downloaded a PNG file
assert response.content[:4] == b'\x89PNG' | Test downloading the contents of a link without saving it. | test_download_link_nofile_excess | python | MechanicalSoup/MechanicalSoup | tests/test_stateful_browser.py | https://github.com/MechanicalSoup/MechanicalSoup/blob/master/tests/test_stateful_browser.py | MIT |
def test_download_link_nofile_ua(httpbin):
"""Test downloading the contents of a link without saving it."""
browser = mechanicalsoup.StatefulBrowser()
open_legacy_httpbin(browser, httpbin)
current_url = browser.url
current_page = browser.page
requests_kwargs = {'headers': {"User-Agent": '007'}}
response = browser.download_link(link='image/png',
requests_kwargs=requests_kwargs)
# Check that the browser state has not changed
assert browser.url == current_url
assert browser.page == current_page
# Check that we actually downloaded a PNG file
assert response.content[:4] == b'\x89PNG'
# Check that we actually set the User-agent outbound
assert response.request.headers['user-agent'] == '007' | Test downloading the contents of a link without saving it. | test_download_link_nofile_ua | python | MechanicalSoup/MechanicalSoup | tests/test_stateful_browser.py | https://github.com/MechanicalSoup/MechanicalSoup/blob/master/tests/test_stateful_browser.py | MIT |
def test_download_link_to_existing_file(httpbin):
"""Test downloading the contents of a link to an existing file."""
browser = mechanicalsoup.StatefulBrowser()
open_legacy_httpbin(browser, httpbin)
tmpdir = tempfile.mkdtemp()
tmpfile = tmpdir + '/existing.png'
with open(tmpfile, "w") as fd:
fd.write("initial content")
current_url = browser.url
current_page = browser.page
response = browser.download_link('image/png', tmpfile)
# Check that the browser state has not changed
assert browser.url == current_url
assert browser.page == current_page
# Check that the file was downloaded
assert os.path.isfile(tmpfile)
assert file_get_contents(tmpfile) == response.content
# Check that we actually downloaded a PNG file
assert response.content[:4] == b'\x89PNG' | Test downloading the contents of a link to an existing file. | test_download_link_to_existing_file | python | MechanicalSoup/MechanicalSoup | tests/test_stateful_browser.py | https://github.com/MechanicalSoup/MechanicalSoup/blob/master/tests/test_stateful_browser.py | MIT |
def test_download_link_404(httpbin):
"""Test downloading the contents of a broken link."""
browser = mechanicalsoup.StatefulBrowser(raise_on_404=True)
browser.open_fake_page('<a href="/no-such-page-404">Link</a>',
url=httpbin.url)
tmpdir = tempfile.mkdtemp()
tmpfile = tmpdir + '/nosuchfile.txt'
current_url = browser.url
current_page = browser.page
with pytest.raises(mechanicalsoup.LinkNotFoundError):
browser.download_link(file=tmpfile, link_text='Link')
# Check that the browser state has not changed
assert browser.url == current_url
assert browser.page == current_page
# Check that the file was not downloaded
assert not os.path.exists(tmpfile) | Test downloading the contents of a broken link. | test_download_link_404 | python | MechanicalSoup/MechanicalSoup | tests/test_stateful_browser.py | https://github.com/MechanicalSoup/MechanicalSoup/blob/master/tests/test_stateful_browser.py | MIT |
def test_download_link_referer(httpbin):
"""Test downloading the contents of a link to file."""
browser = mechanicalsoup.StatefulBrowser()
ref = httpbin + "/my-referer"
browser.open_fake_page('<a href="/headers">Link</a>',
url=ref)
tmpfile = tempfile.NamedTemporaryFile()
current_url = browser.url
current_page = browser.page
browser.download_link(file=tmpfile.name, link_text='Link')
# Check that the browser state has not changed
assert browser.url == current_url
assert browser.page == current_page
# Check that the file was downloaded
with open(tmpfile.name) as fd:
json_data = json.load(fd)
headers = json_data["headers"]
assert headers["Referer"] == ref | Test downloading the contents of a link to file. | test_download_link_referer | python | MechanicalSoup/MechanicalSoup | tests/test_stateful_browser.py | https://github.com/MechanicalSoup/MechanicalSoup/blob/master/tests/test_stateful_browser.py | MIT |
def test_requests_session_and_cookies(httpbin):
"""Check that the session object passed to the constructor of
StatefulBrowser is actually taken into account."""
s = requests.Session()
requests.utils.add_dict_to_cookiejar(s.cookies, {'key1': 'val1'})
browser = mechanicalsoup.StatefulBrowser(session=s)
resp = browser.get(httpbin + "/cookies")
assert resp.json() == {'cookies': {'key1': 'val1'}} | Check that the session object passed to the constructor of
StatefulBrowser is actually taken into account. | test_requests_session_and_cookies | python | MechanicalSoup/MechanicalSoup | tests/test_stateful_browser.py | https://github.com/MechanicalSoup/MechanicalSoup/blob/master/tests/test_stateful_browser.py | MIT |
def shuffle_sparse_matrix(
sparse_matrix, dropout_rate=0.0, min_dropout_rate=0.05, max_dropout_rate=0.99
):
"""
Shuffle sparse matrix encoded as a SciPy csr matrix.
"""
assert dropout_rate >= 0.0 and dropout_rate <= 1.0
(num_rows, num_cols) = sparse_matrix.shape
shuffled_rows = shuffle(np.arange(num_rows))
shuffled_cols = shuffle(np.arange(num_cols))
sparse_matrix = _dropout_sparse_coo_matrix(
sparse_matrix, dropout_rate, min_dropout_rate, max_dropout_rate
)
new_row = np.take(shuffled_rows, sparse_matrix.row)
new_col = np.take(shuffled_cols, sparse_matrix.col)
return sparse.csr_matrix(
(sparse_matrix.data, (new_row, new_col)), shape=(num_rows, num_cols)
) | Shuffle sparse matrix encoded as a SciPy csr matrix. | shuffle_sparse_matrix | python | facebookresearch/generative-recommenders | run_fractal_expansion.py | https://github.com/facebookresearch/generative-recommenders/blob/master/run_fractal_expansion.py | Apache-2.0 |
def graph_reduce(usv, num_rows, num_cols):
"""Apply algorithm 2 in https://arxiv.org/pdf/1901.08910.pdf."""
def _closest_column_orthogonal_matrix(matrix):
return np.matmul(
matrix, np.linalg.inv(scipy.linalg.sqrtm(np.matmul(matrix.T, matrix)))
)
u, s, v = usv
k = min(num_rows, num_cols)
u_random_proj = transform.resize(u[:, :k], (num_rows, k))
v_random_proj = transform.resize(v[:k, :], (k, num_cols))
u_random_proj_orth = _closest_column_orthogonal_matrix(u_random_proj)
v_random_proj_orth = _closest_column_orthogonal_matrix(v_random_proj.T).T
return np.matmul(u_random_proj_orth, np.matmul(np.diag(s[:k]), v_random_proj_orth)) | Apply algorithm 2 in https://arxiv.org/pdf/1901.08910.pdf. | graph_reduce | python | facebookresearch/generative-recommenders | run_fractal_expansion.py | https://github.com/facebookresearch/generative-recommenders/blob/master/run_fractal_expansion.py | Apache-2.0 |
def rescale(matrix, rescale_w_abs=False):
"""Rescale all values of the matrix into [0, 1]."""
if rescale_w_abs:
abs_matrix = np.abs(matrix.copy())
return abs_matrix / abs_matrix.max()
else:
out = (matrix - matrix.min()) / (matrix.max() - matrix.min())
assert out.min() >= 0 and out.max() <= 1
return out | Rescale all values of the matrix into [0, 1]. | rescale | python | facebookresearch/generative-recommenders | run_fractal_expansion.py | https://github.com/facebookresearch/generative-recommenders/blob/master/run_fractal_expansion.py | Apache-2.0 |
def _compute_row_block(
i, left_matrix, right_matrix, indices_out_path, remove_empty_rows
):
"""Compute row block of expansion for row i of the left_matrix."""
kron_blocks = []
num_rows = 0
num_removed_rows = 0
num_interactions = 0
for j in range(left_matrix.shape[1]):
dropout_rate = 1.0 - left_matrix[i, j]
kron_block = shuffle_sparse_matrix(right_matrix, dropout_rate).tocsr()
num_interactions += kron_block.nnz
kron_blocks.append(kron_block)
logger.info(f"Kronecker block ({i}, {j}) processed.")
rows_to_write = sparse.hstack(kron_blocks).tocsr()
logger.info("Writing dataset row by row.")
# Write Kronecker product line per line.
filepath = f"{indices_out_path}_{i}.csv"
os.makedirs(os.path.dirname(filepath), exist_ok=True)
with open(filepath, "w", newline="") as file:
writer = csv.writer(file)
for k in range(right_matrix.shape[0]):
items_to_write = rows_to_write.getrow(k).indices
ratings_to_write = rows_to_write.getrow(k).data
num = items_to_write.shape[0]
if remove_empty_rows and (not num):
logger.info(f"Removed empty output row {i * left_matrix.shape[0] + k}.")
num_removed_rows += 1
continue
num_rows += 1
writer.writerow(
[
i * right_matrix.shape[0] + k,
",".join([str(x) for x in items_to_write]),
",".join([str(x) for x in ratings_to_write]),
]
)
if k % 100000 == 0:
logger.info(f"Done producing data set row {k}.")
num_cols = rows_to_write.shape[1]
metadata = SparseMatrixMetadata(
num_interactions=num_interactions, num_rows=num_rows, num_cols=num_cols
)
logger.info(
f"Done with left matrix row {i}, {num_interactions} interactions written in shard, {num_removed_rows} rows removed in shard."
)
return (num_removed_rows, metadata) | Compute row block of expansion for row i of the left_matrix. | _compute_row_block | python | facebookresearch/generative-recommenders | run_fractal_expansion.py | https://github.com/facebookresearch/generative-recommenders/blob/master/run_fractal_expansion.py | Apache-2.0 |
def build_randomized_kronecker(
left_matrix,
right_matrix,
indices_out_path,
metadata_out_path=None,
remove_empty_rows=True,
):
"""Compute randomized Kronecker product and dump it on the fly based on https://arxiv.org/pdf/1901.08910.pdf."""
logger.info(f"Writing item sequences to pickle files {metadata_out_path}.")
num_rows = 0
num_removed_rows = 0
num_cols = left_matrix.shape[1] * right_matrix.shape[1]
num_interactions = 0
filepath = f"{indices_out_path}_users.csv"
os.makedirs(os.path.dirname(filepath), exist_ok=True)
with open(filepath, "w", newline="") as file:
writer = csv.writer(file)
for i in tqdm(range(left_matrix.shape[0])):
(shard_num_removed_rows, shard_metadata) = _compute_row_block(
i, left_matrix, right_matrix, indices_out_path, remove_empty_rows
)
writer.writerow([i, shard_metadata.num_rows])
file.flush()
num_rows += shard_metadata.num_rows
num_removed_rows += shard_num_removed_rows
num_interactions += shard_metadata.num_interactions
logger.info(f"{num_interactions / num_rows} average sequence length")
logger.info(f"{num_interactions} total interactions written.")
logger.info(f"{num_removed_rows} total rows removed.")
metadata = SparseMatrixMetadata(
num_interactions=num_interactions, num_rows=num_rows, num_cols=num_cols
)
if metadata_out_path is not None:
logger.info(f"Writing metadata file to {metadata_out_path}")
with open(metadata_out_path, "wb") as output_file:
pickle.dump(metadata, output_file)
return metadata | Compute randomized Kronecker product and dump it on the fly based on https://arxiv.org/pdf/1901.08910.pdf. | build_randomized_kronecker | python | facebookresearch/generative-recommenders | run_fractal_expansion.py | https://github.com/facebookresearch/generative-recommenders/blob/master/run_fractal_expansion.py | Apache-2.0 |
def _preprocess_movie_lens(ratings_df, binary=False):
"""
Filters out users with less than three distinct timestamps.
"""
def _create_index(df, colname):
value_set = sorted(set(df[colname].values))
num_unique = len(value_set)
return dict(zip(value_set, range(num_unique)))
if not binary:
ratings_df["data"] = ratings_df["rating"]
else:
ratings_df["data"] = 1.0
ratings_df["binary_data"] = 1.0
num_timestamps = ratings_df[["userId", "timestamp"]].groupby("userId").nunique()
ratings_df["numberOfTimestamps"] = ratings_df["userId"].apply(
lambda x: num_timestamps["timestamp"][x]
)
ratings_df = ratings_df[ratings_df["numberOfTimestamps"] > 2]
user_id_to_user_idx = _create_index(ratings_df, "userId")
item_id_to_item_idx = _create_index(ratings_df, "movieId")
ratings_df["row"] = ratings_df["userId"].apply(lambda x: user_id_to_user_idx[x])
ratings_df["col"] = ratings_df["movieId"].apply(lambda x: item_id_to_item_idx[x])
return ratings_df | Filters out users with less than three distinct timestamps. | _preprocess_movie_lens | python | facebookresearch/generative-recommenders | run_fractal_expansion.py | https://github.com/facebookresearch/generative-recommenders/blob/master/run_fractal_expansion.py | Apache-2.0 |
def forward(
self,
query_embeddings: torch.Tensor,
item_embeddings: torch.Tensor,
**kwargs,
) -> Tuple[torch.Tensor, Dict[str, torch.Tensor]]:
"""
Args:
query_embeddings: (B, input_embedding_dim) x float.
item_embeddings: (1/B, X, item_embedding_dim) x float.
**kwargs: Implementation-specific keys/values (e.g.,
item ids / sideinfo, etc.)
Returns:
A tuple of (
(B, X,) similarity values,
keyed outputs representing auxiliary losses at training time.
).
"""
pass | Args:
query_embeddings: (B, input_embedding_dim) x float.
item_embeddings: (1/B, X, item_embedding_dim) x float.
**kwargs: Implementation-specific keys/values (e.g.,
item ids / sideinfo, etc.)
Returns:
A tuple of (
(B, X,) similarity values,
keyed outputs representing auxiliary losses at training time.
). | forward | python | facebookresearch/generative-recommenders | generative_recommenders/research/rails/similarities/module.py | https://github.com/facebookresearch/generative-recommenders/blob/master/generative_recommenders/research/rails/similarities/module.py | Apache-2.0 |
def forward(
self,
query_embeddings: torch.Tensor,
item_embeddings: torch.Tensor,
**kwargs,
) -> Tuple[torch.Tensor, Dict[str, torch.Tensor]]:
"""
Args:
query_embeddings: (B, D,) or (B * r, D) x float.
item_embeddings: (1, X, D) or (B, X, D) x float.
Returns:
(B, X) x float.
"""
B_I, X, D = item_embeddings.size()
if B_I == 1:
# [B, D] x ([1, X, D] -> [D, X]) => [B, X]
return (
torch.mm(query_embeddings, item_embeddings.squeeze(0).t()),
{},
) # [B, X]
elif query_embeddings.size(0) != B_I:
# (B * r, D) x (B, X, D).
return (
torch.bmm(
query_embeddings.view(B_I, -1, D),
item_embeddings.permute(0, 2, 1),
).view(-1, X),
{},
)
else:
# [B, X, D] x ([B, D] -> [B, D, 1]) => [B, X, 1] -> [B, X]
return (
torch.bmm(item_embeddings, query_embeddings.unsqueeze(2)).squeeze(2),
{},
) | Args:
query_embeddings: (B, D,) or (B * r, D) x float.
item_embeddings: (1, X, D) or (B, X, D) x float.
Returns:
(B, X) x float. | forward | python | facebookresearch/generative-recommenders | generative_recommenders/research/rails/similarities/dot_product_similarity_fn.py | https://github.com/facebookresearch/generative-recommenders/blob/master/generative_recommenders/research/rails/similarities/dot_product_similarity_fn.py | Apache-2.0 |
def forward(
self,
input_embeddings: torch.Tensor,
**kwargs,
) -> Tuple[torch.Tensor, Dict[str, torch.Tensor]]:
"""
Args:
input_embeddings: (B, ...) x float where B is the batch size.
kwargs: implementation-specific.
Returns:
Tuple of (
(B, query_dot_product_groups/item_dot_product_groups, dot_product_embedding_dim) x float,
str-keyed auxiliary losses.
).
"""
pass | Args:
input_embeddings: (B, ...) x float where B is the batch size.
kwargs: implementation-specific.
Returns:
Tuple of (
(B, query_dot_product_groups/item_dot_product_groups, dot_product_embedding_dim) x float,
str-keyed auxiliary losses.
). | forward | python | facebookresearch/generative-recommenders | generative_recommenders/research/rails/similarities/mol/embeddings_fn.py | https://github.com/facebookresearch/generative-recommenders/blob/master/generative_recommenders/research/rails/similarities/mol/embeddings_fn.py | Apache-2.0 |
def forward(
self,
input_embeddings: torch.Tensor,
**kwargs,
) -> Tuple[torch.Tensor, Dict[str, torch.Tensor]]:
"""
Args:
input_embeddings: (B, query_embedding_dim,) x float where B is the batch size.
kwargs: str-keyed tensors. Implementation-specific.
Returns:
Tuple of (
(B, query_dot_product_groups, dot_product_embedding_dim) x float,
str-keyed aux_losses,
).
"""
split_query_embeddings = self._query_emb_proj_module(input_embeddings).reshape(
(
input_embeddings.size(0),
self._query_emb_based_dot_product_groups,
self._dot_product_dimension,
)
)
aux_losses: Dict[str, torch.Tensor] = {}
if len(self._uid_embedding_hash_sizes) > 0:
all_uid_embeddings = []
for i, hash_size in enumerate(self._uid_embedding_hash_sizes):
# TODO: decouple this from MoLQueryEmbeddingFn.
uid_embeddings = getattr(self, f"_uid_embeddings_{i}")(
(kwargs["user_ids"] % hash_size) + 1
)
if self.training:
l2_norm = (uid_embeddings * uid_embeddings).sum(-1).mean()
if i == 0:
aux_losses["uid_embedding_l2_norm"] = l2_norm
else:
aux_losses["uid_embedding_l2_norm"] = (
aux_losses["uid_embedding_l2_norm"] + l2_norm
)
if self._uid_dropout_rate > 0.0:
if self._uid_embedding_level_dropout:
# conditionally dropout the entire embedding.
if self.training:
uid_dropout_mask = (
torch.rand(
uid_embeddings.size()[:-1],
device=uid_embeddings.device,
)
> self._uid_dropout_rate
)
uid_embeddings = (
uid_embeddings
* uid_dropout_mask.unsqueeze(-1)
/ (1.0 - self._uid_dropout_rate)
)
else:
uid_embeddings = F.dropout(
uid_embeddings,
p=self._uid_dropout_rate,
training=self.training,
)
all_uid_embeddings.append(uid_embeddings.unsqueeze(1))
split_query_embeddings = torch.cat(
[split_query_embeddings] + all_uid_embeddings, dim=1
)
if self._dot_product_l2_norm:
split_query_embeddings = split_query_embeddings / torch.clamp(
torch.linalg.norm(
split_query_embeddings,
ord=None,
dim=-1,
keepdim=True,
),
min=self._eps,
)
return split_query_embeddings, aux_losses | Args:
input_embeddings: (B, query_embedding_dim,) x float where B is the batch size.
kwargs: str-keyed tensors. Implementation-specific.
Returns:
Tuple of (
(B, query_dot_product_groups, dot_product_embedding_dim) x float,
str-keyed aux_losses,
). | forward | python | facebookresearch/generative-recommenders | generative_recommenders/research/rails/similarities/mol/query_embeddings_fn.py | https://github.com/facebookresearch/generative-recommenders/blob/master/generative_recommenders/research/rails/similarities/mol/query_embeddings_fn.py | Apache-2.0 |
def forward(
self,
input_embeddings: torch.Tensor,
**kwargs,
) -> Tuple[torch.Tensor, Dict[str, torch.Tensor]]:
"""
Args:
input_embeddings: (B, item_embedding_dim,) x float where B is the batch size.
kwargs: str-keyed tensors. Implementation-specific.
Returns:
Tuple of (
(B, item_dot_product_groups, dot_product_embedding_dim) x float,
str-keyed aux_losses,
).
"""
split_item_embeddings = self._item_emb_proj_module(input_embeddings).reshape(
input_embeddings.size()[:-1]
+ (
self._item_emb_based_dot_product_groups,
self._dot_product_dimension,
)
)
if self._dot_product_l2_norm:
split_item_embeddings = split_item_embeddings / torch.clamp(
torch.linalg.norm(
split_item_embeddings,
ord=None,
dim=-1,
keepdim=True,
),
min=self._eps,
)
return split_item_embeddings, {} | Args:
input_embeddings: (B, item_embedding_dim,) x float where B is the batch size.
kwargs: str-keyed tensors. Implementation-specific.
Returns:
Tuple of (
(B, item_dot_product_groups, dot_product_embedding_dim) x float,
str-keyed aux_losses,
). | forward | python | facebookresearch/generative-recommenders | generative_recommenders/research/rails/similarities/mol/item_embeddings_fn.py | https://github.com/facebookresearch/generative-recommenders/blob/master/generative_recommenders/research/rails/similarities/mol/item_embeddings_fn.py | Apache-2.0 |
def _softmax_dropout_combiner_fn(
x: torch.Tensor,
y: torch.Tensor,
dropout_pr: float,
eps: float,
training: bool,
) -> Tuple[torch.Tensor, torch.Tensor]:
"""
Computes (_softmax_dropout_fn(x) * y).sum(-1).
"""
x = F.softmax(x, dim=-1)
if dropout_pr > 0.0:
x = F.dropout(x, p=dropout_pr, training=training)
x = x / torch.clamp(x.sum(-1, keepdims=True), min=eps) # pyre-ignore [19]
return x, (x * y).sum(-1) | Computes (_softmax_dropout_fn(x) * y).sum(-1). | _softmax_dropout_combiner_fn | python | facebookresearch/generative-recommenders | generative_recommenders/research/rails/similarities/mol/similarity_fn.py | https://github.com/facebookresearch/generative-recommenders/blob/master/generative_recommenders/research/rails/similarities/mol/similarity_fn.py | Apache-2.0 |
def _load_balancing_mi_loss_fn(
gating_prs: torch.Tensor,
eps: float,
) -> torch.Tensor:
"""
See Retrieval with Learned Similarities (RAILS, https://arxiv.org/abs/2407.15462) for discussions.
"""
B, X, E = gating_prs.size()
expert_util_prs = gating_prs.view(B * X, E).sum(0, keepdim=False) / (1.0 * B * X)
expert_util_entropy = -(expert_util_prs * torch.log(expert_util_prs + eps)).sum()
per_example_expert_entropy = -(gating_prs * torch.log(gating_prs + eps)).sum() / (
1.0 * B * X
)
return -expert_util_entropy + per_example_expert_entropy | See Retrieval with Learned Similarities (RAILS, https://arxiv.org/abs/2407.15462) for discussions. | _load_balancing_mi_loss_fn | python | facebookresearch/generative-recommenders | generative_recommenders/research/rails/similarities/mol/similarity_fn.py | https://github.com/facebookresearch/generative-recommenders/blob/master/generative_recommenders/research/rails/similarities/mol/similarity_fn.py | Apache-2.0 |
def forward(
self,
logits: torch.Tensor,
query_embeddings: torch.Tensor,
item_embeddings: torch.Tensor,
) -> Tuple[torch.Tensor, Dict[str, torch.Tensor]]:
"""
Args:
logits: (B, X, P_Q * P_X) x float;
query_embeddings: (B, D) x float;
item_embeddings: (1/B, X, D') x float;
Returns:
(B, X) x float, Dict[str, Tensor] representing auxiliary losses.
"""
B, X, _ = logits.size()
# [B, 1, F], [1/B, X, F], [B, X, F]
query_partial_inputs, item_partial_inputs, qi_partial_inputs = None, None, None
if self._query_only_partial_module is not None:
query_partial_inputs = self._query_only_partial_module(
query_embeddings
).unsqueeze(1)
if self._item_only_partial_module is not None:
item_partial_inputs = self._item_only_partial_module(item_embeddings)
if self._qi_partial_module is not None:
qi_partial_inputs = self._qi_partial_module(logits)
if self._combination_type == "glu_silu":
gating_inputs = (
query_partial_inputs * item_partial_inputs + qi_partial_inputs
)
gating_weights = gating_inputs * F.sigmoid(gating_inputs)
elif self._combination_type == "glu_silu_ln":
gating_inputs = (
query_partial_inputs * item_partial_inputs + qi_partial_inputs
)
gating_weights = gating_inputs * F.sigmoid(
F.layer_norm(gating_inputs, normalized_shape=[self._num_logits])
)
elif self._combination_type == "none":
gating_inputs = query_partial_inputs
if gating_inputs is None:
gating_inputs = item_partial_inputs
elif item_partial_inputs is not None:
gating_inputs += item_partial_inputs
if gating_inputs is None:
gating_inputs = qi_partial_inputs
elif qi_partial_inputs is not None:
gating_inputs += qi_partial_inputs
gating_weights = gating_inputs
else:
raise ValueError(f"Unknown combination_type {self._combination_type}")
return self._normalization_fn(gating_weights, logits) | Args:
logits: (B, X, P_Q * P_X) x float;
query_embeddings: (B, D) x float;
item_embeddings: (1/B, X, D') x float;
Returns:
(B, X) x float, Dict[str, Tensor] representing auxiliary losses. | forward | python | facebookresearch/generative-recommenders | generative_recommenders/research/rails/similarities/mol/similarity_fn.py | https://github.com/facebookresearch/generative-recommenders/blob/master/generative_recommenders/research/rails/similarities/mol/similarity_fn.py | Apache-2.0 |
def __init__(
self,
query_embedding_dim: int,
item_embedding_dim: int,
dot_product_dimension: int,
query_dot_product_groups: int,
item_dot_product_groups: int,
temperature: float,
dot_product_l2_norm: bool,
query_embeddings_fn: MoLEmbeddingsFn,
item_embeddings_fn: Optional[MoLEmbeddingsFn],
gating_query_only_partial_fn: Optional[Callable[[int, int], torch.nn.Module]],
gating_item_only_partial_fn: Optional[Callable[[int, int], torch.nn.Module]],
gating_qi_partial_fn: Optional[Callable[[int], torch.nn.Module]],
gating_combination_type: str,
gating_normalization_fn: Callable[[int], torch.nn.Module],
eps: float,
apply_query_embeddings_fn: bool = True,
apply_item_embeddings_fn: bool = True,
autocast_bf16: bool = False,
) -> None:
"""
Args:
apply_query_embeddings_fn: bool. If true, compute query_embeddings_fn
to input during forward(). Otherwise, we assume the caller will
invoke get_query_component_embeddings() separately before
calling forward().
apply_item_embeddings_fn: bool. If true, compute item_embeddings_fn
to input during forward(). Otherwise, we assume the caller will
invoke get_item_component_embeddings() separately before
calling forward().
"""
super().__init__()
self._gating_fn: MoLGatingFn = MoLGatingFn(
num_logits=query_dot_product_groups * item_dot_product_groups,
query_embedding_dim=query_embedding_dim,
item_embedding_dim=item_embedding_dim,
query_only_partial_fn=gating_query_only_partial_fn,
item_only_partial_fn=gating_item_only_partial_fn,
qi_partial_fn=gating_qi_partial_fn, # pyre-ignore [6]
combination_type=gating_combination_type,
normalization_fn=gating_normalization_fn,
)
self._query_embeddings_fn: MoLEmbeddingsFn = query_embeddings_fn
self._item_embeddings_fn: MoLEmbeddingsFn = ( # pyre-ignore [8]
item_embeddings_fn
)
self._apply_query_embeddings_fn: bool = apply_query_embeddings_fn
self._apply_item_embeddings_fn: bool = apply_item_embeddings_fn
self._dot_product_l2_norm: bool = dot_product_l2_norm
self._query_dot_product_groups: int = query_dot_product_groups
self._item_dot_product_groups: int = item_dot_product_groups
self._dot_product_dimension: int = dot_product_dimension
self._temperature: float = temperature
self._eps: float = eps
self._autocast_bf16: bool = autocast_bf16 | Args:
apply_query_embeddings_fn: bool. If true, compute query_embeddings_fn
to input during forward(). Otherwise, we assume the caller will
invoke get_query_component_embeddings() separately before
calling forward().
apply_item_embeddings_fn: bool. If true, compute item_embeddings_fn
to input during forward(). Otherwise, we assume the caller will
invoke get_item_component_embeddings() separately before
calling forward(). | __init__ | python | facebookresearch/generative-recommenders | generative_recommenders/research/rails/similarities/mol/similarity_fn.py | https://github.com/facebookresearch/generative-recommenders/blob/master/generative_recommenders/research/rails/similarities/mol/similarity_fn.py | Apache-2.0 |
def get_query_component_embeddings(
self,
input_embeddings: torch.Tensor,
decoupled_inference: bool = False,
**kwargs,
) -> Tuple[torch.Tensor, Dict[str, torch.Tensor]]:
"""
Args:
input_embeddings: (B, self._input_embedding_dim,) x float
or (B, P_Q, self._dot_product_dimension) x float.
decoupled_inference: bool. If true, the call represents an attempt to run
forward() in decoupled mode at inference time (e.g., to pre-compute
component-level query embeddings for filtering, etc.). We simulate
the logic in forward() in this case (e.g., if forward() doesn't apply
query_embeddings_fn, then this call won't either).
kwargs: additional implementation-specific arguments.
Returns:
(B, query_dot_product_groups, dot_product_embedding_dim) x float.
"""
if decoupled_inference and not self._apply_query_embeddings_fn:
return input_embeddings, {}
return self._query_embeddings_fn(input_embeddings, **kwargs) | Args:
input_embeddings: (B, self._input_embedding_dim,) x float
or (B, P_Q, self._dot_product_dimension) x float.
decoupled_inference: bool. If true, the call represents an attempt to run
forward() in decoupled mode at inference time (e.g., to pre-compute
component-level query embeddings for filtering, etc.). We simulate
the logic in forward() in this case (e.g., if forward() doesn't apply
query_embeddings_fn, then this call won't either).
kwargs: additional implementation-specific arguments.
Returns:
(B, query_dot_product_groups, dot_product_embedding_dim) x float. | get_query_component_embeddings | python | facebookresearch/generative-recommenders | generative_recommenders/research/rails/similarities/mol/similarity_fn.py | https://github.com/facebookresearch/generative-recommenders/blob/master/generative_recommenders/research/rails/similarities/mol/similarity_fn.py | Apache-2.0 |
def get_item_component_embeddings(
self,
input_embeddings: torch.Tensor,
decoupled_inference: bool = False,
**kwargs,
) -> Tuple[torch.Tensor, Dict[str, torch.Tensor]]:
"""
Args:
input_embeddings: (..., self._input_embedding_dim,) x float
or (..., P_X, self._dot_product_dimension) x float.
decoupled_inference: bool. If true, the call represents an attempt to run
forward() in decoupled mode at inference time (e.g., to pre-compute
component-level item embeddings for filtering, etc.). We simulate
the logic in forward() in this case (e.g., if forward() doesn't apply
item_embeddings_fn, then this call won't either).
kwargs: additional implementation-specific arguments.
Returns:
(..., item_dot_product_groups, dot_product_embedding_dim) x float.
"""
if decoupled_inference and not self._apply_item_embeddings_fn:
return input_embeddings, {}
return self._item_embeddings_fn(input_embeddings, **kwargs) | Args:
input_embeddings: (..., self._input_embedding_dim,) x float
or (..., P_X, self._dot_product_dimension) x float.
decoupled_inference: bool. If true, the call represents an attempt to run
forward() in decoupled mode at inference time (e.g., to pre-compute
component-level item embeddings for filtering, etc.). We simulate
the logic in forward() in this case (e.g., if forward() doesn't apply
item_embeddings_fn, then this call won't either).
kwargs: additional implementation-specific arguments.
Returns:
(..., item_dot_product_groups, dot_product_embedding_dim) x float. | get_item_component_embeddings | python | facebookresearch/generative-recommenders | generative_recommenders/research/rails/similarities/mol/similarity_fn.py | https://github.com/facebookresearch/generative-recommenders/blob/master/generative_recommenders/research/rails/similarities/mol/similarity_fn.py | Apache-2.0 |
def forward(
self,
query_embeddings: torch.Tensor,
item_embeddings: torch.Tensor,
**kwargs,
) -> Tuple[torch.Tensor, Dict[str, torch.Tensor]]:
"""
Args:
query_embeddings: (B, self._input_embedding_dim) x float or
(B, P_Q, self._dot_product_dimension) x float (when query_embeddings_fn
is applied externally).
item_embeddings: (1/B, X, self._item_embedding_dim) x float or
(1/B, X, P_X, self._dot_product_dimension) x float (when item_embeddings_fn
is applied externally).
kwargs: additional implementation-specific arguments.
Returns:
(B, X) x float, Dict[str, Tensor] representing auxiliary losses.
"""
with torch.autocast(
enabled=self._autocast_bf16, dtype=torch.bfloat16, device_type="cuda"
):
B = query_embeddings.size(0)
B_prime = item_embeddings.shape[0] # 1 or B
X = item_embeddings.shape[1]
if self._apply_query_embeddings_fn:
(
split_query_embeddings,
query_aux_losses,
) = self.get_query_component_embeddings(
query_embeddings,
**kwargs,
)
else:
split_query_embeddings, query_aux_losses = query_embeddings, {}
if self._apply_item_embeddings_fn:
(
split_item_embeddings,
item_aux_losses,
) = self.get_item_component_embeddings(
input_embeddings=item_embeddings,
**kwargs,
)
else:
split_item_embeddings, item_aux_losses = item_embeddings, {}
if B_prime == 1:
logits = torch.einsum(
"bnd,xmd->bxnm",
split_query_embeddings,
split_item_embeddings.squeeze(0),
).reshape(
B, X, self._query_dot_product_groups * self._item_dot_product_groups
)
else:
logits = torch.einsum(
"bnd,bxmd->bxnm", split_query_embeddings, split_item_embeddings
).reshape(
B, X, self._query_dot_product_groups * self._item_dot_product_groups
)
gated_outputs, gating_aux_losses = self._gating_fn(
logits=logits / self._temperature, # [B, X, L]
query_embeddings=query_embeddings, # [B, D]
item_embeddings=item_embeddings, # [1/B, X, D']
)
return gated_outputs, {
**gating_aux_losses,
**query_aux_losses,
**item_aux_losses,
} | Args:
query_embeddings: (B, self._input_embedding_dim) x float or
(B, P_Q, self._dot_product_dimension) x float (when query_embeddings_fn
is applied externally).
item_embeddings: (1/B, X, self._item_embedding_dim) x float or
(1/B, X, P_X, self._dot_product_dimension) x float (when item_embeddings_fn
is applied externally).
kwargs: additional implementation-specific arguments.
Returns:
(B, X) x float, Dict[str, Tensor] representing auxiliary losses. | forward | python | facebookresearch/generative-recommenders | generative_recommenders/research/rails/similarities/mol/similarity_fn.py | https://github.com/facebookresearch/generative-recommenders/blob/master/generative_recommenders/research/rails/similarities/mol/similarity_fn.py | Apache-2.0 |
def __init__(
self,
mol_module: MoLSimilarity,
item_embeddings: torch.Tensor,
item_ids: torch.Tensor,
flatten_item_ids_and_embeddings: bool,
keep_component_level_item_embeddings: bool,
component_level_item_embeddings_dtype: torch.dtype = torch.bfloat16,
) -> None:
"""
Args:
mol_module: MoLSimilarity.
item_embeddings: (1, X, D) if mol_module._apply_item_embeddings_fn is True,
(1, X, P_X, D_P) otherwise.
item_ids: (1, X,) representing the item ids.
flatten_item_ids_and_embeddings: bool. If true, do not keep the extra (1,)
dimension at size(0).
keep_component_level_item_embeddings: bool. If true, keep P_x component-level
embeddings in `self._mol_item_embeddings` for downstream applications.
component_level_item_embeddings_dtype: torch.dtype. If set, the dtype
to keep component-level item embeddings in. By default we use bfloat16.
"""
super().__init__()
self._mol_module: MoLSimilarity = mol_module
self._item_embeddings: torch.Tensor = (
item_embeddings
if not flatten_item_ids_and_embeddings
else item_embeddings.squeeze(0)
)
if keep_component_level_item_embeddings:
self._mol_item_embeddings: torch.Tensor = (
mol_module.get_item_component_embeddings(
(
self._item_embeddings.squeeze(0)
if not flatten_item_ids_and_embeddings
else self._item_embeddings
),
decoupled_inference=True,
)[0] # (X, D) -> (X, P_X, D_P)
).to(component_level_item_embeddings_dtype)
self._item_ids: torch.Tensor = (
item_ids if not flatten_item_ids_and_embeddings else item_ids.squeeze(0)
) | Args:
mol_module: MoLSimilarity.
item_embeddings: (1, X, D) if mol_module._apply_item_embeddings_fn is True,
(1, X, P_X, D_P) otherwise.
item_ids: (1, X,) representing the item ids.
flatten_item_ids_and_embeddings: bool. If true, do not keep the extra (1,)
dimension at size(0).
keep_component_level_item_embeddings: bool. If true, keep P_x component-level
embeddings in `self._mol_item_embeddings` for downstream applications.
component_level_item_embeddings_dtype: torch.dtype. If set, the dtype
to keep component-level item embeddings in. By default we use bfloat16. | __init__ | python | facebookresearch/generative-recommenders | generative_recommenders/research/rails/indexing/mol_top_k.py | https://github.com/facebookresearch/generative-recommenders/blob/master/generative_recommenders/research/rails/indexing/mol_top_k.py | Apache-2.0 |
def forward(
self,
query_embeddings: torch.Tensor,
k: int,
sorted: bool = True,
**kwargs,
) -> Tuple[torch.Tensor, torch.Tensor]:
"""
Args:
query_embeddings: (B, X, D) if mol_module._apply_query_embeddings_fn is True,
(B, X, P_Q, D_P) otherwise.
k: int. final top-k to return.
sorted: bool. whether to sort final top-k results or not.
**kwargs: Implementation-specific keys/values.
Returns:
Tuple of (top_k_scores x float, top_k_ids x int), both of shape (B, K,)
"""
# (B, X,)
all_logits, _ = self.mol_module(
query_embeddings,
self._item_embeddings,
**kwargs,
)
top_k_logits, top_k_indices = torch.topk(
all_logits,
dim=1,
k=k,
sorted=sorted,
largest=True,
) # (B, k,)
return top_k_logits, self._item_ids.squeeze(0)[top_k_indices] | Args:
query_embeddings: (B, X, D) if mol_module._apply_query_embeddings_fn is True,
(B, X, P_Q, D_P) otherwise.
k: int. final top-k to return.
sorted: bool. whether to sort final top-k results or not.
**kwargs: Implementation-specific keys/values.
Returns:
Tuple of (top_k_scores x float, top_k_ids x int), both of shape (B, K,) | forward | python | facebookresearch/generative-recommenders | generative_recommenders/research/rails/indexing/mol_top_k.py | https://github.com/facebookresearch/generative-recommenders/blob/master/generative_recommenders/research/rails/indexing/mol_top_k.py | Apache-2.0 |
def forward(
self,
query_embeddings: torch.Tensor,
k: int,
sorted: bool = True,
**kwargs,
) -> Tuple[torch.Tensor, torch.Tensor]:
"""
Args:
query_embeddings: (B, X, ...). Implementation-specific.
k: int. top k to return.
sorted: bool.
Returns:
Tuple of (top_k_scores, top_k_ids), both of shape (B, K,)
"""
pass | Args:
query_embeddings: (B, X, ...). Implementation-specific.
k: int. top k to return.
sorted: bool.
Returns:
Tuple of (top_k_scores, top_k_ids), both of shape (B, K,) | forward | python | facebookresearch/generative-recommenders | generative_recommenders/research/rails/indexing/candidate_index.py | https://github.com/facebookresearch/generative-recommenders/blob/master/generative_recommenders/research/rails/indexing/candidate_index.py | Apache-2.0 |
def __init__(
self,
item_embeddings: torch.Tensor,
item_ids: torch.Tensor,
) -> None:
"""
Args:
item_embeddings: (1, X, D)
item_ids: (1, X,)
"""
super().__init__()
self._item_embeddings: torch.Tensor = item_embeddings
self._item_ids: torch.Tensor = item_ids | Args:
item_embeddings: (1, X, D)
item_ids: (1, X,) | __init__ | python | facebookresearch/generative-recommenders | generative_recommenders/research/rails/indexing/mips_top_k.py | https://github.com/facebookresearch/generative-recommenders/blob/master/generative_recommenders/research/rails/indexing/mips_top_k.py | Apache-2.0 |
def forward(
self,
query_embeddings: torch.Tensor,
k: int,
sorted: bool = True,
**kwargs,
) -> Tuple[torch.Tensor, torch.Tensor]:
"""
Args:
query_embeddings: (B, ...). Implementation-specific.
k: int. final top-k to return.
sorted: bool. whether to sort final top-k results or not.
Returns:
Tuple of (top_k_scores x float, top_k_ids x int), both of shape (B, K,)
"""
# (B, X,)
all_logits = torch.mm(query_embeddings, self._item_embeddings_t)
top_k_logits, top_k_indices = torch.topk(
all_logits,
dim=1,
k=k,
sorted=sorted,
largest=True,
) # (B, k,)
return top_k_logits, self._item_ids.squeeze(0)[top_k_indices] | Args:
query_embeddings: (B, ...). Implementation-specific.
k: int. final top-k to return.
sorted: bool. whether to sort final top-k results or not.
Returns:
Tuple of (top_k_scores x float, top_k_ids x int), both of shape (B, K,) | forward | python | facebookresearch/generative-recommenders | generative_recommenders/research/rails/indexing/mips_top_k.py | https://github.com/facebookresearch/generative-recommenders/blob/master/generative_recommenders/research/rails/indexing/mips_top_k.py | Apache-2.0 |
def ids(self) -> torch.Tensor:
"""
Returns:
(1, X) or (B, X), where valid ids are positive integers.
"""
return self._ids | Returns:
(1, X) or (B, X), where valid ids are positive integers. | ids | python | facebookresearch/generative-recommenders | generative_recommenders/research/indexing/candidate_index.py | https://github.com/facebookresearch/generative-recommenders/blob/master/generative_recommenders/research/indexing/candidate_index.py | Apache-2.0 |
def embeddings(self) -> torch.Tensor:
"""
Returns:
(1, X, D) or (B, X, D) with the same shape as `ids'.
"""
return self._embeddings | Returns:
(1, X, D) or (B, X, D) with the same shape as `ids'. | embeddings | python | facebookresearch/generative-recommenders | generative_recommenders/research/indexing/candidate_index.py | https://github.com/facebookresearch/generative-recommenders/blob/master/generative_recommenders/research/indexing/candidate_index.py | Apache-2.0 |
def filter_invalid_ids(
self,
invalid_ids: torch.Tensor,
) -> "CandidateIndex":
"""
Filters invalid_ids (batch dimension dependent) from the current index.
Args:
invalid_ids: (B, N) x int64.
Returns:
CandidateIndex with invalid_ids filtered.
"""
X = self._ids.size(1)
if self._ids.size(0) == 1:
# ((1, X, 1) == (B, 1, N)) -> (B, X)
invalid_mask, _ = (self._ids.unsqueeze(2) == invalid_ids.unsqueeze(1)).max(
dim=2
)
lengths = (~invalid_mask).int().sum(-1) # (B,)
valid_1d_mask = (~invalid_mask).view(-1)
B: int = lengths.size(0)
D: int = self._embeddings.size(-1)
jagged_ids = self._ids.expand(B, -1).reshape(-1)[valid_1d_mask]
jagged_embeddings = self._embeddings.expand(B, -1, -1).reshape(-1, D)[
valid_1d_mask
]
X_prime: int = lengths.max(-1)[0].item()
jagged_offsets = torch.ops.fbgemm.asynchronous_complete_cumsum(lengths)
return CandidateIndex(
ids=torch.ops.fbgemm.jagged_to_padded_dense(
values=jagged_ids.unsqueeze(-1),
offsets=[jagged_offsets],
max_lengths=[X_prime],
padding_value=0,
).squeeze(-1),
embeddings=torch.ops.fbgemm.jagged_to_padded_dense(
values=jagged_embeddings,
offsets=[jagged_offsets],
max_lengths=[X_prime],
padding_value=0.0,
),
debug_path=self._debug_path,
)
else:
assert self._invalid_ids == None
return CandidateIndex(
ids=self.ids,
embeddings=self.embeddings,
invalid_ids=invalid_ids,
debug_path=self._debug_path,
) | Filters invalid_ids (batch dimension dependent) from the current index.
Args:
invalid_ids: (B, N) x int64.
Returns:
CandidateIndex with invalid_ids filtered. | filter_invalid_ids | python | facebookresearch/generative-recommenders | generative_recommenders/research/indexing/candidate_index.py | https://github.com/facebookresearch/generative-recommenders/blob/master/generative_recommenders/research/indexing/candidate_index.py | Apache-2.0 |
def get_top_k_outputs(
self,
query_embeddings: torch.Tensor,
k: int,
top_k_module: TopKModule,
invalid_ids: Optional[torch.Tensor],
r: int = 1,
return_embeddings: bool = False,
) -> Tuple[torch.Tensor, torch.Tensor, Optional[torch.Tensor]]:
"""
Gets top-k outputs specified by `policy_fn', while filtering out
invalid ids per row as specified by `invalid_ids'.
Args:
k: int. top k to return.
policy_fn: lambda that takes in item-side embeddings (B, X, D,) and user-side
embeddings (B * r, ...), and returns predictions (unnormalized logits)
of shape (B * r, X,).
invalid_ids: (B * r, N_0) x int64. The list of ids (if > 0) to filter from
results if present. Expect N_0 to be a small constant.
return_embeddings: bool if we should additionally return embeddings for the
top k results.
Returns:
A tuple of (top_k_ids, top_k_prs, top_k_embeddings) of shape (B * r, k, ...).
"""
B: int = query_embeddings.size(0)
max_num_invalid_ids = 0
if invalid_ids is not None:
max_num_invalid_ids = invalid_ids.size(1)
k_prime = min(k + max_num_invalid_ids, self.num_objects)
top_k_prime_scores, top_k_prime_ids = top_k_module(
query_embeddings=query_embeddings, k=k_prime
)
# Masks out invalid items rowwise.
if invalid_ids is not None:
id_is_valid = ~(
(top_k_prime_ids.unsqueeze(2) == invalid_ids.unsqueeze(1)).max(2)[0]
) # [B, K + N_0]
id_is_valid = torch.logical_and(
id_is_valid, torch.cumsum(id_is_valid.int(), dim=1) <= k
)
# [[1, 0, 1, 0], [0, 1, 1, 1]], k=2 -> [[0, 2], [1, 2]]
top_k_rowwise_offsets = torch.nonzero(id_is_valid, as_tuple=True)[1].view(
-1, k
)
top_k_scores = torch.gather(
top_k_prime_scores, dim=1, index=top_k_rowwise_offsets
)
top_k_ids = torch.gather(
top_k_prime_ids, dim=1, index=top_k_rowwise_offsets
)
else:
top_k_scores = top_k_prime_scores
top_k_ids = top_k_prime_ids
# TODO: this should be decoupled from candidate_index.
if return_embeddings:
raise ValueError("return_embeddings not supported yet.")
else:
top_k_embeddings = None
return top_k_ids, top_k_scores, top_k_embeddings | Gets top-k outputs specified by `policy_fn', while filtering out
invalid ids per row as specified by `invalid_ids'.
Args:
k: int. top k to return.
policy_fn: lambda that takes in item-side embeddings (B, X, D,) and user-side
embeddings (B * r, ...), and returns predictions (unnormalized logits)
of shape (B * r, X,).
invalid_ids: (B * r, N_0) x int64. The list of ids (if > 0) to filter from
results if present. Expect N_0 to be a small constant.
return_embeddings: bool if we should additionally return embeddings for the
top k results.
Returns:
A tuple of (top_k_ids, top_k_prs, top_k_embeddings) of shape (B * r, k, ...). | get_top_k_outputs | python | facebookresearch/generative-recommenders | generative_recommenders/research/indexing/candidate_index.py | https://github.com/facebookresearch/generative-recommenders/blob/master/generative_recommenders/research/indexing/candidate_index.py | Apache-2.0 |
def apply_object_filter(self) -> "CandidateIndex":
"""
Applies general per batch filters.
"""
raise NotImplementedError("not implemented.") | Applies general per batch filters. | apply_object_filter | python | facebookresearch/generative-recommenders | generative_recommenders/research/indexing/candidate_index.py | https://github.com/facebookresearch/generative-recommenders/blob/master/generative_recommenders/research/indexing/candidate_index.py | Apache-2.0 |
def eval_metrics_v2_from_tensors(
eval_state: EvalState,
model: SimilarityModule,
seq_features: SequentialFeatures,
target_ids: torch.Tensor, # [B, 1]
min_positive_rating: int = 4,
target_ratings: Optional[torch.Tensor] = None, # [B, 1]
epoch: Optional[str] = None,
filter_invalid_ids: bool = True,
user_max_batch_size: Optional[int] = None,
dtype: Optional[torch.dtype] = None,
) -> Dict[str, Union[float, torch.Tensor]]:
"""
Args:
eval_negatives_ids: Optional[Tensor]. If not present, defaults to eval over
the entire corpus (`num_items`) excluding all the items that users have
seen in the past (historical_ids, target_ids). This is consistent with
papers like SASRec and TDM but may not be fair in practice as retrieval
modules don't have access to read state during the initial fetch stage.
filter_invalid_ids: bool. If true, filters seen ids by default.
Returns:
keyed metric -> list of values for each example.
"""
B, _ = target_ids.shape
device = target_ids.device
for target_id in target_ids:
target_id = int(target_id)
if target_id not in eval_state.all_item_ids:
print(f"missing target_id {target_id}")
# computes ro- part exactly once.
# pyre-fixme[29]: `Union[Tensor, Module]` is not a function.
shared_input_embeddings = model.encode(
past_lengths=seq_features.past_lengths,
past_ids=seq_features.past_ids,
# pyre-fixme[29]: `Union[Tensor, Module]` is not a function.
past_embeddings=model.get_item_embeddings(seq_features.past_ids),
past_payloads=seq_features.past_payloads,
)
if dtype is not None:
shared_input_embeddings = shared_input_embeddings.to(dtype)
MAX_K = 2500
k = min(MAX_K, eval_state.candidate_index.ids.size(1))
user_max_batch_size = user_max_batch_size or shared_input_embeddings.size(0)
num_batches = (
shared_input_embeddings.size(0) + user_max_batch_size - 1
) // user_max_batch_size
eval_top_k_ids_all = []
eval_top_k_prs_all = []
for mb in range(num_batches):
eval_top_k_ids, eval_top_k_prs, _ = (
eval_state.candidate_index.get_top_k_outputs(
query_embeddings=shared_input_embeddings[
mb * user_max_batch_size : (mb + 1) * user_max_batch_size, ...
],
top_k_module=eval_state.top_k_module,
k=k,
invalid_ids=(
seq_features.past_ids[
mb * user_max_batch_size : (mb + 1) * user_max_batch_size, :
]
if filter_invalid_ids
else None
),
return_embeddings=False,
)
)
eval_top_k_ids_all.append(eval_top_k_ids)
eval_top_k_prs_all.append(eval_top_k_prs)
if num_batches == 1:
eval_top_k_ids = eval_top_k_ids_all[0]
eval_top_k_prs = eval_top_k_prs_all[0]
else:
eval_top_k_ids = torch.cat(eval_top_k_ids_all, dim=0)
eval_top_k_prs = torch.cat(eval_top_k_prs_all, dim=0)
assert eval_top_k_ids.size(1) == k
_, eval_rank_indices = torch.max(
torch.cat(
[eval_top_k_ids, target_ids],
dim=1,
)
== target_ids,
dim=1,
)
eval_ranks = torch.where(eval_rank_indices == k, MAX_K + 1, eval_rank_indices + 1)
output = {
"ndcg@1": torch.where(
eval_ranks <= 1,
torch.div(1.0, torch.log2(eval_ranks + 1)),
torch.zeros(1, dtype=torch.float32, device=device),
),
"ndcg@10": torch.where(
eval_ranks <= 10,
torch.div(1.0, torch.log2(eval_ranks + 1)),
torch.zeros(1, dtype=torch.float32, device=device),
),
"ndcg@50": torch.where(
eval_ranks <= 50,
torch.div(1.0, torch.log2(eval_ranks + 1)),
torch.zeros(1, dtype=torch.float32, device=device),
),
"ndcg@100": torch.where(
eval_ranks <= 100,
torch.div(1.0, torch.log2(eval_ranks + 1)),
torch.zeros(1, dtype=torch.float32, device=device),
),
"ndcg@200": torch.where(
eval_ranks <= 200,
torch.div(1.0, torch.log2(eval_ranks + 1)),
torch.zeros(1, dtype=torch.float32, device=device),
),
"hr@1": (eval_ranks <= 1),
"hr@10": (eval_ranks <= 10),
"hr@50": (eval_ranks <= 50),
"hr@100": (eval_ranks <= 100),
"hr@200": (eval_ranks <= 200),
"hr@500": (eval_ranks <= 500),
"hr@1000": (eval_ranks <= 1000),
"mrr": torch.div(1.0, eval_ranks),
}
if target_ratings is not None:
target_ratings = target_ratings.squeeze(1) # [B]
output["ndcg@10_>=4"] = torch.where(
eval_ranks[target_ratings >= 4] <= 10,
torch.div(1.0, torch.log2(eval_ranks[target_ratings >= 4] + 1)),
torch.zeros(1, dtype=torch.float32, device=device),
)
output[f"hr@10_>={min_positive_rating}"] = (
eval_ranks[target_ratings >= min_positive_rating] <= 10
)
output[f"hr@50_>={min_positive_rating}"] = (
eval_ranks[target_ratings >= min_positive_rating] <= 50
)
output[f"mrr_>={min_positive_rating}"] = torch.div(
1.0, eval_ranks[target_ratings >= min_positive_rating]
)
return output # pyre-ignore [7] | Args:
eval_negatives_ids: Optional[Tensor]. If not present, defaults to eval over
the entire corpus (`num_items`) excluding all the items that users have
seen in the past (historical_ids, target_ids). This is consistent with
papers like SASRec and TDM but may not be fair in practice as retrieval
modules don't have access to read state during the initial fetch stage.
filter_invalid_ids: bool. If true, filters seen ids by default.
Returns:
keyed metric -> list of values for each example. | eval_metrics_v2_from_tensors | python | facebookresearch/generative-recommenders | generative_recommenders/research/data/eval.py | https://github.com/facebookresearch/generative-recommenders/blob/master/generative_recommenders/research/data/eval.py | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.