repository_name stringclasses 316 values | func_path_in_repository stringlengths 6 223 | func_name stringlengths 1 134 | language stringclasses 1 value | func_code_string stringlengths 57 65.5k | func_documentation_string stringlengths 1 46.3k | split_name stringclasses 1 value | func_code_url stringlengths 91 315 | called_functions listlengths 1 156 ⌀ | enclosing_scope stringlengths 2 1.48M |
|---|---|---|---|---|---|---|---|---|---|
sentinelsat/sentinelsat | sentinelsat/sentinel.py | SentinelAPI.download_all | python | def download_all(self, products, directory_path='.', max_attempts=10, checksum=True):
product_ids = list(products)
self.logger.info("Will download %d products", len(product_ids))
return_values = OrderedDict()
last_exception = None
for i, product_id in enumerate(products):
for attempt_num in range(max_attempts):
try:
product_info = self.download(product_id, directory_path, checksum)
return_values[product_id] = product_info
break
except (KeyboardInterrupt, SystemExit):
raise
except InvalidChecksumError as e:
last_exception = e
self.logger.warning(
"Invalid checksum. The downloaded file for '%s' is corrupted.", product_id)
except SentinelAPILTAError as e:
last_exception = e
self.logger.exception("There was an error retrieving %s from the LTA", product_id)
break
except Exception as e:
last_exception = e
self.logger.exception("There was an error downloading %s", product_id)
self.logger.info("%s/%s products downloaded", i + 1, len(product_ids))
failed = set(products) - set(return_values)
# split up sucessfully processed products into downloaded and only triggered retrieval from the LTA
triggered = OrderedDict([(k, v) for k, v in return_values.items() if v['Online'] is False])
downloaded = OrderedDict([(k, v) for k, v in return_values.items() if v['Online'] is True])
if len(failed) == len(product_ids) and last_exception is not None:
raise last_exception
return downloaded, triggered, failed | Download a list of products.
Takes a list of product IDs as input. This means that the return value of query() can be
passed directly to this method.
File names on the server are used for the downloaded files, e.g.
"S1A_EW_GRDH_1SDH_20141003T003840_20141003T003920_002658_002F54_4DD1.zip".
In case of interruptions or other exceptions, downloading will restart from where it left
off. Downloading is attempted at most max_attempts times to avoid getting stuck with
unrecoverable errors.
Parameters
----------
products : list
List of product IDs
directory_path : string
Directory where the downloaded files will be downloaded
max_attempts : int, optional
Number of allowed retries before giving up downloading a product. Defaults to 10.
checksum : bool, optional
If True, verify the downloaded files' integrity by checking its MD5 checksum.
Throws InvalidChecksumError if the checksum does not match.
Defaults to True.
Raises
------
Raises the most recent downloading exception if all downloads failed.
Returns
-------
dict[string, dict]
A dictionary containing the return value from download() for each successfully
downloaded product.
dict[string, dict]
A dictionary containing the product information for products whose retrieval
from the long term archive was successfully triggered.
set[string]
The list of products that failed to download. | train | https://github.com/sentinelsat/sentinelsat/blob/eacfd79ff4e7e939147db9dfdd393c67d64eecaa/sentinelsat/sentinel.py#L554-L627 | [
"def download(self, id, directory_path='.', checksum=True):\n \"\"\"Download a product.\n\n Uses the filename on the server for the downloaded file, e.g.\n \"S1A_EW_GRDH_1SDH_20141003T003840_20141003T003920_002658_002F54_4DD1.zip\".\n\n Incomplete downloads are continued and complete files are skipped.\n\n Parameters\n ----------\n id : string\n UUID of the product, e.g. 'a8dd0cfd-613e-45ce-868c-d79177b916ed'\n directory_path : string, optional\n Where the file will be downloaded\n checksum : bool, optional\n If True, verify the downloaded file's integrity by checking its MD5 checksum.\n Throws InvalidChecksumError if the checksum does not match.\n Defaults to True.\n\n Returns\n -------\n product_info : dict\n Dictionary containing the product's info from get_product_info() as well as\n the path on disk.\n\n Raises\n ------\n InvalidChecksumError\n If the MD5 checksum does not match the checksum on the server.\n \"\"\"\n product_info = self.get_product_odata(id)\n path = join(directory_path, product_info['title'] + '.zip')\n product_info['path'] = path\n product_info['downloaded_bytes'] = 0\n\n self.logger.info('Downloading %s to %s', id, path)\n\n if exists(path):\n # We assume that the product has been downloaded and is complete\n return product_info\n\n # An incomplete download triggers the retrieval from the LTA if the product is not online\n if not product_info['Online']:\n self.logger.warning(\n 'Product %s is not online. Triggering retrieval from long term archive.',\n product_info['id'])\n self._trigger_offline_retrieval(product_info['url'])\n return product_info\n\n # Use a temporary file for downloading\n temp_path = path + '.incomplete'\n\n skip_download = False\n if exists(temp_path):\n if getsize(temp_path) > product_info['size']:\n self.logger.warning(\n \"Existing incomplete file %s is larger than the expected final size\"\n \" (%s vs %s bytes). Deleting it.\",\n str(temp_path), getsize(temp_path), product_info['size'])\n remove(temp_path)\n elif getsize(temp_path) == product_info['size']:\n if self._md5_compare(temp_path, product_info['md5']):\n skip_download = True\n else:\n # Log a warning since this should never happen\n self.logger.warning(\n \"Existing incomplete file %s appears to be fully downloaded but \"\n \"its checksum is incorrect. Deleting it.\",\n str(temp_path))\n remove(temp_path)\n else:\n # continue downloading\n self.logger.info(\n \"Download will resume from existing incomplete file %s.\", temp_path)\n pass\n\n if not skip_download:\n # Store the number of downloaded bytes for unit tests\n product_info['downloaded_bytes'] = self._download(\n product_info['url'], temp_path, self.session, product_info['size'])\n\n # Check integrity with MD5 checksum\n if checksum is True:\n if not self._md5_compare(temp_path, product_info['md5']):\n remove(temp_path)\n raise InvalidChecksumError('File corrupt: checksums do not match')\n\n # Download successful, rename the temporary file to its proper name\n shutil.move(temp_path, path)\n return product_info\n"
] | class SentinelAPI:
"""Class to connect to Copernicus Open Access Hub, search and download imagery.
Parameters
----------
user : string
username for DataHub
set to None to use ~/.netrc
password : string
password for DataHub
set to None to use ~/.netrc
api_url : string, optional
URL of the DataHub
defaults to 'https://scihub.copernicus.eu/apihub'
show_progressbars : bool
Whether progressbars should be shown or not, e.g. during download. Defaults to True.
timeout : float or tuple, optional
How long to wait for DataHub response (in seconds).
Tuple (connect, read) allowed.
Attributes
----------
session : requests.Session
Session to connect to DataHub
api_url : str
URL to the DataHub
page_size : int
Number of results per query page.
Current value: 100 (maximum allowed on ApiHub)
timeout : float or tuple
How long to wait for DataHub response (in seconds).
"""
logger = logging.getLogger('sentinelsat.SentinelAPI')
def __init__(self, user, password, api_url='https://scihub.copernicus.eu/apihub/',
show_progressbars=True, timeout=None):
self.session = requests.Session()
if user and password:
self.session.auth = (user, password)
self.api_url = api_url if api_url.endswith('/') else api_url + '/'
self.page_size = 100
self.user_agent = 'sentinelsat/' + sentinelsat_version
self.session.headers['User-Agent'] = self.user_agent
self.show_progressbars = show_progressbars
self.timeout = timeout
# For unit tests
self._last_query = None
self._last_response = None
def query(self, area=None, date=None, raw=None, area_relation='Intersects',
order_by=None, limit=None, offset=0, **keywords):
"""Query the OpenSearch API with the coordinates of an area, a date interval
and any other search keywords accepted by the API.
Parameters
----------
area : str, optional
The area of interest formatted as a Well-Known Text string.
date : tuple of (str or datetime) or str, optional
A time interval filter based on the Sensing Start Time of the products.
Expects a tuple of (start, end), e.g. ("NOW-1DAY", "NOW").
The timestamps can be either a Python datetime or a string in one of the
following formats:
- yyyyMMdd
- yyyy-MM-ddThh:mm:ss.SSSZ (ISO-8601)
- yyyy-MM-ddThh:mm:ssZ
- NOW
- NOW-<n>DAY(S) (or HOUR(S), MONTH(S), etc.)
- NOW+<n>DAY(S)
- yyyy-MM-ddThh:mm:ssZ-<n>DAY(S)
- NOW/DAY (or HOUR, MONTH etc.) - rounds the value to the given unit
Alternatively, an already fully formatted string such as "[NOW-1DAY TO NOW]" can be
used as well.
raw : str, optional
Additional query text that will be appended to the query.
area_relation : {'Intersects', 'Contains', 'IsWithin'}, optional
What relation to use for testing the AOI. Case insensitive.
- Intersects: true if the AOI and the footprint intersect (default)
- Contains: true if the AOI is inside the footprint
- IsWithin: true if the footprint is inside the AOI
order_by: str, optional
A comma-separated list of fields to order by (on server side).
Prefix the field name by '+' or '-' to sort in ascending or descending order,
respectively. Ascending order is used if prefix is omitted.
Example: "cloudcoverpercentage, -beginposition".
limit: int, optional
Maximum number of products returned. Defaults to no limit.
offset: int, optional
The number of results to skip. Defaults to 0.
**keywords
Additional keywords can be used to specify other query parameters,
e.g. `relativeorbitnumber=70`.
See https://scihub.copernicus.eu/twiki/do/view/SciHubUserGuide/3FullTextSearch
for a full list.
Range values can be passed as two-element tuples, e.g. `cloudcoverpercentage=(0, 30)`.
`None` can be used in range values for one-sided ranges, e.g. `orbitnumber=(16302, None)`.
Ranges with no bounds (`orbitnumber=(None, None)`) will not be included in the query.
The time interval formats accepted by the `date` parameter can also be used with
any other parameters that expect time intervals (that is: 'beginposition', 'endposition',
'date', 'creationdate', and 'ingestiondate').
Returns
-------
dict[string, dict]
Products returned by the query as a dictionary with the product ID as the key and
the product's attributes (a dictionary) as the value.
"""
query = self.format_query(area, date, raw, area_relation, **keywords)
self.logger.debug("Running query: order_by=%s, limit=%s, offset=%s, query=%s",
order_by, limit, offset, query)
formatted_order_by = _format_order_by(order_by)
response, count = self._load_query(query, formatted_order_by, limit, offset)
self.logger.info("Found %s products", count)
return _parse_opensearch_response(response)
@staticmethod
def format_query(area=None, date=None, raw=None, area_relation='Intersects',
**keywords):
"""Create a OpenSearch API query string.
"""
if area_relation.lower() not in {"intersects", "contains", "iswithin"}:
raise ValueError("Incorrect AOI relation provided ({})".format(area_relation))
# Check for duplicate keywords
kw_lower = set(x.lower() for x in keywords)
if (len(kw_lower) != len(keywords) or
(date is not None and 'beginposition' in kw_lower) or
(area is not None and 'footprint' in kw_lower)):
raise ValueError("Query contains duplicate keywords. Note that query keywords are case-insensitive.")
query_parts = []
if date is not None:
keywords['beginPosition'] = date
for attr, value in sorted(keywords.items()):
# Escape spaces, where appropriate
if isinstance(value, string_types):
value = value.strip()
if not any(value.startswith(s[0]) and value.endswith(s[1]) for s in ['[]', '{}', '//', '()']):
value = re.sub(r'\s', r'\ ', value, re.M)
# Handle date keywords
# Keywords from https://github.com/SentinelDataHub/DataHubSystem/search?q=text/date+iso8601
date_attrs = ['beginposition', 'endposition', 'date', 'creationdate', 'ingestiondate']
if attr.lower() in date_attrs:
# Automatically format date-type attributes
if isinstance(value, string_types) and ' TO ' in value:
# This is a string already formatted as a date interval,
# e.g. '[NOW-1DAY TO NOW]'
pass
elif not isinstance(value, string_types) and len(value) == 2:
value = (format_query_date(value[0]), format_query_date(value[1]))
else:
raise ValueError("Date-type query parameter '{}' expects a two-element tuple "
"of str or datetime objects. Received {}".format(attr, value))
# Handle ranged values
if isinstance(value, (list, tuple)):
# Handle value ranges
if len(value) == 2:
# Allow None to be used as a unlimited bound
value = ['*' if x is None else x for x in value]
if all(x == '*' for x in value):
continue
value = '[{} TO {}]'.format(*value)
else:
raise ValueError("Invalid number of elements in list. Expected 2, received "
"{}".format(len(value)))
query_parts.append('{}:{}'.format(attr, value))
if raw:
query_parts.append(raw)
if area is not None:
query_parts.append('footprint:"{}({})"'.format(area_relation, area))
return ' '.join(query_parts)
def query_raw(self, query, order_by=None, limit=None, offset=0):
"""
Do a full-text query on the OpenSearch API using the format specified in
https://scihub.copernicus.eu/twiki/do/view/SciHubUserGuide/3FullTextSearch
DEPRECATED: use :meth:`query(raw=...) <.query>` instead. This method will be removed in the next major release.
Parameters
----------
query : str
The query string.
order_by: str, optional
A comma-separated list of fields to order by (on server side).
Prefix the field name by '+' or '-' to sort in ascending or descending order, respectively.
Ascending order is used, if prefix is omitted.
Example: "cloudcoverpercentage, -beginposition".
limit: int, optional
Maximum number of products returned. Defaults to no limit.
offset: int, optional
The number of results to skip. Defaults to 0.
Returns
-------
dict[string, dict]
Products returned by the query as a dictionary with the product ID as the key and
the product's attributes (a dictionary) as the value.
"""
warnings.warn(
"query_raw() has been merged with query(). use query(raw=...) instead.",
PendingDeprecationWarning
)
return self.query(raw=query, order_by=order_by, limit=limit, offset=offset)
def count(self, area=None, date=None, raw=None, area_relation='Intersects', **keywords):
"""Get the number of products matching a query.
Accepted parameters are identical to :meth:`SentinelAPI.query()`.
This is a significantly more efficient alternative to doing `len(api.query())`,
which can take minutes to run for queries matching thousands of products.
Returns
-------
int
The number of products matching a query.
"""
for kw in ['order_by', 'limit', 'offset']:
# Allow these function arguments to be included for compatibility with query(),
# but ignore them.
if kw in keywords:
del keywords[kw]
query = self.format_query(area, date, raw, area_relation, **keywords)
_, total_count = self._load_query(query, limit=0)
return total_count
def _load_query(self, query, order_by=None, limit=None, offset=0):
products, count = self._load_subquery(query, order_by, limit, offset)
# repeat query until all results have been loaded
max_offset = count
if limit is not None:
max_offset = min(count, offset + limit)
if max_offset > offset + self.page_size:
progress = self._tqdm(desc="Querying products",
initial=self.page_size,
total=max_offset - offset,
unit=' products')
for new_offset in range(offset + self.page_size, max_offset, self.page_size):
new_limit = limit
if limit is not None:
new_limit = limit - new_offset + offset
ret = self._load_subquery(query, order_by, new_limit, new_offset)[0]
progress.update(len(ret))
products += ret
progress.close()
return products, count
def _load_subquery(self, query, order_by=None, limit=None, offset=0):
# store last query (for testing)
self._last_query = query
self.logger.debug("Sub-query: offset=%s, limit=%s", offset, limit)
# load query results
url = self._format_url(order_by, limit, offset)
response = self.session.post(url, {'q': query}, auth=self.session.auth,
headers={'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'},
timeout=self.timeout)
_check_scihub_response(response)
# store last status code (for testing)
self._last_response = response
# parse response content
try:
json_feed = response.json()['feed']
if json_feed['opensearch:totalResults'] is None:
# We are using some unintended behavior of the server that a null is
# returned as the total results value when the query string was incorrect.
raise SentinelAPIError(
'Invalid query string. Check the parameters and format.', response)
total_results = int(json_feed['opensearch:totalResults'])
except (ValueError, KeyError):
raise SentinelAPIError('API response not valid. JSON decoding failed.', response)
products = json_feed.get('entry', [])
# this verification is necessary because if the query returns only
# one product, self.products will be a dict not a list
if isinstance(products, dict):
products = [products]
return products, total_results
def _format_url(self, order_by=None, limit=None, offset=0):
if limit is None:
limit = self.page_size
limit = min(limit, self.page_size)
url = 'search?format=json&rows={}'.format(limit)
url += '&start={}'.format(offset)
if order_by:
url += '&orderby={}'.format(order_by)
return urljoin(self.api_url, url)
@staticmethod
def to_geojson(products):
"""Return the products from a query response as a GeoJSON with the values in their
appropriate Python types.
"""
feature_list = []
for i, (product_id, props) in enumerate(products.items()):
props = props.copy()
props['id'] = product_id
poly = geomet.wkt.loads(props['footprint'])
del props['footprint']
del props['gmlfootprint']
# Fix "'datetime' is not JSON serializable"
for k, v in props.items():
if isinstance(v, (date, datetime)):
props[k] = v.strftime('%Y-%m-%dT%H:%M:%S.%fZ')
feature_list.append(
geojson.Feature(geometry=poly, id=i, properties=props)
)
return geojson.FeatureCollection(feature_list)
@staticmethod
def to_dataframe(products):
"""Return the products from a query response as a Pandas DataFrame
with the values in their appropriate Python types.
"""
try:
import pandas as pd
except ImportError:
raise ImportError("to_dataframe requires the optional dependency Pandas.")
return pd.DataFrame.from_dict(products, orient='index')
@staticmethod
def to_geodataframe(products):
"""Return the products from a query response as a GeoPandas GeoDataFrame
with the values in their appropriate Python types.
"""
try:
import geopandas as gpd
import shapely.wkt
except ImportError:
raise ImportError("to_geodataframe requires the optional dependencies GeoPandas and Shapely.")
crs = {'init': 'epsg:4326'} # WGS84
if len(products) == 0:
return gpd.GeoDataFrame(crs=crs)
df = SentinelAPI.to_dataframe(products)
geometry = [shapely.wkt.loads(fp) for fp in df['footprint']]
# remove useless columns
df.drop(['footprint', 'gmlfootprint'], axis=1, inplace=True)
return gpd.GeoDataFrame(df, crs=crs, geometry=geometry)
def get_product_odata(self, id, full=False):
"""Access OData API to get info about a product.
Returns a dict containing the id, title, size, md5sum, date, footprint and download url
of the product. The date field corresponds to the Start ContentDate value.
If `full` is set to True, then the full, detailed metadata of the product is returned
in addition to the above.
Parameters
----------
id : string
The UUID of the product to query
full : bool
Whether to get the full metadata for the Product. False by default.
Returns
-------
dict[str, Any]
A dictionary with an item for each metadata attribute
Notes
-----
For a full list of mappings between the OpenSearch (Solr) and OData attribute names
see the following definition files:
https://github.com/SentinelDataHub/DataHubSystem/blob/master/addon/sentinel-1/src/main/resources/META-INF/sentinel-1.owl
https://github.com/SentinelDataHub/DataHubSystem/blob/master/addon/sentinel-2/src/main/resources/META-INF/sentinel-2.owl
https://github.com/SentinelDataHub/DataHubSystem/blob/master/addon/sentinel-3/src/main/resources/META-INF/sentinel-3.owl
"""
url = urljoin(self.api_url, u"odata/v1/Products('{}')?$format=json".format(id))
if full:
url += '&$expand=Attributes'
response = self.session.get(url, auth=self.session.auth,
timeout=self.timeout)
_check_scihub_response(response)
values = _parse_odata_response(response.json()['d'])
return values
def _trigger_offline_retrieval(self, url):
""" Triggers retrieval of an offline product
Trying to download an offline product triggers its retrieval from the long term archive.
The returned HTTP status code conveys whether this was successful.
Parameters
----------
url : string
URL for downloading the product
Notes
-----
https://scihub.copernicus.eu/userguide/LongTermArchive
"""
with self.session.get(url, auth=self.session.auth, timeout=self.timeout) as r:
# check https://scihub.copernicus.eu/userguide/LongTermArchive#HTTP_Status_codes
if r.status_code == 202:
self.logger.info("Accepted for retrieval")
elif r.status_code == 503:
self.logger.error("Request not accepted")
raise SentinelAPILTAError('Request for retrieval from LTA not accepted', r)
elif r.status_code == 403:
self.logger.error("Requests exceed user quota")
raise SentinelAPILTAError('Requests for retrieval from LTA exceed user quota', r)
elif r.status_code == 500:
# should not happen
self.logger.error("Trying to download an offline product")
raise SentinelAPILTAError('Trying to download an offline product', r)
return r.status_code
def download(self, id, directory_path='.', checksum=True):
"""Download a product.
Uses the filename on the server for the downloaded file, e.g.
"S1A_EW_GRDH_1SDH_20141003T003840_20141003T003920_002658_002F54_4DD1.zip".
Incomplete downloads are continued and complete files are skipped.
Parameters
----------
id : string
UUID of the product, e.g. 'a8dd0cfd-613e-45ce-868c-d79177b916ed'
directory_path : string, optional
Where the file will be downloaded
checksum : bool, optional
If True, verify the downloaded file's integrity by checking its MD5 checksum.
Throws InvalidChecksumError if the checksum does not match.
Defaults to True.
Returns
-------
product_info : dict
Dictionary containing the product's info from get_product_info() as well as
the path on disk.
Raises
------
InvalidChecksumError
If the MD5 checksum does not match the checksum on the server.
"""
product_info = self.get_product_odata(id)
path = join(directory_path, product_info['title'] + '.zip')
product_info['path'] = path
product_info['downloaded_bytes'] = 0
self.logger.info('Downloading %s to %s', id, path)
if exists(path):
# We assume that the product has been downloaded and is complete
return product_info
# An incomplete download triggers the retrieval from the LTA if the product is not online
if not product_info['Online']:
self.logger.warning(
'Product %s is not online. Triggering retrieval from long term archive.',
product_info['id'])
self._trigger_offline_retrieval(product_info['url'])
return product_info
# Use a temporary file for downloading
temp_path = path + '.incomplete'
skip_download = False
if exists(temp_path):
if getsize(temp_path) > product_info['size']:
self.logger.warning(
"Existing incomplete file %s is larger than the expected final size"
" (%s vs %s bytes). Deleting it.",
str(temp_path), getsize(temp_path), product_info['size'])
remove(temp_path)
elif getsize(temp_path) == product_info['size']:
if self._md5_compare(temp_path, product_info['md5']):
skip_download = True
else:
# Log a warning since this should never happen
self.logger.warning(
"Existing incomplete file %s appears to be fully downloaded but "
"its checksum is incorrect. Deleting it.",
str(temp_path))
remove(temp_path)
else:
# continue downloading
self.logger.info(
"Download will resume from existing incomplete file %s.", temp_path)
pass
if not skip_download:
# Store the number of downloaded bytes for unit tests
product_info['downloaded_bytes'] = self._download(
product_info['url'], temp_path, self.session, product_info['size'])
# Check integrity with MD5 checksum
if checksum is True:
if not self._md5_compare(temp_path, product_info['md5']):
remove(temp_path)
raise InvalidChecksumError('File corrupt: checksums do not match')
# Download successful, rename the temporary file to its proper name
shutil.move(temp_path, path)
return product_info
@staticmethod
def get_products_size(products):
"""Return the total file size in GB of all products in the OpenSearch response."""
size_total = 0
for title, props in products.items():
size_product = props["size"]
size_value = float(size_product.split(" ")[0])
size_unit = str(size_product.split(" ")[1])
if size_unit == "MB":
size_value /= 1024.
if size_unit == "KB":
size_value /= 1024. * 1024.
size_total += size_value
return round(size_total, 2)
@staticmethod
def check_query_length(query):
"""Determine whether a query to the OpenSearch API is too long.
The length of a query string is limited to approximately 3938 characters but
any special characters (that is, not alphanumeric or -_.*) will take up more space.
Parameters
----------
query : str
The query string
Returns
-------
float
Ratio of the query length to the maximum length
"""
# The server uses the Java's URLEncoder implementation internally, which we are replicating here
effective_length = len(quote_plus(query, safe="-_.*").replace('~', '%7E'))
return effective_length / 3938
def _query_names(self, names):
"""Find products by their names, e.g.
S1A_EW_GRDH_1SDH_20141003T003840_20141003T003920_002658_002F54_4DD1.
Note that duplicates exist on server, so multiple products can be returned for each name.
Parameters
----------
names : list[string]
List of product names.
Returns
-------
dict[string, dict[str, dict]]
A dictionary mapping each name to a dictionary which contains the products with
that name (with ID as the key).
"""
def chunks(l, n):
"""Yield successive n-sized chunks from l."""
for i in range(0, len(l), n):
yield l[i:i + n]
products = {}
# 40 names per query fits reasonably well inside the query limit
for chunk in chunks(names, 40):
query = " OR ".join(chunk)
products.update(self.query(raw=query))
# Group the products
output = OrderedDict((name, dict()) for name in names)
for id, metadata in products.items():
name = metadata['identifier']
output[name][id] = metadata
return output
def check_files(self, paths=None, ids=None, directory=None, delete=False):
"""Verify the integrity of product files on disk.
Integrity is checked by comparing the size and checksum of the file with the respective
values on the server.
The input can be a list of products to check or a list of IDs and a directory.
In cases where multiple products with different IDs exist on the server for given product
name, the file is considered to be correct if any of them matches the file size and
checksum. A warning is logged in such situations.
The corrupt products' OData info is included in the return value to make it easier to
re-download the products, if necessary.
Parameters
----------
paths : list[string]
List of product file paths.
ids : list[string]
List of product IDs.
directory : string
Directory where the files are located, if checking based on product IDs.
delete : bool
Whether to delete corrupt products. Defaults to False.
Returns
-------
dict[str, list[dict]]
A dictionary listing the invalid or missing files. The dictionary maps the corrupt
file paths to a list of OData dictionaries of matching products on the server (as
returned by :meth:`SentinelAPI.get_product_odata()`).
"""
if not ids and not paths:
raise ValueError("Must provide either file paths or product IDs and a directory")
if ids and not directory:
raise ValueError("Directory value missing")
paths = paths or []
ids = ids or []
def name_from_path(path):
return splitext(basename(path))[0]
# Get product IDs corresponding to the files on disk
names = []
if paths:
names = list(map(name_from_path, paths))
result = self._query_names(names)
for product_dicts in result.values():
ids += list(product_dicts)
names_from_paths = set(names)
ids = set(ids)
# Collect the OData information for each product
# Product name -> list of matching odata dicts
product_infos = defaultdict(list)
for id in ids:
odata = self.get_product_odata(id)
name = odata['title']
product_infos[name].append(odata)
# Collect
if name not in names_from_paths:
paths.append(join(directory, name + '.zip'))
# Now go over the list of products and check them
corrupt = {}
for path in paths:
name = name_from_path(path)
if len(product_infos[name]) > 1:
self.logger.warning("{} matches multiple products on server".format(path))
if not exists(path):
# We will consider missing files as corrupt also
self.logger.info("{} does not exist on disk".format(path))
corrupt[path] = product_infos[name]
continue
is_fine = False
for product_info in product_infos[name]:
if (getsize(path) == product_info['size'] and
self._md5_compare(path, product_info['md5'])):
is_fine = True
break
if not is_fine:
self.logger.info("{} is corrupt".format(path))
corrupt[path] = product_infos[name]
if delete:
remove(path)
return corrupt
def _md5_compare(self, file_path, checksum, block_size=2 ** 13):
"""Compare a given MD5 checksum with one calculated from a file."""
with closing(self._tqdm(desc="MD5 checksumming", total=getsize(file_path), unit="B",
unit_scale=True)) as progress:
md5 = hashlib.md5()
with open(file_path, "rb") as f:
while True:
block_data = f.read(block_size)
if not block_data:
break
md5.update(block_data)
progress.update(len(block_data))
return md5.hexdigest().lower() == checksum.lower()
def _download(self, url, path, session, file_size):
headers = {}
continuing = exists(path)
if continuing:
already_downloaded_bytes = getsize(path)
headers = {'Range': 'bytes={}-'.format(already_downloaded_bytes)}
else:
already_downloaded_bytes = 0
downloaded_bytes = 0
with closing(session.get(url, stream=True, auth=session.auth,
headers=headers, timeout=self.timeout)) as r, \
closing(self._tqdm(desc="Downloading", total=file_size, unit="B",
unit_scale=True, initial=already_downloaded_bytes)) as progress:
_check_scihub_response(r, test_json=False)
chunk_size = 2 ** 20 # download in 1 MB chunks
mode = 'ab' if continuing else 'wb'
with open(path, mode) as f:
for chunk in r.iter_content(chunk_size=chunk_size):
if chunk: # filter out keep-alive new chunks
f.write(chunk)
progress.update(len(chunk))
downloaded_bytes += len(chunk)
# Return the number of bytes downloaded
return downloaded_bytes
def _tqdm(self, **kwargs):
"""tqdm progressbar wrapper. May be overridden to customize progressbar behavior"""
kwargs.update({'disable': not self.show_progressbars})
return tqdm(**kwargs)
|
sentinelsat/sentinelsat | sentinelsat/sentinel.py | SentinelAPI.get_products_size | python | def get_products_size(products):
size_total = 0
for title, props in products.items():
size_product = props["size"]
size_value = float(size_product.split(" ")[0])
size_unit = str(size_product.split(" ")[1])
if size_unit == "MB":
size_value /= 1024.
if size_unit == "KB":
size_value /= 1024. * 1024.
size_total += size_value
return round(size_total, 2) | Return the total file size in GB of all products in the OpenSearch response. | train | https://github.com/sentinelsat/sentinelsat/blob/eacfd79ff4e7e939147db9dfdd393c67d64eecaa/sentinelsat/sentinel.py#L630-L642 | null | class SentinelAPI:
"""Class to connect to Copernicus Open Access Hub, search and download imagery.
Parameters
----------
user : string
username for DataHub
set to None to use ~/.netrc
password : string
password for DataHub
set to None to use ~/.netrc
api_url : string, optional
URL of the DataHub
defaults to 'https://scihub.copernicus.eu/apihub'
show_progressbars : bool
Whether progressbars should be shown or not, e.g. during download. Defaults to True.
timeout : float or tuple, optional
How long to wait for DataHub response (in seconds).
Tuple (connect, read) allowed.
Attributes
----------
session : requests.Session
Session to connect to DataHub
api_url : str
URL to the DataHub
page_size : int
Number of results per query page.
Current value: 100 (maximum allowed on ApiHub)
timeout : float or tuple
How long to wait for DataHub response (in seconds).
"""
logger = logging.getLogger('sentinelsat.SentinelAPI')
def __init__(self, user, password, api_url='https://scihub.copernicus.eu/apihub/',
show_progressbars=True, timeout=None):
self.session = requests.Session()
if user and password:
self.session.auth = (user, password)
self.api_url = api_url if api_url.endswith('/') else api_url + '/'
self.page_size = 100
self.user_agent = 'sentinelsat/' + sentinelsat_version
self.session.headers['User-Agent'] = self.user_agent
self.show_progressbars = show_progressbars
self.timeout = timeout
# For unit tests
self._last_query = None
self._last_response = None
def query(self, area=None, date=None, raw=None, area_relation='Intersects',
order_by=None, limit=None, offset=0, **keywords):
"""Query the OpenSearch API with the coordinates of an area, a date interval
and any other search keywords accepted by the API.
Parameters
----------
area : str, optional
The area of interest formatted as a Well-Known Text string.
date : tuple of (str or datetime) or str, optional
A time interval filter based on the Sensing Start Time of the products.
Expects a tuple of (start, end), e.g. ("NOW-1DAY", "NOW").
The timestamps can be either a Python datetime or a string in one of the
following formats:
- yyyyMMdd
- yyyy-MM-ddThh:mm:ss.SSSZ (ISO-8601)
- yyyy-MM-ddThh:mm:ssZ
- NOW
- NOW-<n>DAY(S) (or HOUR(S), MONTH(S), etc.)
- NOW+<n>DAY(S)
- yyyy-MM-ddThh:mm:ssZ-<n>DAY(S)
- NOW/DAY (or HOUR, MONTH etc.) - rounds the value to the given unit
Alternatively, an already fully formatted string such as "[NOW-1DAY TO NOW]" can be
used as well.
raw : str, optional
Additional query text that will be appended to the query.
area_relation : {'Intersects', 'Contains', 'IsWithin'}, optional
What relation to use for testing the AOI. Case insensitive.
- Intersects: true if the AOI and the footprint intersect (default)
- Contains: true if the AOI is inside the footprint
- IsWithin: true if the footprint is inside the AOI
order_by: str, optional
A comma-separated list of fields to order by (on server side).
Prefix the field name by '+' or '-' to sort in ascending or descending order,
respectively. Ascending order is used if prefix is omitted.
Example: "cloudcoverpercentage, -beginposition".
limit: int, optional
Maximum number of products returned. Defaults to no limit.
offset: int, optional
The number of results to skip. Defaults to 0.
**keywords
Additional keywords can be used to specify other query parameters,
e.g. `relativeorbitnumber=70`.
See https://scihub.copernicus.eu/twiki/do/view/SciHubUserGuide/3FullTextSearch
for a full list.
Range values can be passed as two-element tuples, e.g. `cloudcoverpercentage=(0, 30)`.
`None` can be used in range values for one-sided ranges, e.g. `orbitnumber=(16302, None)`.
Ranges with no bounds (`orbitnumber=(None, None)`) will not be included in the query.
The time interval formats accepted by the `date` parameter can also be used with
any other parameters that expect time intervals (that is: 'beginposition', 'endposition',
'date', 'creationdate', and 'ingestiondate').
Returns
-------
dict[string, dict]
Products returned by the query as a dictionary with the product ID as the key and
the product's attributes (a dictionary) as the value.
"""
query = self.format_query(area, date, raw, area_relation, **keywords)
self.logger.debug("Running query: order_by=%s, limit=%s, offset=%s, query=%s",
order_by, limit, offset, query)
formatted_order_by = _format_order_by(order_by)
response, count = self._load_query(query, formatted_order_by, limit, offset)
self.logger.info("Found %s products", count)
return _parse_opensearch_response(response)
@staticmethod
def format_query(area=None, date=None, raw=None, area_relation='Intersects',
**keywords):
"""Create a OpenSearch API query string.
"""
if area_relation.lower() not in {"intersects", "contains", "iswithin"}:
raise ValueError("Incorrect AOI relation provided ({})".format(area_relation))
# Check for duplicate keywords
kw_lower = set(x.lower() for x in keywords)
if (len(kw_lower) != len(keywords) or
(date is not None and 'beginposition' in kw_lower) or
(area is not None and 'footprint' in kw_lower)):
raise ValueError("Query contains duplicate keywords. Note that query keywords are case-insensitive.")
query_parts = []
if date is not None:
keywords['beginPosition'] = date
for attr, value in sorted(keywords.items()):
# Escape spaces, where appropriate
if isinstance(value, string_types):
value = value.strip()
if not any(value.startswith(s[0]) and value.endswith(s[1]) for s in ['[]', '{}', '//', '()']):
value = re.sub(r'\s', r'\ ', value, re.M)
# Handle date keywords
# Keywords from https://github.com/SentinelDataHub/DataHubSystem/search?q=text/date+iso8601
date_attrs = ['beginposition', 'endposition', 'date', 'creationdate', 'ingestiondate']
if attr.lower() in date_attrs:
# Automatically format date-type attributes
if isinstance(value, string_types) and ' TO ' in value:
# This is a string already formatted as a date interval,
# e.g. '[NOW-1DAY TO NOW]'
pass
elif not isinstance(value, string_types) and len(value) == 2:
value = (format_query_date(value[0]), format_query_date(value[1]))
else:
raise ValueError("Date-type query parameter '{}' expects a two-element tuple "
"of str or datetime objects. Received {}".format(attr, value))
# Handle ranged values
if isinstance(value, (list, tuple)):
# Handle value ranges
if len(value) == 2:
# Allow None to be used as a unlimited bound
value = ['*' if x is None else x for x in value]
if all(x == '*' for x in value):
continue
value = '[{} TO {}]'.format(*value)
else:
raise ValueError("Invalid number of elements in list. Expected 2, received "
"{}".format(len(value)))
query_parts.append('{}:{}'.format(attr, value))
if raw:
query_parts.append(raw)
if area is not None:
query_parts.append('footprint:"{}({})"'.format(area_relation, area))
return ' '.join(query_parts)
def query_raw(self, query, order_by=None, limit=None, offset=0):
"""
Do a full-text query on the OpenSearch API using the format specified in
https://scihub.copernicus.eu/twiki/do/view/SciHubUserGuide/3FullTextSearch
DEPRECATED: use :meth:`query(raw=...) <.query>` instead. This method will be removed in the next major release.
Parameters
----------
query : str
The query string.
order_by: str, optional
A comma-separated list of fields to order by (on server side).
Prefix the field name by '+' or '-' to sort in ascending or descending order, respectively.
Ascending order is used, if prefix is omitted.
Example: "cloudcoverpercentage, -beginposition".
limit: int, optional
Maximum number of products returned. Defaults to no limit.
offset: int, optional
The number of results to skip. Defaults to 0.
Returns
-------
dict[string, dict]
Products returned by the query as a dictionary with the product ID as the key and
the product's attributes (a dictionary) as the value.
"""
warnings.warn(
"query_raw() has been merged with query(). use query(raw=...) instead.",
PendingDeprecationWarning
)
return self.query(raw=query, order_by=order_by, limit=limit, offset=offset)
def count(self, area=None, date=None, raw=None, area_relation='Intersects', **keywords):
"""Get the number of products matching a query.
Accepted parameters are identical to :meth:`SentinelAPI.query()`.
This is a significantly more efficient alternative to doing `len(api.query())`,
which can take minutes to run for queries matching thousands of products.
Returns
-------
int
The number of products matching a query.
"""
for kw in ['order_by', 'limit', 'offset']:
# Allow these function arguments to be included for compatibility with query(),
# but ignore them.
if kw in keywords:
del keywords[kw]
query = self.format_query(area, date, raw, area_relation, **keywords)
_, total_count = self._load_query(query, limit=0)
return total_count
def _load_query(self, query, order_by=None, limit=None, offset=0):
products, count = self._load_subquery(query, order_by, limit, offset)
# repeat query until all results have been loaded
max_offset = count
if limit is not None:
max_offset = min(count, offset + limit)
if max_offset > offset + self.page_size:
progress = self._tqdm(desc="Querying products",
initial=self.page_size,
total=max_offset - offset,
unit=' products')
for new_offset in range(offset + self.page_size, max_offset, self.page_size):
new_limit = limit
if limit is not None:
new_limit = limit - new_offset + offset
ret = self._load_subquery(query, order_by, new_limit, new_offset)[0]
progress.update(len(ret))
products += ret
progress.close()
return products, count
def _load_subquery(self, query, order_by=None, limit=None, offset=0):
# store last query (for testing)
self._last_query = query
self.logger.debug("Sub-query: offset=%s, limit=%s", offset, limit)
# load query results
url = self._format_url(order_by, limit, offset)
response = self.session.post(url, {'q': query}, auth=self.session.auth,
headers={'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'},
timeout=self.timeout)
_check_scihub_response(response)
# store last status code (for testing)
self._last_response = response
# parse response content
try:
json_feed = response.json()['feed']
if json_feed['opensearch:totalResults'] is None:
# We are using some unintended behavior of the server that a null is
# returned as the total results value when the query string was incorrect.
raise SentinelAPIError(
'Invalid query string. Check the parameters and format.', response)
total_results = int(json_feed['opensearch:totalResults'])
except (ValueError, KeyError):
raise SentinelAPIError('API response not valid. JSON decoding failed.', response)
products = json_feed.get('entry', [])
# this verification is necessary because if the query returns only
# one product, self.products will be a dict not a list
if isinstance(products, dict):
products = [products]
return products, total_results
def _format_url(self, order_by=None, limit=None, offset=0):
if limit is None:
limit = self.page_size
limit = min(limit, self.page_size)
url = 'search?format=json&rows={}'.format(limit)
url += '&start={}'.format(offset)
if order_by:
url += '&orderby={}'.format(order_by)
return urljoin(self.api_url, url)
@staticmethod
def to_geojson(products):
"""Return the products from a query response as a GeoJSON with the values in their
appropriate Python types.
"""
feature_list = []
for i, (product_id, props) in enumerate(products.items()):
props = props.copy()
props['id'] = product_id
poly = geomet.wkt.loads(props['footprint'])
del props['footprint']
del props['gmlfootprint']
# Fix "'datetime' is not JSON serializable"
for k, v in props.items():
if isinstance(v, (date, datetime)):
props[k] = v.strftime('%Y-%m-%dT%H:%M:%S.%fZ')
feature_list.append(
geojson.Feature(geometry=poly, id=i, properties=props)
)
return geojson.FeatureCollection(feature_list)
@staticmethod
def to_dataframe(products):
"""Return the products from a query response as a Pandas DataFrame
with the values in their appropriate Python types.
"""
try:
import pandas as pd
except ImportError:
raise ImportError("to_dataframe requires the optional dependency Pandas.")
return pd.DataFrame.from_dict(products, orient='index')
@staticmethod
def to_geodataframe(products):
"""Return the products from a query response as a GeoPandas GeoDataFrame
with the values in their appropriate Python types.
"""
try:
import geopandas as gpd
import shapely.wkt
except ImportError:
raise ImportError("to_geodataframe requires the optional dependencies GeoPandas and Shapely.")
crs = {'init': 'epsg:4326'} # WGS84
if len(products) == 0:
return gpd.GeoDataFrame(crs=crs)
df = SentinelAPI.to_dataframe(products)
geometry = [shapely.wkt.loads(fp) for fp in df['footprint']]
# remove useless columns
df.drop(['footprint', 'gmlfootprint'], axis=1, inplace=True)
return gpd.GeoDataFrame(df, crs=crs, geometry=geometry)
def get_product_odata(self, id, full=False):
"""Access OData API to get info about a product.
Returns a dict containing the id, title, size, md5sum, date, footprint and download url
of the product. The date field corresponds to the Start ContentDate value.
If `full` is set to True, then the full, detailed metadata of the product is returned
in addition to the above.
Parameters
----------
id : string
The UUID of the product to query
full : bool
Whether to get the full metadata for the Product. False by default.
Returns
-------
dict[str, Any]
A dictionary with an item for each metadata attribute
Notes
-----
For a full list of mappings between the OpenSearch (Solr) and OData attribute names
see the following definition files:
https://github.com/SentinelDataHub/DataHubSystem/blob/master/addon/sentinel-1/src/main/resources/META-INF/sentinel-1.owl
https://github.com/SentinelDataHub/DataHubSystem/blob/master/addon/sentinel-2/src/main/resources/META-INF/sentinel-2.owl
https://github.com/SentinelDataHub/DataHubSystem/blob/master/addon/sentinel-3/src/main/resources/META-INF/sentinel-3.owl
"""
url = urljoin(self.api_url, u"odata/v1/Products('{}')?$format=json".format(id))
if full:
url += '&$expand=Attributes'
response = self.session.get(url, auth=self.session.auth,
timeout=self.timeout)
_check_scihub_response(response)
values = _parse_odata_response(response.json()['d'])
return values
def _trigger_offline_retrieval(self, url):
""" Triggers retrieval of an offline product
Trying to download an offline product triggers its retrieval from the long term archive.
The returned HTTP status code conveys whether this was successful.
Parameters
----------
url : string
URL for downloading the product
Notes
-----
https://scihub.copernicus.eu/userguide/LongTermArchive
"""
with self.session.get(url, auth=self.session.auth, timeout=self.timeout) as r:
# check https://scihub.copernicus.eu/userguide/LongTermArchive#HTTP_Status_codes
if r.status_code == 202:
self.logger.info("Accepted for retrieval")
elif r.status_code == 503:
self.logger.error("Request not accepted")
raise SentinelAPILTAError('Request for retrieval from LTA not accepted', r)
elif r.status_code == 403:
self.logger.error("Requests exceed user quota")
raise SentinelAPILTAError('Requests for retrieval from LTA exceed user quota', r)
elif r.status_code == 500:
# should not happen
self.logger.error("Trying to download an offline product")
raise SentinelAPILTAError('Trying to download an offline product', r)
return r.status_code
def download(self, id, directory_path='.', checksum=True):
"""Download a product.
Uses the filename on the server for the downloaded file, e.g.
"S1A_EW_GRDH_1SDH_20141003T003840_20141003T003920_002658_002F54_4DD1.zip".
Incomplete downloads are continued and complete files are skipped.
Parameters
----------
id : string
UUID of the product, e.g. 'a8dd0cfd-613e-45ce-868c-d79177b916ed'
directory_path : string, optional
Where the file will be downloaded
checksum : bool, optional
If True, verify the downloaded file's integrity by checking its MD5 checksum.
Throws InvalidChecksumError if the checksum does not match.
Defaults to True.
Returns
-------
product_info : dict
Dictionary containing the product's info from get_product_info() as well as
the path on disk.
Raises
------
InvalidChecksumError
If the MD5 checksum does not match the checksum on the server.
"""
product_info = self.get_product_odata(id)
path = join(directory_path, product_info['title'] + '.zip')
product_info['path'] = path
product_info['downloaded_bytes'] = 0
self.logger.info('Downloading %s to %s', id, path)
if exists(path):
# We assume that the product has been downloaded and is complete
return product_info
# An incomplete download triggers the retrieval from the LTA if the product is not online
if not product_info['Online']:
self.logger.warning(
'Product %s is not online. Triggering retrieval from long term archive.',
product_info['id'])
self._trigger_offline_retrieval(product_info['url'])
return product_info
# Use a temporary file for downloading
temp_path = path + '.incomplete'
skip_download = False
if exists(temp_path):
if getsize(temp_path) > product_info['size']:
self.logger.warning(
"Existing incomplete file %s is larger than the expected final size"
" (%s vs %s bytes). Deleting it.",
str(temp_path), getsize(temp_path), product_info['size'])
remove(temp_path)
elif getsize(temp_path) == product_info['size']:
if self._md5_compare(temp_path, product_info['md5']):
skip_download = True
else:
# Log a warning since this should never happen
self.logger.warning(
"Existing incomplete file %s appears to be fully downloaded but "
"its checksum is incorrect. Deleting it.",
str(temp_path))
remove(temp_path)
else:
# continue downloading
self.logger.info(
"Download will resume from existing incomplete file %s.", temp_path)
pass
if not skip_download:
# Store the number of downloaded bytes for unit tests
product_info['downloaded_bytes'] = self._download(
product_info['url'], temp_path, self.session, product_info['size'])
# Check integrity with MD5 checksum
if checksum is True:
if not self._md5_compare(temp_path, product_info['md5']):
remove(temp_path)
raise InvalidChecksumError('File corrupt: checksums do not match')
# Download successful, rename the temporary file to its proper name
shutil.move(temp_path, path)
return product_info
def download_all(self, products, directory_path='.', max_attempts=10, checksum=True):
"""Download a list of products.
Takes a list of product IDs as input. This means that the return value of query() can be
passed directly to this method.
File names on the server are used for the downloaded files, e.g.
"S1A_EW_GRDH_1SDH_20141003T003840_20141003T003920_002658_002F54_4DD1.zip".
In case of interruptions or other exceptions, downloading will restart from where it left
off. Downloading is attempted at most max_attempts times to avoid getting stuck with
unrecoverable errors.
Parameters
----------
products : list
List of product IDs
directory_path : string
Directory where the downloaded files will be downloaded
max_attempts : int, optional
Number of allowed retries before giving up downloading a product. Defaults to 10.
checksum : bool, optional
If True, verify the downloaded files' integrity by checking its MD5 checksum.
Throws InvalidChecksumError if the checksum does not match.
Defaults to True.
Raises
------
Raises the most recent downloading exception if all downloads failed.
Returns
-------
dict[string, dict]
A dictionary containing the return value from download() for each successfully
downloaded product.
dict[string, dict]
A dictionary containing the product information for products whose retrieval
from the long term archive was successfully triggered.
set[string]
The list of products that failed to download.
"""
product_ids = list(products)
self.logger.info("Will download %d products", len(product_ids))
return_values = OrderedDict()
last_exception = None
for i, product_id in enumerate(products):
for attempt_num in range(max_attempts):
try:
product_info = self.download(product_id, directory_path, checksum)
return_values[product_id] = product_info
break
except (KeyboardInterrupt, SystemExit):
raise
except InvalidChecksumError as e:
last_exception = e
self.logger.warning(
"Invalid checksum. The downloaded file for '%s' is corrupted.", product_id)
except SentinelAPILTAError as e:
last_exception = e
self.logger.exception("There was an error retrieving %s from the LTA", product_id)
break
except Exception as e:
last_exception = e
self.logger.exception("There was an error downloading %s", product_id)
self.logger.info("%s/%s products downloaded", i + 1, len(product_ids))
failed = set(products) - set(return_values)
# split up sucessfully processed products into downloaded and only triggered retrieval from the LTA
triggered = OrderedDict([(k, v) for k, v in return_values.items() if v['Online'] is False])
downloaded = OrderedDict([(k, v) for k, v in return_values.items() if v['Online'] is True])
if len(failed) == len(product_ids) and last_exception is not None:
raise last_exception
return downloaded, triggered, failed
@staticmethod
@staticmethod
def check_query_length(query):
"""Determine whether a query to the OpenSearch API is too long.
The length of a query string is limited to approximately 3938 characters but
any special characters (that is, not alphanumeric or -_.*) will take up more space.
Parameters
----------
query : str
The query string
Returns
-------
float
Ratio of the query length to the maximum length
"""
# The server uses the Java's URLEncoder implementation internally, which we are replicating here
effective_length = len(quote_plus(query, safe="-_.*").replace('~', '%7E'))
return effective_length / 3938
def _query_names(self, names):
"""Find products by their names, e.g.
S1A_EW_GRDH_1SDH_20141003T003840_20141003T003920_002658_002F54_4DD1.
Note that duplicates exist on server, so multiple products can be returned for each name.
Parameters
----------
names : list[string]
List of product names.
Returns
-------
dict[string, dict[str, dict]]
A dictionary mapping each name to a dictionary which contains the products with
that name (with ID as the key).
"""
def chunks(l, n):
"""Yield successive n-sized chunks from l."""
for i in range(0, len(l), n):
yield l[i:i + n]
products = {}
# 40 names per query fits reasonably well inside the query limit
for chunk in chunks(names, 40):
query = " OR ".join(chunk)
products.update(self.query(raw=query))
# Group the products
output = OrderedDict((name, dict()) for name in names)
for id, metadata in products.items():
name = metadata['identifier']
output[name][id] = metadata
return output
def check_files(self, paths=None, ids=None, directory=None, delete=False):
"""Verify the integrity of product files on disk.
Integrity is checked by comparing the size and checksum of the file with the respective
values on the server.
The input can be a list of products to check or a list of IDs and a directory.
In cases where multiple products with different IDs exist on the server for given product
name, the file is considered to be correct if any of them matches the file size and
checksum. A warning is logged in such situations.
The corrupt products' OData info is included in the return value to make it easier to
re-download the products, if necessary.
Parameters
----------
paths : list[string]
List of product file paths.
ids : list[string]
List of product IDs.
directory : string
Directory where the files are located, if checking based on product IDs.
delete : bool
Whether to delete corrupt products. Defaults to False.
Returns
-------
dict[str, list[dict]]
A dictionary listing the invalid or missing files. The dictionary maps the corrupt
file paths to a list of OData dictionaries of matching products on the server (as
returned by :meth:`SentinelAPI.get_product_odata()`).
"""
if not ids and not paths:
raise ValueError("Must provide either file paths or product IDs and a directory")
if ids and not directory:
raise ValueError("Directory value missing")
paths = paths or []
ids = ids or []
def name_from_path(path):
return splitext(basename(path))[0]
# Get product IDs corresponding to the files on disk
names = []
if paths:
names = list(map(name_from_path, paths))
result = self._query_names(names)
for product_dicts in result.values():
ids += list(product_dicts)
names_from_paths = set(names)
ids = set(ids)
# Collect the OData information for each product
# Product name -> list of matching odata dicts
product_infos = defaultdict(list)
for id in ids:
odata = self.get_product_odata(id)
name = odata['title']
product_infos[name].append(odata)
# Collect
if name not in names_from_paths:
paths.append(join(directory, name + '.zip'))
# Now go over the list of products and check them
corrupt = {}
for path in paths:
name = name_from_path(path)
if len(product_infos[name]) > 1:
self.logger.warning("{} matches multiple products on server".format(path))
if not exists(path):
# We will consider missing files as corrupt also
self.logger.info("{} does not exist on disk".format(path))
corrupt[path] = product_infos[name]
continue
is_fine = False
for product_info in product_infos[name]:
if (getsize(path) == product_info['size'] and
self._md5_compare(path, product_info['md5'])):
is_fine = True
break
if not is_fine:
self.logger.info("{} is corrupt".format(path))
corrupt[path] = product_infos[name]
if delete:
remove(path)
return corrupt
def _md5_compare(self, file_path, checksum, block_size=2 ** 13):
"""Compare a given MD5 checksum with one calculated from a file."""
with closing(self._tqdm(desc="MD5 checksumming", total=getsize(file_path), unit="B",
unit_scale=True)) as progress:
md5 = hashlib.md5()
with open(file_path, "rb") as f:
while True:
block_data = f.read(block_size)
if not block_data:
break
md5.update(block_data)
progress.update(len(block_data))
return md5.hexdigest().lower() == checksum.lower()
def _download(self, url, path, session, file_size):
headers = {}
continuing = exists(path)
if continuing:
already_downloaded_bytes = getsize(path)
headers = {'Range': 'bytes={}-'.format(already_downloaded_bytes)}
else:
already_downloaded_bytes = 0
downloaded_bytes = 0
with closing(session.get(url, stream=True, auth=session.auth,
headers=headers, timeout=self.timeout)) as r, \
closing(self._tqdm(desc="Downloading", total=file_size, unit="B",
unit_scale=True, initial=already_downloaded_bytes)) as progress:
_check_scihub_response(r, test_json=False)
chunk_size = 2 ** 20 # download in 1 MB chunks
mode = 'ab' if continuing else 'wb'
with open(path, mode) as f:
for chunk in r.iter_content(chunk_size=chunk_size):
if chunk: # filter out keep-alive new chunks
f.write(chunk)
progress.update(len(chunk))
downloaded_bytes += len(chunk)
# Return the number of bytes downloaded
return downloaded_bytes
def _tqdm(self, **kwargs):
"""tqdm progressbar wrapper. May be overridden to customize progressbar behavior"""
kwargs.update({'disable': not self.show_progressbars})
return tqdm(**kwargs)
|
sentinelsat/sentinelsat | sentinelsat/sentinel.py | SentinelAPI._query_names | python | def _query_names(self, names):
def chunks(l, n):
"""Yield successive n-sized chunks from l."""
for i in range(0, len(l), n):
yield l[i:i + n]
products = {}
# 40 names per query fits reasonably well inside the query limit
for chunk in chunks(names, 40):
query = " OR ".join(chunk)
products.update(self.query(raw=query))
# Group the products
output = OrderedDict((name, dict()) for name in names)
for id, metadata in products.items():
name = metadata['identifier']
output[name][id] = metadata
return output | Find products by their names, e.g.
S1A_EW_GRDH_1SDH_20141003T003840_20141003T003920_002658_002F54_4DD1.
Note that duplicates exist on server, so multiple products can be returned for each name.
Parameters
----------
names : list[string]
List of product names.
Returns
-------
dict[string, dict[str, dict]]
A dictionary mapping each name to a dictionary which contains the products with
that name (with ID as the key). | train | https://github.com/sentinelsat/sentinelsat/blob/eacfd79ff4e7e939147db9dfdd393c67d64eecaa/sentinelsat/sentinel.py#L665-L700 | null | class SentinelAPI:
"""Class to connect to Copernicus Open Access Hub, search and download imagery.
Parameters
----------
user : string
username for DataHub
set to None to use ~/.netrc
password : string
password for DataHub
set to None to use ~/.netrc
api_url : string, optional
URL of the DataHub
defaults to 'https://scihub.copernicus.eu/apihub'
show_progressbars : bool
Whether progressbars should be shown or not, e.g. during download. Defaults to True.
timeout : float or tuple, optional
How long to wait for DataHub response (in seconds).
Tuple (connect, read) allowed.
Attributes
----------
session : requests.Session
Session to connect to DataHub
api_url : str
URL to the DataHub
page_size : int
Number of results per query page.
Current value: 100 (maximum allowed on ApiHub)
timeout : float or tuple
How long to wait for DataHub response (in seconds).
"""
logger = logging.getLogger('sentinelsat.SentinelAPI')
def __init__(self, user, password, api_url='https://scihub.copernicus.eu/apihub/',
show_progressbars=True, timeout=None):
self.session = requests.Session()
if user and password:
self.session.auth = (user, password)
self.api_url = api_url if api_url.endswith('/') else api_url + '/'
self.page_size = 100
self.user_agent = 'sentinelsat/' + sentinelsat_version
self.session.headers['User-Agent'] = self.user_agent
self.show_progressbars = show_progressbars
self.timeout = timeout
# For unit tests
self._last_query = None
self._last_response = None
def query(self, area=None, date=None, raw=None, area_relation='Intersects',
order_by=None, limit=None, offset=0, **keywords):
"""Query the OpenSearch API with the coordinates of an area, a date interval
and any other search keywords accepted by the API.
Parameters
----------
area : str, optional
The area of interest formatted as a Well-Known Text string.
date : tuple of (str or datetime) or str, optional
A time interval filter based on the Sensing Start Time of the products.
Expects a tuple of (start, end), e.g. ("NOW-1DAY", "NOW").
The timestamps can be either a Python datetime or a string in one of the
following formats:
- yyyyMMdd
- yyyy-MM-ddThh:mm:ss.SSSZ (ISO-8601)
- yyyy-MM-ddThh:mm:ssZ
- NOW
- NOW-<n>DAY(S) (or HOUR(S), MONTH(S), etc.)
- NOW+<n>DAY(S)
- yyyy-MM-ddThh:mm:ssZ-<n>DAY(S)
- NOW/DAY (or HOUR, MONTH etc.) - rounds the value to the given unit
Alternatively, an already fully formatted string such as "[NOW-1DAY TO NOW]" can be
used as well.
raw : str, optional
Additional query text that will be appended to the query.
area_relation : {'Intersects', 'Contains', 'IsWithin'}, optional
What relation to use for testing the AOI. Case insensitive.
- Intersects: true if the AOI and the footprint intersect (default)
- Contains: true if the AOI is inside the footprint
- IsWithin: true if the footprint is inside the AOI
order_by: str, optional
A comma-separated list of fields to order by (on server side).
Prefix the field name by '+' or '-' to sort in ascending or descending order,
respectively. Ascending order is used if prefix is omitted.
Example: "cloudcoverpercentage, -beginposition".
limit: int, optional
Maximum number of products returned. Defaults to no limit.
offset: int, optional
The number of results to skip. Defaults to 0.
**keywords
Additional keywords can be used to specify other query parameters,
e.g. `relativeorbitnumber=70`.
See https://scihub.copernicus.eu/twiki/do/view/SciHubUserGuide/3FullTextSearch
for a full list.
Range values can be passed as two-element tuples, e.g. `cloudcoverpercentage=(0, 30)`.
`None` can be used in range values for one-sided ranges, e.g. `orbitnumber=(16302, None)`.
Ranges with no bounds (`orbitnumber=(None, None)`) will not be included in the query.
The time interval formats accepted by the `date` parameter can also be used with
any other parameters that expect time intervals (that is: 'beginposition', 'endposition',
'date', 'creationdate', and 'ingestiondate').
Returns
-------
dict[string, dict]
Products returned by the query as a dictionary with the product ID as the key and
the product's attributes (a dictionary) as the value.
"""
query = self.format_query(area, date, raw, area_relation, **keywords)
self.logger.debug("Running query: order_by=%s, limit=%s, offset=%s, query=%s",
order_by, limit, offset, query)
formatted_order_by = _format_order_by(order_by)
response, count = self._load_query(query, formatted_order_by, limit, offset)
self.logger.info("Found %s products", count)
return _parse_opensearch_response(response)
@staticmethod
def format_query(area=None, date=None, raw=None, area_relation='Intersects',
**keywords):
"""Create a OpenSearch API query string.
"""
if area_relation.lower() not in {"intersects", "contains", "iswithin"}:
raise ValueError("Incorrect AOI relation provided ({})".format(area_relation))
# Check for duplicate keywords
kw_lower = set(x.lower() for x in keywords)
if (len(kw_lower) != len(keywords) or
(date is not None and 'beginposition' in kw_lower) or
(area is not None and 'footprint' in kw_lower)):
raise ValueError("Query contains duplicate keywords. Note that query keywords are case-insensitive.")
query_parts = []
if date is not None:
keywords['beginPosition'] = date
for attr, value in sorted(keywords.items()):
# Escape spaces, where appropriate
if isinstance(value, string_types):
value = value.strip()
if not any(value.startswith(s[0]) and value.endswith(s[1]) for s in ['[]', '{}', '//', '()']):
value = re.sub(r'\s', r'\ ', value, re.M)
# Handle date keywords
# Keywords from https://github.com/SentinelDataHub/DataHubSystem/search?q=text/date+iso8601
date_attrs = ['beginposition', 'endposition', 'date', 'creationdate', 'ingestiondate']
if attr.lower() in date_attrs:
# Automatically format date-type attributes
if isinstance(value, string_types) and ' TO ' in value:
# This is a string already formatted as a date interval,
# e.g. '[NOW-1DAY TO NOW]'
pass
elif not isinstance(value, string_types) and len(value) == 2:
value = (format_query_date(value[0]), format_query_date(value[1]))
else:
raise ValueError("Date-type query parameter '{}' expects a two-element tuple "
"of str or datetime objects. Received {}".format(attr, value))
# Handle ranged values
if isinstance(value, (list, tuple)):
# Handle value ranges
if len(value) == 2:
# Allow None to be used as a unlimited bound
value = ['*' if x is None else x for x in value]
if all(x == '*' for x in value):
continue
value = '[{} TO {}]'.format(*value)
else:
raise ValueError("Invalid number of elements in list. Expected 2, received "
"{}".format(len(value)))
query_parts.append('{}:{}'.format(attr, value))
if raw:
query_parts.append(raw)
if area is not None:
query_parts.append('footprint:"{}({})"'.format(area_relation, area))
return ' '.join(query_parts)
def query_raw(self, query, order_by=None, limit=None, offset=0):
"""
Do a full-text query on the OpenSearch API using the format specified in
https://scihub.copernicus.eu/twiki/do/view/SciHubUserGuide/3FullTextSearch
DEPRECATED: use :meth:`query(raw=...) <.query>` instead. This method will be removed in the next major release.
Parameters
----------
query : str
The query string.
order_by: str, optional
A comma-separated list of fields to order by (on server side).
Prefix the field name by '+' or '-' to sort in ascending or descending order, respectively.
Ascending order is used, if prefix is omitted.
Example: "cloudcoverpercentage, -beginposition".
limit: int, optional
Maximum number of products returned. Defaults to no limit.
offset: int, optional
The number of results to skip. Defaults to 0.
Returns
-------
dict[string, dict]
Products returned by the query as a dictionary with the product ID as the key and
the product's attributes (a dictionary) as the value.
"""
warnings.warn(
"query_raw() has been merged with query(). use query(raw=...) instead.",
PendingDeprecationWarning
)
return self.query(raw=query, order_by=order_by, limit=limit, offset=offset)
def count(self, area=None, date=None, raw=None, area_relation='Intersects', **keywords):
"""Get the number of products matching a query.
Accepted parameters are identical to :meth:`SentinelAPI.query()`.
This is a significantly more efficient alternative to doing `len(api.query())`,
which can take minutes to run for queries matching thousands of products.
Returns
-------
int
The number of products matching a query.
"""
for kw in ['order_by', 'limit', 'offset']:
# Allow these function arguments to be included for compatibility with query(),
# but ignore them.
if kw in keywords:
del keywords[kw]
query = self.format_query(area, date, raw, area_relation, **keywords)
_, total_count = self._load_query(query, limit=0)
return total_count
def _load_query(self, query, order_by=None, limit=None, offset=0):
products, count = self._load_subquery(query, order_by, limit, offset)
# repeat query until all results have been loaded
max_offset = count
if limit is not None:
max_offset = min(count, offset + limit)
if max_offset > offset + self.page_size:
progress = self._tqdm(desc="Querying products",
initial=self.page_size,
total=max_offset - offset,
unit=' products')
for new_offset in range(offset + self.page_size, max_offset, self.page_size):
new_limit = limit
if limit is not None:
new_limit = limit - new_offset + offset
ret = self._load_subquery(query, order_by, new_limit, new_offset)[0]
progress.update(len(ret))
products += ret
progress.close()
return products, count
def _load_subquery(self, query, order_by=None, limit=None, offset=0):
# store last query (for testing)
self._last_query = query
self.logger.debug("Sub-query: offset=%s, limit=%s", offset, limit)
# load query results
url = self._format_url(order_by, limit, offset)
response = self.session.post(url, {'q': query}, auth=self.session.auth,
headers={'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'},
timeout=self.timeout)
_check_scihub_response(response)
# store last status code (for testing)
self._last_response = response
# parse response content
try:
json_feed = response.json()['feed']
if json_feed['opensearch:totalResults'] is None:
# We are using some unintended behavior of the server that a null is
# returned as the total results value when the query string was incorrect.
raise SentinelAPIError(
'Invalid query string. Check the parameters and format.', response)
total_results = int(json_feed['opensearch:totalResults'])
except (ValueError, KeyError):
raise SentinelAPIError('API response not valid. JSON decoding failed.', response)
products = json_feed.get('entry', [])
# this verification is necessary because if the query returns only
# one product, self.products will be a dict not a list
if isinstance(products, dict):
products = [products]
return products, total_results
def _format_url(self, order_by=None, limit=None, offset=0):
if limit is None:
limit = self.page_size
limit = min(limit, self.page_size)
url = 'search?format=json&rows={}'.format(limit)
url += '&start={}'.format(offset)
if order_by:
url += '&orderby={}'.format(order_by)
return urljoin(self.api_url, url)
@staticmethod
def to_geojson(products):
"""Return the products from a query response as a GeoJSON with the values in their
appropriate Python types.
"""
feature_list = []
for i, (product_id, props) in enumerate(products.items()):
props = props.copy()
props['id'] = product_id
poly = geomet.wkt.loads(props['footprint'])
del props['footprint']
del props['gmlfootprint']
# Fix "'datetime' is not JSON serializable"
for k, v in props.items():
if isinstance(v, (date, datetime)):
props[k] = v.strftime('%Y-%m-%dT%H:%M:%S.%fZ')
feature_list.append(
geojson.Feature(geometry=poly, id=i, properties=props)
)
return geojson.FeatureCollection(feature_list)
@staticmethod
def to_dataframe(products):
"""Return the products from a query response as a Pandas DataFrame
with the values in their appropriate Python types.
"""
try:
import pandas as pd
except ImportError:
raise ImportError("to_dataframe requires the optional dependency Pandas.")
return pd.DataFrame.from_dict(products, orient='index')
@staticmethod
def to_geodataframe(products):
"""Return the products from a query response as a GeoPandas GeoDataFrame
with the values in their appropriate Python types.
"""
try:
import geopandas as gpd
import shapely.wkt
except ImportError:
raise ImportError("to_geodataframe requires the optional dependencies GeoPandas and Shapely.")
crs = {'init': 'epsg:4326'} # WGS84
if len(products) == 0:
return gpd.GeoDataFrame(crs=crs)
df = SentinelAPI.to_dataframe(products)
geometry = [shapely.wkt.loads(fp) for fp in df['footprint']]
# remove useless columns
df.drop(['footprint', 'gmlfootprint'], axis=1, inplace=True)
return gpd.GeoDataFrame(df, crs=crs, geometry=geometry)
def get_product_odata(self, id, full=False):
"""Access OData API to get info about a product.
Returns a dict containing the id, title, size, md5sum, date, footprint and download url
of the product. The date field corresponds to the Start ContentDate value.
If `full` is set to True, then the full, detailed metadata of the product is returned
in addition to the above.
Parameters
----------
id : string
The UUID of the product to query
full : bool
Whether to get the full metadata for the Product. False by default.
Returns
-------
dict[str, Any]
A dictionary with an item for each metadata attribute
Notes
-----
For a full list of mappings between the OpenSearch (Solr) and OData attribute names
see the following definition files:
https://github.com/SentinelDataHub/DataHubSystem/blob/master/addon/sentinel-1/src/main/resources/META-INF/sentinel-1.owl
https://github.com/SentinelDataHub/DataHubSystem/blob/master/addon/sentinel-2/src/main/resources/META-INF/sentinel-2.owl
https://github.com/SentinelDataHub/DataHubSystem/blob/master/addon/sentinel-3/src/main/resources/META-INF/sentinel-3.owl
"""
url = urljoin(self.api_url, u"odata/v1/Products('{}')?$format=json".format(id))
if full:
url += '&$expand=Attributes'
response = self.session.get(url, auth=self.session.auth,
timeout=self.timeout)
_check_scihub_response(response)
values = _parse_odata_response(response.json()['d'])
return values
def _trigger_offline_retrieval(self, url):
""" Triggers retrieval of an offline product
Trying to download an offline product triggers its retrieval from the long term archive.
The returned HTTP status code conveys whether this was successful.
Parameters
----------
url : string
URL for downloading the product
Notes
-----
https://scihub.copernicus.eu/userguide/LongTermArchive
"""
with self.session.get(url, auth=self.session.auth, timeout=self.timeout) as r:
# check https://scihub.copernicus.eu/userguide/LongTermArchive#HTTP_Status_codes
if r.status_code == 202:
self.logger.info("Accepted for retrieval")
elif r.status_code == 503:
self.logger.error("Request not accepted")
raise SentinelAPILTAError('Request for retrieval from LTA not accepted', r)
elif r.status_code == 403:
self.logger.error("Requests exceed user quota")
raise SentinelAPILTAError('Requests for retrieval from LTA exceed user quota', r)
elif r.status_code == 500:
# should not happen
self.logger.error("Trying to download an offline product")
raise SentinelAPILTAError('Trying to download an offline product', r)
return r.status_code
def download(self, id, directory_path='.', checksum=True):
"""Download a product.
Uses the filename on the server for the downloaded file, e.g.
"S1A_EW_GRDH_1SDH_20141003T003840_20141003T003920_002658_002F54_4DD1.zip".
Incomplete downloads are continued and complete files are skipped.
Parameters
----------
id : string
UUID of the product, e.g. 'a8dd0cfd-613e-45ce-868c-d79177b916ed'
directory_path : string, optional
Where the file will be downloaded
checksum : bool, optional
If True, verify the downloaded file's integrity by checking its MD5 checksum.
Throws InvalidChecksumError if the checksum does not match.
Defaults to True.
Returns
-------
product_info : dict
Dictionary containing the product's info from get_product_info() as well as
the path on disk.
Raises
------
InvalidChecksumError
If the MD5 checksum does not match the checksum on the server.
"""
product_info = self.get_product_odata(id)
path = join(directory_path, product_info['title'] + '.zip')
product_info['path'] = path
product_info['downloaded_bytes'] = 0
self.logger.info('Downloading %s to %s', id, path)
if exists(path):
# We assume that the product has been downloaded and is complete
return product_info
# An incomplete download triggers the retrieval from the LTA if the product is not online
if not product_info['Online']:
self.logger.warning(
'Product %s is not online. Triggering retrieval from long term archive.',
product_info['id'])
self._trigger_offline_retrieval(product_info['url'])
return product_info
# Use a temporary file for downloading
temp_path = path + '.incomplete'
skip_download = False
if exists(temp_path):
if getsize(temp_path) > product_info['size']:
self.logger.warning(
"Existing incomplete file %s is larger than the expected final size"
" (%s vs %s bytes). Deleting it.",
str(temp_path), getsize(temp_path), product_info['size'])
remove(temp_path)
elif getsize(temp_path) == product_info['size']:
if self._md5_compare(temp_path, product_info['md5']):
skip_download = True
else:
# Log a warning since this should never happen
self.logger.warning(
"Existing incomplete file %s appears to be fully downloaded but "
"its checksum is incorrect. Deleting it.",
str(temp_path))
remove(temp_path)
else:
# continue downloading
self.logger.info(
"Download will resume from existing incomplete file %s.", temp_path)
pass
if not skip_download:
# Store the number of downloaded bytes for unit tests
product_info['downloaded_bytes'] = self._download(
product_info['url'], temp_path, self.session, product_info['size'])
# Check integrity with MD5 checksum
if checksum is True:
if not self._md5_compare(temp_path, product_info['md5']):
remove(temp_path)
raise InvalidChecksumError('File corrupt: checksums do not match')
# Download successful, rename the temporary file to its proper name
shutil.move(temp_path, path)
return product_info
def download_all(self, products, directory_path='.', max_attempts=10, checksum=True):
"""Download a list of products.
Takes a list of product IDs as input. This means that the return value of query() can be
passed directly to this method.
File names on the server are used for the downloaded files, e.g.
"S1A_EW_GRDH_1SDH_20141003T003840_20141003T003920_002658_002F54_4DD1.zip".
In case of interruptions or other exceptions, downloading will restart from where it left
off. Downloading is attempted at most max_attempts times to avoid getting stuck with
unrecoverable errors.
Parameters
----------
products : list
List of product IDs
directory_path : string
Directory where the downloaded files will be downloaded
max_attempts : int, optional
Number of allowed retries before giving up downloading a product. Defaults to 10.
checksum : bool, optional
If True, verify the downloaded files' integrity by checking its MD5 checksum.
Throws InvalidChecksumError if the checksum does not match.
Defaults to True.
Raises
------
Raises the most recent downloading exception if all downloads failed.
Returns
-------
dict[string, dict]
A dictionary containing the return value from download() for each successfully
downloaded product.
dict[string, dict]
A dictionary containing the product information for products whose retrieval
from the long term archive was successfully triggered.
set[string]
The list of products that failed to download.
"""
product_ids = list(products)
self.logger.info("Will download %d products", len(product_ids))
return_values = OrderedDict()
last_exception = None
for i, product_id in enumerate(products):
for attempt_num in range(max_attempts):
try:
product_info = self.download(product_id, directory_path, checksum)
return_values[product_id] = product_info
break
except (KeyboardInterrupt, SystemExit):
raise
except InvalidChecksumError as e:
last_exception = e
self.logger.warning(
"Invalid checksum. The downloaded file for '%s' is corrupted.", product_id)
except SentinelAPILTAError as e:
last_exception = e
self.logger.exception("There was an error retrieving %s from the LTA", product_id)
break
except Exception as e:
last_exception = e
self.logger.exception("There was an error downloading %s", product_id)
self.logger.info("%s/%s products downloaded", i + 1, len(product_ids))
failed = set(products) - set(return_values)
# split up sucessfully processed products into downloaded and only triggered retrieval from the LTA
triggered = OrderedDict([(k, v) for k, v in return_values.items() if v['Online'] is False])
downloaded = OrderedDict([(k, v) for k, v in return_values.items() if v['Online'] is True])
if len(failed) == len(product_ids) and last_exception is not None:
raise last_exception
return downloaded, triggered, failed
@staticmethod
def get_products_size(products):
"""Return the total file size in GB of all products in the OpenSearch response."""
size_total = 0
for title, props in products.items():
size_product = props["size"]
size_value = float(size_product.split(" ")[0])
size_unit = str(size_product.split(" ")[1])
if size_unit == "MB":
size_value /= 1024.
if size_unit == "KB":
size_value /= 1024. * 1024.
size_total += size_value
return round(size_total, 2)
@staticmethod
def check_query_length(query):
"""Determine whether a query to the OpenSearch API is too long.
The length of a query string is limited to approximately 3938 characters but
any special characters (that is, not alphanumeric or -_.*) will take up more space.
Parameters
----------
query : str
The query string
Returns
-------
float
Ratio of the query length to the maximum length
"""
# The server uses the Java's URLEncoder implementation internally, which we are replicating here
effective_length = len(quote_plus(query, safe="-_.*").replace('~', '%7E'))
return effective_length / 3938
def check_files(self, paths=None, ids=None, directory=None, delete=False):
"""Verify the integrity of product files on disk.
Integrity is checked by comparing the size and checksum of the file with the respective
values on the server.
The input can be a list of products to check or a list of IDs and a directory.
In cases where multiple products with different IDs exist on the server for given product
name, the file is considered to be correct if any of them matches the file size and
checksum. A warning is logged in such situations.
The corrupt products' OData info is included in the return value to make it easier to
re-download the products, if necessary.
Parameters
----------
paths : list[string]
List of product file paths.
ids : list[string]
List of product IDs.
directory : string
Directory where the files are located, if checking based on product IDs.
delete : bool
Whether to delete corrupt products. Defaults to False.
Returns
-------
dict[str, list[dict]]
A dictionary listing the invalid or missing files. The dictionary maps the corrupt
file paths to a list of OData dictionaries of matching products on the server (as
returned by :meth:`SentinelAPI.get_product_odata()`).
"""
if not ids and not paths:
raise ValueError("Must provide either file paths or product IDs and a directory")
if ids and not directory:
raise ValueError("Directory value missing")
paths = paths or []
ids = ids or []
def name_from_path(path):
return splitext(basename(path))[0]
# Get product IDs corresponding to the files on disk
names = []
if paths:
names = list(map(name_from_path, paths))
result = self._query_names(names)
for product_dicts in result.values():
ids += list(product_dicts)
names_from_paths = set(names)
ids = set(ids)
# Collect the OData information for each product
# Product name -> list of matching odata dicts
product_infos = defaultdict(list)
for id in ids:
odata = self.get_product_odata(id)
name = odata['title']
product_infos[name].append(odata)
# Collect
if name not in names_from_paths:
paths.append(join(directory, name + '.zip'))
# Now go over the list of products and check them
corrupt = {}
for path in paths:
name = name_from_path(path)
if len(product_infos[name]) > 1:
self.logger.warning("{} matches multiple products on server".format(path))
if not exists(path):
# We will consider missing files as corrupt also
self.logger.info("{} does not exist on disk".format(path))
corrupt[path] = product_infos[name]
continue
is_fine = False
for product_info in product_infos[name]:
if (getsize(path) == product_info['size'] and
self._md5_compare(path, product_info['md5'])):
is_fine = True
break
if not is_fine:
self.logger.info("{} is corrupt".format(path))
corrupt[path] = product_infos[name]
if delete:
remove(path)
return corrupt
def _md5_compare(self, file_path, checksum, block_size=2 ** 13):
"""Compare a given MD5 checksum with one calculated from a file."""
with closing(self._tqdm(desc="MD5 checksumming", total=getsize(file_path), unit="B",
unit_scale=True)) as progress:
md5 = hashlib.md5()
with open(file_path, "rb") as f:
while True:
block_data = f.read(block_size)
if not block_data:
break
md5.update(block_data)
progress.update(len(block_data))
return md5.hexdigest().lower() == checksum.lower()
def _download(self, url, path, session, file_size):
headers = {}
continuing = exists(path)
if continuing:
already_downloaded_bytes = getsize(path)
headers = {'Range': 'bytes={}-'.format(already_downloaded_bytes)}
else:
already_downloaded_bytes = 0
downloaded_bytes = 0
with closing(session.get(url, stream=True, auth=session.auth,
headers=headers, timeout=self.timeout)) as r, \
closing(self._tqdm(desc="Downloading", total=file_size, unit="B",
unit_scale=True, initial=already_downloaded_bytes)) as progress:
_check_scihub_response(r, test_json=False)
chunk_size = 2 ** 20 # download in 1 MB chunks
mode = 'ab' if continuing else 'wb'
with open(path, mode) as f:
for chunk in r.iter_content(chunk_size=chunk_size):
if chunk: # filter out keep-alive new chunks
f.write(chunk)
progress.update(len(chunk))
downloaded_bytes += len(chunk)
# Return the number of bytes downloaded
return downloaded_bytes
def _tqdm(self, **kwargs):
"""tqdm progressbar wrapper. May be overridden to customize progressbar behavior"""
kwargs.update({'disable': not self.show_progressbars})
return tqdm(**kwargs)
|
sentinelsat/sentinelsat | sentinelsat/sentinel.py | SentinelAPI.check_files | python | def check_files(self, paths=None, ids=None, directory=None, delete=False):
if not ids and not paths:
raise ValueError("Must provide either file paths or product IDs and a directory")
if ids and not directory:
raise ValueError("Directory value missing")
paths = paths or []
ids = ids or []
def name_from_path(path):
return splitext(basename(path))[0]
# Get product IDs corresponding to the files on disk
names = []
if paths:
names = list(map(name_from_path, paths))
result = self._query_names(names)
for product_dicts in result.values():
ids += list(product_dicts)
names_from_paths = set(names)
ids = set(ids)
# Collect the OData information for each product
# Product name -> list of matching odata dicts
product_infos = defaultdict(list)
for id in ids:
odata = self.get_product_odata(id)
name = odata['title']
product_infos[name].append(odata)
# Collect
if name not in names_from_paths:
paths.append(join(directory, name + '.zip'))
# Now go over the list of products and check them
corrupt = {}
for path in paths:
name = name_from_path(path)
if len(product_infos[name]) > 1:
self.logger.warning("{} matches multiple products on server".format(path))
if not exists(path):
# We will consider missing files as corrupt also
self.logger.info("{} does not exist on disk".format(path))
corrupt[path] = product_infos[name]
continue
is_fine = False
for product_info in product_infos[name]:
if (getsize(path) == product_info['size'] and
self._md5_compare(path, product_info['md5'])):
is_fine = True
break
if not is_fine:
self.logger.info("{} is corrupt".format(path))
corrupt[path] = product_infos[name]
if delete:
remove(path)
return corrupt | Verify the integrity of product files on disk.
Integrity is checked by comparing the size and checksum of the file with the respective
values on the server.
The input can be a list of products to check or a list of IDs and a directory.
In cases where multiple products with different IDs exist on the server for given product
name, the file is considered to be correct if any of them matches the file size and
checksum. A warning is logged in such situations.
The corrupt products' OData info is included in the return value to make it easier to
re-download the products, if necessary.
Parameters
----------
paths : list[string]
List of product file paths.
ids : list[string]
List of product IDs.
directory : string
Directory where the files are located, if checking based on product IDs.
delete : bool
Whether to delete corrupt products. Defaults to False.
Returns
-------
dict[str, list[dict]]
A dictionary listing the invalid or missing files. The dictionary maps the corrupt
file paths to a list of OData dictionaries of matching products on the server (as
returned by :meth:`SentinelAPI.get_product_odata()`). | train | https://github.com/sentinelsat/sentinelsat/blob/eacfd79ff4e7e939147db9dfdd393c67d64eecaa/sentinelsat/sentinel.py#L702-L793 | null | class SentinelAPI:
"""Class to connect to Copernicus Open Access Hub, search and download imagery.
Parameters
----------
user : string
username for DataHub
set to None to use ~/.netrc
password : string
password for DataHub
set to None to use ~/.netrc
api_url : string, optional
URL of the DataHub
defaults to 'https://scihub.copernicus.eu/apihub'
show_progressbars : bool
Whether progressbars should be shown or not, e.g. during download. Defaults to True.
timeout : float or tuple, optional
How long to wait for DataHub response (in seconds).
Tuple (connect, read) allowed.
Attributes
----------
session : requests.Session
Session to connect to DataHub
api_url : str
URL to the DataHub
page_size : int
Number of results per query page.
Current value: 100 (maximum allowed on ApiHub)
timeout : float or tuple
How long to wait for DataHub response (in seconds).
"""
logger = logging.getLogger('sentinelsat.SentinelAPI')
def __init__(self, user, password, api_url='https://scihub.copernicus.eu/apihub/',
show_progressbars=True, timeout=None):
self.session = requests.Session()
if user and password:
self.session.auth = (user, password)
self.api_url = api_url if api_url.endswith('/') else api_url + '/'
self.page_size = 100
self.user_agent = 'sentinelsat/' + sentinelsat_version
self.session.headers['User-Agent'] = self.user_agent
self.show_progressbars = show_progressbars
self.timeout = timeout
# For unit tests
self._last_query = None
self._last_response = None
def query(self, area=None, date=None, raw=None, area_relation='Intersects',
order_by=None, limit=None, offset=0, **keywords):
"""Query the OpenSearch API with the coordinates of an area, a date interval
and any other search keywords accepted by the API.
Parameters
----------
area : str, optional
The area of interest formatted as a Well-Known Text string.
date : tuple of (str or datetime) or str, optional
A time interval filter based on the Sensing Start Time of the products.
Expects a tuple of (start, end), e.g. ("NOW-1DAY", "NOW").
The timestamps can be either a Python datetime or a string in one of the
following formats:
- yyyyMMdd
- yyyy-MM-ddThh:mm:ss.SSSZ (ISO-8601)
- yyyy-MM-ddThh:mm:ssZ
- NOW
- NOW-<n>DAY(S) (or HOUR(S), MONTH(S), etc.)
- NOW+<n>DAY(S)
- yyyy-MM-ddThh:mm:ssZ-<n>DAY(S)
- NOW/DAY (or HOUR, MONTH etc.) - rounds the value to the given unit
Alternatively, an already fully formatted string such as "[NOW-1DAY TO NOW]" can be
used as well.
raw : str, optional
Additional query text that will be appended to the query.
area_relation : {'Intersects', 'Contains', 'IsWithin'}, optional
What relation to use for testing the AOI. Case insensitive.
- Intersects: true if the AOI and the footprint intersect (default)
- Contains: true if the AOI is inside the footprint
- IsWithin: true if the footprint is inside the AOI
order_by: str, optional
A comma-separated list of fields to order by (on server side).
Prefix the field name by '+' or '-' to sort in ascending or descending order,
respectively. Ascending order is used if prefix is omitted.
Example: "cloudcoverpercentage, -beginposition".
limit: int, optional
Maximum number of products returned. Defaults to no limit.
offset: int, optional
The number of results to skip. Defaults to 0.
**keywords
Additional keywords can be used to specify other query parameters,
e.g. `relativeorbitnumber=70`.
See https://scihub.copernicus.eu/twiki/do/view/SciHubUserGuide/3FullTextSearch
for a full list.
Range values can be passed as two-element tuples, e.g. `cloudcoverpercentage=(0, 30)`.
`None` can be used in range values for one-sided ranges, e.g. `orbitnumber=(16302, None)`.
Ranges with no bounds (`orbitnumber=(None, None)`) will not be included in the query.
The time interval formats accepted by the `date` parameter can also be used with
any other parameters that expect time intervals (that is: 'beginposition', 'endposition',
'date', 'creationdate', and 'ingestiondate').
Returns
-------
dict[string, dict]
Products returned by the query as a dictionary with the product ID as the key and
the product's attributes (a dictionary) as the value.
"""
query = self.format_query(area, date, raw, area_relation, **keywords)
self.logger.debug("Running query: order_by=%s, limit=%s, offset=%s, query=%s",
order_by, limit, offset, query)
formatted_order_by = _format_order_by(order_by)
response, count = self._load_query(query, formatted_order_by, limit, offset)
self.logger.info("Found %s products", count)
return _parse_opensearch_response(response)
@staticmethod
def format_query(area=None, date=None, raw=None, area_relation='Intersects',
**keywords):
"""Create a OpenSearch API query string.
"""
if area_relation.lower() not in {"intersects", "contains", "iswithin"}:
raise ValueError("Incorrect AOI relation provided ({})".format(area_relation))
# Check for duplicate keywords
kw_lower = set(x.lower() for x in keywords)
if (len(kw_lower) != len(keywords) or
(date is not None and 'beginposition' in kw_lower) or
(area is not None and 'footprint' in kw_lower)):
raise ValueError("Query contains duplicate keywords. Note that query keywords are case-insensitive.")
query_parts = []
if date is not None:
keywords['beginPosition'] = date
for attr, value in sorted(keywords.items()):
# Escape spaces, where appropriate
if isinstance(value, string_types):
value = value.strip()
if not any(value.startswith(s[0]) and value.endswith(s[1]) for s in ['[]', '{}', '//', '()']):
value = re.sub(r'\s', r'\ ', value, re.M)
# Handle date keywords
# Keywords from https://github.com/SentinelDataHub/DataHubSystem/search?q=text/date+iso8601
date_attrs = ['beginposition', 'endposition', 'date', 'creationdate', 'ingestiondate']
if attr.lower() in date_attrs:
# Automatically format date-type attributes
if isinstance(value, string_types) and ' TO ' in value:
# This is a string already formatted as a date interval,
# e.g. '[NOW-1DAY TO NOW]'
pass
elif not isinstance(value, string_types) and len(value) == 2:
value = (format_query_date(value[0]), format_query_date(value[1]))
else:
raise ValueError("Date-type query parameter '{}' expects a two-element tuple "
"of str or datetime objects. Received {}".format(attr, value))
# Handle ranged values
if isinstance(value, (list, tuple)):
# Handle value ranges
if len(value) == 2:
# Allow None to be used as a unlimited bound
value = ['*' if x is None else x for x in value]
if all(x == '*' for x in value):
continue
value = '[{} TO {}]'.format(*value)
else:
raise ValueError("Invalid number of elements in list. Expected 2, received "
"{}".format(len(value)))
query_parts.append('{}:{}'.format(attr, value))
if raw:
query_parts.append(raw)
if area is not None:
query_parts.append('footprint:"{}({})"'.format(area_relation, area))
return ' '.join(query_parts)
def query_raw(self, query, order_by=None, limit=None, offset=0):
"""
Do a full-text query on the OpenSearch API using the format specified in
https://scihub.copernicus.eu/twiki/do/view/SciHubUserGuide/3FullTextSearch
DEPRECATED: use :meth:`query(raw=...) <.query>` instead. This method will be removed in the next major release.
Parameters
----------
query : str
The query string.
order_by: str, optional
A comma-separated list of fields to order by (on server side).
Prefix the field name by '+' or '-' to sort in ascending or descending order, respectively.
Ascending order is used, if prefix is omitted.
Example: "cloudcoverpercentage, -beginposition".
limit: int, optional
Maximum number of products returned. Defaults to no limit.
offset: int, optional
The number of results to skip. Defaults to 0.
Returns
-------
dict[string, dict]
Products returned by the query as a dictionary with the product ID as the key and
the product's attributes (a dictionary) as the value.
"""
warnings.warn(
"query_raw() has been merged with query(). use query(raw=...) instead.",
PendingDeprecationWarning
)
return self.query(raw=query, order_by=order_by, limit=limit, offset=offset)
def count(self, area=None, date=None, raw=None, area_relation='Intersects', **keywords):
"""Get the number of products matching a query.
Accepted parameters are identical to :meth:`SentinelAPI.query()`.
This is a significantly more efficient alternative to doing `len(api.query())`,
which can take minutes to run for queries matching thousands of products.
Returns
-------
int
The number of products matching a query.
"""
for kw in ['order_by', 'limit', 'offset']:
# Allow these function arguments to be included for compatibility with query(),
# but ignore them.
if kw in keywords:
del keywords[kw]
query = self.format_query(area, date, raw, area_relation, **keywords)
_, total_count = self._load_query(query, limit=0)
return total_count
def _load_query(self, query, order_by=None, limit=None, offset=0):
products, count = self._load_subquery(query, order_by, limit, offset)
# repeat query until all results have been loaded
max_offset = count
if limit is not None:
max_offset = min(count, offset + limit)
if max_offset > offset + self.page_size:
progress = self._tqdm(desc="Querying products",
initial=self.page_size,
total=max_offset - offset,
unit=' products')
for new_offset in range(offset + self.page_size, max_offset, self.page_size):
new_limit = limit
if limit is not None:
new_limit = limit - new_offset + offset
ret = self._load_subquery(query, order_by, new_limit, new_offset)[0]
progress.update(len(ret))
products += ret
progress.close()
return products, count
def _load_subquery(self, query, order_by=None, limit=None, offset=0):
# store last query (for testing)
self._last_query = query
self.logger.debug("Sub-query: offset=%s, limit=%s", offset, limit)
# load query results
url = self._format_url(order_by, limit, offset)
response = self.session.post(url, {'q': query}, auth=self.session.auth,
headers={'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'},
timeout=self.timeout)
_check_scihub_response(response)
# store last status code (for testing)
self._last_response = response
# parse response content
try:
json_feed = response.json()['feed']
if json_feed['opensearch:totalResults'] is None:
# We are using some unintended behavior of the server that a null is
# returned as the total results value when the query string was incorrect.
raise SentinelAPIError(
'Invalid query string. Check the parameters and format.', response)
total_results = int(json_feed['opensearch:totalResults'])
except (ValueError, KeyError):
raise SentinelAPIError('API response not valid. JSON decoding failed.', response)
products = json_feed.get('entry', [])
# this verification is necessary because if the query returns only
# one product, self.products will be a dict not a list
if isinstance(products, dict):
products = [products]
return products, total_results
def _format_url(self, order_by=None, limit=None, offset=0):
if limit is None:
limit = self.page_size
limit = min(limit, self.page_size)
url = 'search?format=json&rows={}'.format(limit)
url += '&start={}'.format(offset)
if order_by:
url += '&orderby={}'.format(order_by)
return urljoin(self.api_url, url)
@staticmethod
def to_geojson(products):
"""Return the products from a query response as a GeoJSON with the values in their
appropriate Python types.
"""
feature_list = []
for i, (product_id, props) in enumerate(products.items()):
props = props.copy()
props['id'] = product_id
poly = geomet.wkt.loads(props['footprint'])
del props['footprint']
del props['gmlfootprint']
# Fix "'datetime' is not JSON serializable"
for k, v in props.items():
if isinstance(v, (date, datetime)):
props[k] = v.strftime('%Y-%m-%dT%H:%M:%S.%fZ')
feature_list.append(
geojson.Feature(geometry=poly, id=i, properties=props)
)
return geojson.FeatureCollection(feature_list)
@staticmethod
def to_dataframe(products):
"""Return the products from a query response as a Pandas DataFrame
with the values in their appropriate Python types.
"""
try:
import pandas as pd
except ImportError:
raise ImportError("to_dataframe requires the optional dependency Pandas.")
return pd.DataFrame.from_dict(products, orient='index')
@staticmethod
def to_geodataframe(products):
"""Return the products from a query response as a GeoPandas GeoDataFrame
with the values in their appropriate Python types.
"""
try:
import geopandas as gpd
import shapely.wkt
except ImportError:
raise ImportError("to_geodataframe requires the optional dependencies GeoPandas and Shapely.")
crs = {'init': 'epsg:4326'} # WGS84
if len(products) == 0:
return gpd.GeoDataFrame(crs=crs)
df = SentinelAPI.to_dataframe(products)
geometry = [shapely.wkt.loads(fp) for fp in df['footprint']]
# remove useless columns
df.drop(['footprint', 'gmlfootprint'], axis=1, inplace=True)
return gpd.GeoDataFrame(df, crs=crs, geometry=geometry)
def get_product_odata(self, id, full=False):
"""Access OData API to get info about a product.
Returns a dict containing the id, title, size, md5sum, date, footprint and download url
of the product. The date field corresponds to the Start ContentDate value.
If `full` is set to True, then the full, detailed metadata of the product is returned
in addition to the above.
Parameters
----------
id : string
The UUID of the product to query
full : bool
Whether to get the full metadata for the Product. False by default.
Returns
-------
dict[str, Any]
A dictionary with an item for each metadata attribute
Notes
-----
For a full list of mappings between the OpenSearch (Solr) and OData attribute names
see the following definition files:
https://github.com/SentinelDataHub/DataHubSystem/blob/master/addon/sentinel-1/src/main/resources/META-INF/sentinel-1.owl
https://github.com/SentinelDataHub/DataHubSystem/blob/master/addon/sentinel-2/src/main/resources/META-INF/sentinel-2.owl
https://github.com/SentinelDataHub/DataHubSystem/blob/master/addon/sentinel-3/src/main/resources/META-INF/sentinel-3.owl
"""
url = urljoin(self.api_url, u"odata/v1/Products('{}')?$format=json".format(id))
if full:
url += '&$expand=Attributes'
response = self.session.get(url, auth=self.session.auth,
timeout=self.timeout)
_check_scihub_response(response)
values = _parse_odata_response(response.json()['d'])
return values
def _trigger_offline_retrieval(self, url):
""" Triggers retrieval of an offline product
Trying to download an offline product triggers its retrieval from the long term archive.
The returned HTTP status code conveys whether this was successful.
Parameters
----------
url : string
URL for downloading the product
Notes
-----
https://scihub.copernicus.eu/userguide/LongTermArchive
"""
with self.session.get(url, auth=self.session.auth, timeout=self.timeout) as r:
# check https://scihub.copernicus.eu/userguide/LongTermArchive#HTTP_Status_codes
if r.status_code == 202:
self.logger.info("Accepted for retrieval")
elif r.status_code == 503:
self.logger.error("Request not accepted")
raise SentinelAPILTAError('Request for retrieval from LTA not accepted', r)
elif r.status_code == 403:
self.logger.error("Requests exceed user quota")
raise SentinelAPILTAError('Requests for retrieval from LTA exceed user quota', r)
elif r.status_code == 500:
# should not happen
self.logger.error("Trying to download an offline product")
raise SentinelAPILTAError('Trying to download an offline product', r)
return r.status_code
def download(self, id, directory_path='.', checksum=True):
"""Download a product.
Uses the filename on the server for the downloaded file, e.g.
"S1A_EW_GRDH_1SDH_20141003T003840_20141003T003920_002658_002F54_4DD1.zip".
Incomplete downloads are continued and complete files are skipped.
Parameters
----------
id : string
UUID of the product, e.g. 'a8dd0cfd-613e-45ce-868c-d79177b916ed'
directory_path : string, optional
Where the file will be downloaded
checksum : bool, optional
If True, verify the downloaded file's integrity by checking its MD5 checksum.
Throws InvalidChecksumError if the checksum does not match.
Defaults to True.
Returns
-------
product_info : dict
Dictionary containing the product's info from get_product_info() as well as
the path on disk.
Raises
------
InvalidChecksumError
If the MD5 checksum does not match the checksum on the server.
"""
product_info = self.get_product_odata(id)
path = join(directory_path, product_info['title'] + '.zip')
product_info['path'] = path
product_info['downloaded_bytes'] = 0
self.logger.info('Downloading %s to %s', id, path)
if exists(path):
# We assume that the product has been downloaded and is complete
return product_info
# An incomplete download triggers the retrieval from the LTA if the product is not online
if not product_info['Online']:
self.logger.warning(
'Product %s is not online. Triggering retrieval from long term archive.',
product_info['id'])
self._trigger_offline_retrieval(product_info['url'])
return product_info
# Use a temporary file for downloading
temp_path = path + '.incomplete'
skip_download = False
if exists(temp_path):
if getsize(temp_path) > product_info['size']:
self.logger.warning(
"Existing incomplete file %s is larger than the expected final size"
" (%s vs %s bytes). Deleting it.",
str(temp_path), getsize(temp_path), product_info['size'])
remove(temp_path)
elif getsize(temp_path) == product_info['size']:
if self._md5_compare(temp_path, product_info['md5']):
skip_download = True
else:
# Log a warning since this should never happen
self.logger.warning(
"Existing incomplete file %s appears to be fully downloaded but "
"its checksum is incorrect. Deleting it.",
str(temp_path))
remove(temp_path)
else:
# continue downloading
self.logger.info(
"Download will resume from existing incomplete file %s.", temp_path)
pass
if not skip_download:
# Store the number of downloaded bytes for unit tests
product_info['downloaded_bytes'] = self._download(
product_info['url'], temp_path, self.session, product_info['size'])
# Check integrity with MD5 checksum
if checksum is True:
if not self._md5_compare(temp_path, product_info['md5']):
remove(temp_path)
raise InvalidChecksumError('File corrupt: checksums do not match')
# Download successful, rename the temporary file to its proper name
shutil.move(temp_path, path)
return product_info
def download_all(self, products, directory_path='.', max_attempts=10, checksum=True):
"""Download a list of products.
Takes a list of product IDs as input. This means that the return value of query() can be
passed directly to this method.
File names on the server are used for the downloaded files, e.g.
"S1A_EW_GRDH_1SDH_20141003T003840_20141003T003920_002658_002F54_4DD1.zip".
In case of interruptions or other exceptions, downloading will restart from where it left
off. Downloading is attempted at most max_attempts times to avoid getting stuck with
unrecoverable errors.
Parameters
----------
products : list
List of product IDs
directory_path : string
Directory where the downloaded files will be downloaded
max_attempts : int, optional
Number of allowed retries before giving up downloading a product. Defaults to 10.
checksum : bool, optional
If True, verify the downloaded files' integrity by checking its MD5 checksum.
Throws InvalidChecksumError if the checksum does not match.
Defaults to True.
Raises
------
Raises the most recent downloading exception if all downloads failed.
Returns
-------
dict[string, dict]
A dictionary containing the return value from download() for each successfully
downloaded product.
dict[string, dict]
A dictionary containing the product information for products whose retrieval
from the long term archive was successfully triggered.
set[string]
The list of products that failed to download.
"""
product_ids = list(products)
self.logger.info("Will download %d products", len(product_ids))
return_values = OrderedDict()
last_exception = None
for i, product_id in enumerate(products):
for attempt_num in range(max_attempts):
try:
product_info = self.download(product_id, directory_path, checksum)
return_values[product_id] = product_info
break
except (KeyboardInterrupt, SystemExit):
raise
except InvalidChecksumError as e:
last_exception = e
self.logger.warning(
"Invalid checksum. The downloaded file for '%s' is corrupted.", product_id)
except SentinelAPILTAError as e:
last_exception = e
self.logger.exception("There was an error retrieving %s from the LTA", product_id)
break
except Exception as e:
last_exception = e
self.logger.exception("There was an error downloading %s", product_id)
self.logger.info("%s/%s products downloaded", i + 1, len(product_ids))
failed = set(products) - set(return_values)
# split up sucessfully processed products into downloaded and only triggered retrieval from the LTA
triggered = OrderedDict([(k, v) for k, v in return_values.items() if v['Online'] is False])
downloaded = OrderedDict([(k, v) for k, v in return_values.items() if v['Online'] is True])
if len(failed) == len(product_ids) and last_exception is not None:
raise last_exception
return downloaded, triggered, failed
@staticmethod
def get_products_size(products):
"""Return the total file size in GB of all products in the OpenSearch response."""
size_total = 0
for title, props in products.items():
size_product = props["size"]
size_value = float(size_product.split(" ")[0])
size_unit = str(size_product.split(" ")[1])
if size_unit == "MB":
size_value /= 1024.
if size_unit == "KB":
size_value /= 1024. * 1024.
size_total += size_value
return round(size_total, 2)
@staticmethod
def check_query_length(query):
"""Determine whether a query to the OpenSearch API is too long.
The length of a query string is limited to approximately 3938 characters but
any special characters (that is, not alphanumeric or -_.*) will take up more space.
Parameters
----------
query : str
The query string
Returns
-------
float
Ratio of the query length to the maximum length
"""
# The server uses the Java's URLEncoder implementation internally, which we are replicating here
effective_length = len(quote_plus(query, safe="-_.*").replace('~', '%7E'))
return effective_length / 3938
def _query_names(self, names):
"""Find products by their names, e.g.
S1A_EW_GRDH_1SDH_20141003T003840_20141003T003920_002658_002F54_4DD1.
Note that duplicates exist on server, so multiple products can be returned for each name.
Parameters
----------
names : list[string]
List of product names.
Returns
-------
dict[string, dict[str, dict]]
A dictionary mapping each name to a dictionary which contains the products with
that name (with ID as the key).
"""
def chunks(l, n):
"""Yield successive n-sized chunks from l."""
for i in range(0, len(l), n):
yield l[i:i + n]
products = {}
# 40 names per query fits reasonably well inside the query limit
for chunk in chunks(names, 40):
query = " OR ".join(chunk)
products.update(self.query(raw=query))
# Group the products
output = OrderedDict((name, dict()) for name in names)
for id, metadata in products.items():
name = metadata['identifier']
output[name][id] = metadata
return output
def _md5_compare(self, file_path, checksum, block_size=2 ** 13):
"""Compare a given MD5 checksum with one calculated from a file."""
with closing(self._tqdm(desc="MD5 checksumming", total=getsize(file_path), unit="B",
unit_scale=True)) as progress:
md5 = hashlib.md5()
with open(file_path, "rb") as f:
while True:
block_data = f.read(block_size)
if not block_data:
break
md5.update(block_data)
progress.update(len(block_data))
return md5.hexdigest().lower() == checksum.lower()
def _download(self, url, path, session, file_size):
headers = {}
continuing = exists(path)
if continuing:
already_downloaded_bytes = getsize(path)
headers = {'Range': 'bytes={}-'.format(already_downloaded_bytes)}
else:
already_downloaded_bytes = 0
downloaded_bytes = 0
with closing(session.get(url, stream=True, auth=session.auth,
headers=headers, timeout=self.timeout)) as r, \
closing(self._tqdm(desc="Downloading", total=file_size, unit="B",
unit_scale=True, initial=already_downloaded_bytes)) as progress:
_check_scihub_response(r, test_json=False)
chunk_size = 2 ** 20 # download in 1 MB chunks
mode = 'ab' if continuing else 'wb'
with open(path, mode) as f:
for chunk in r.iter_content(chunk_size=chunk_size):
if chunk: # filter out keep-alive new chunks
f.write(chunk)
progress.update(len(chunk))
downloaded_bytes += len(chunk)
# Return the number of bytes downloaded
return downloaded_bytes
def _tqdm(self, **kwargs):
"""tqdm progressbar wrapper. May be overridden to customize progressbar behavior"""
kwargs.update({'disable': not self.show_progressbars})
return tqdm(**kwargs)
|
sentinelsat/sentinelsat | sentinelsat/sentinel.py | SentinelAPI._md5_compare | python | def _md5_compare(self, file_path, checksum, block_size=2 ** 13):
with closing(self._tqdm(desc="MD5 checksumming", total=getsize(file_path), unit="B",
unit_scale=True)) as progress:
md5 = hashlib.md5()
with open(file_path, "rb") as f:
while True:
block_data = f.read(block_size)
if not block_data:
break
md5.update(block_data)
progress.update(len(block_data))
return md5.hexdigest().lower() == checksum.lower() | Compare a given MD5 checksum with one calculated from a file. | train | https://github.com/sentinelsat/sentinelsat/blob/eacfd79ff4e7e939147db9dfdd393c67d64eecaa/sentinelsat/sentinel.py#L795-L807 | [
"def _tqdm(self, **kwargs):\n \"\"\"tqdm progressbar wrapper. May be overridden to customize progressbar behavior\"\"\"\n kwargs.update({'disable': not self.show_progressbars})\n return tqdm(**kwargs)\n"
] | class SentinelAPI:
"""Class to connect to Copernicus Open Access Hub, search and download imagery.
Parameters
----------
user : string
username for DataHub
set to None to use ~/.netrc
password : string
password for DataHub
set to None to use ~/.netrc
api_url : string, optional
URL of the DataHub
defaults to 'https://scihub.copernicus.eu/apihub'
show_progressbars : bool
Whether progressbars should be shown or not, e.g. during download. Defaults to True.
timeout : float or tuple, optional
How long to wait for DataHub response (in seconds).
Tuple (connect, read) allowed.
Attributes
----------
session : requests.Session
Session to connect to DataHub
api_url : str
URL to the DataHub
page_size : int
Number of results per query page.
Current value: 100 (maximum allowed on ApiHub)
timeout : float or tuple
How long to wait for DataHub response (in seconds).
"""
logger = logging.getLogger('sentinelsat.SentinelAPI')
def __init__(self, user, password, api_url='https://scihub.copernicus.eu/apihub/',
show_progressbars=True, timeout=None):
self.session = requests.Session()
if user and password:
self.session.auth = (user, password)
self.api_url = api_url if api_url.endswith('/') else api_url + '/'
self.page_size = 100
self.user_agent = 'sentinelsat/' + sentinelsat_version
self.session.headers['User-Agent'] = self.user_agent
self.show_progressbars = show_progressbars
self.timeout = timeout
# For unit tests
self._last_query = None
self._last_response = None
def query(self, area=None, date=None, raw=None, area_relation='Intersects',
order_by=None, limit=None, offset=0, **keywords):
"""Query the OpenSearch API with the coordinates of an area, a date interval
and any other search keywords accepted by the API.
Parameters
----------
area : str, optional
The area of interest formatted as a Well-Known Text string.
date : tuple of (str or datetime) or str, optional
A time interval filter based on the Sensing Start Time of the products.
Expects a tuple of (start, end), e.g. ("NOW-1DAY", "NOW").
The timestamps can be either a Python datetime or a string in one of the
following formats:
- yyyyMMdd
- yyyy-MM-ddThh:mm:ss.SSSZ (ISO-8601)
- yyyy-MM-ddThh:mm:ssZ
- NOW
- NOW-<n>DAY(S) (or HOUR(S), MONTH(S), etc.)
- NOW+<n>DAY(S)
- yyyy-MM-ddThh:mm:ssZ-<n>DAY(S)
- NOW/DAY (or HOUR, MONTH etc.) - rounds the value to the given unit
Alternatively, an already fully formatted string such as "[NOW-1DAY TO NOW]" can be
used as well.
raw : str, optional
Additional query text that will be appended to the query.
area_relation : {'Intersects', 'Contains', 'IsWithin'}, optional
What relation to use for testing the AOI. Case insensitive.
- Intersects: true if the AOI and the footprint intersect (default)
- Contains: true if the AOI is inside the footprint
- IsWithin: true if the footprint is inside the AOI
order_by: str, optional
A comma-separated list of fields to order by (on server side).
Prefix the field name by '+' or '-' to sort in ascending or descending order,
respectively. Ascending order is used if prefix is omitted.
Example: "cloudcoverpercentage, -beginposition".
limit: int, optional
Maximum number of products returned. Defaults to no limit.
offset: int, optional
The number of results to skip. Defaults to 0.
**keywords
Additional keywords can be used to specify other query parameters,
e.g. `relativeorbitnumber=70`.
See https://scihub.copernicus.eu/twiki/do/view/SciHubUserGuide/3FullTextSearch
for a full list.
Range values can be passed as two-element tuples, e.g. `cloudcoverpercentage=(0, 30)`.
`None` can be used in range values for one-sided ranges, e.g. `orbitnumber=(16302, None)`.
Ranges with no bounds (`orbitnumber=(None, None)`) will not be included in the query.
The time interval formats accepted by the `date` parameter can also be used with
any other parameters that expect time intervals (that is: 'beginposition', 'endposition',
'date', 'creationdate', and 'ingestiondate').
Returns
-------
dict[string, dict]
Products returned by the query as a dictionary with the product ID as the key and
the product's attributes (a dictionary) as the value.
"""
query = self.format_query(area, date, raw, area_relation, **keywords)
self.logger.debug("Running query: order_by=%s, limit=%s, offset=%s, query=%s",
order_by, limit, offset, query)
formatted_order_by = _format_order_by(order_by)
response, count = self._load_query(query, formatted_order_by, limit, offset)
self.logger.info("Found %s products", count)
return _parse_opensearch_response(response)
@staticmethod
def format_query(area=None, date=None, raw=None, area_relation='Intersects',
**keywords):
"""Create a OpenSearch API query string.
"""
if area_relation.lower() not in {"intersects", "contains", "iswithin"}:
raise ValueError("Incorrect AOI relation provided ({})".format(area_relation))
# Check for duplicate keywords
kw_lower = set(x.lower() for x in keywords)
if (len(kw_lower) != len(keywords) or
(date is not None and 'beginposition' in kw_lower) or
(area is not None and 'footprint' in kw_lower)):
raise ValueError("Query contains duplicate keywords. Note that query keywords are case-insensitive.")
query_parts = []
if date is not None:
keywords['beginPosition'] = date
for attr, value in sorted(keywords.items()):
# Escape spaces, where appropriate
if isinstance(value, string_types):
value = value.strip()
if not any(value.startswith(s[0]) and value.endswith(s[1]) for s in ['[]', '{}', '//', '()']):
value = re.sub(r'\s', r'\ ', value, re.M)
# Handle date keywords
# Keywords from https://github.com/SentinelDataHub/DataHubSystem/search?q=text/date+iso8601
date_attrs = ['beginposition', 'endposition', 'date', 'creationdate', 'ingestiondate']
if attr.lower() in date_attrs:
# Automatically format date-type attributes
if isinstance(value, string_types) and ' TO ' in value:
# This is a string already formatted as a date interval,
# e.g. '[NOW-1DAY TO NOW]'
pass
elif not isinstance(value, string_types) and len(value) == 2:
value = (format_query_date(value[0]), format_query_date(value[1]))
else:
raise ValueError("Date-type query parameter '{}' expects a two-element tuple "
"of str or datetime objects. Received {}".format(attr, value))
# Handle ranged values
if isinstance(value, (list, tuple)):
# Handle value ranges
if len(value) == 2:
# Allow None to be used as a unlimited bound
value = ['*' if x is None else x for x in value]
if all(x == '*' for x in value):
continue
value = '[{} TO {}]'.format(*value)
else:
raise ValueError("Invalid number of elements in list. Expected 2, received "
"{}".format(len(value)))
query_parts.append('{}:{}'.format(attr, value))
if raw:
query_parts.append(raw)
if area is not None:
query_parts.append('footprint:"{}({})"'.format(area_relation, area))
return ' '.join(query_parts)
def query_raw(self, query, order_by=None, limit=None, offset=0):
"""
Do a full-text query on the OpenSearch API using the format specified in
https://scihub.copernicus.eu/twiki/do/view/SciHubUserGuide/3FullTextSearch
DEPRECATED: use :meth:`query(raw=...) <.query>` instead. This method will be removed in the next major release.
Parameters
----------
query : str
The query string.
order_by: str, optional
A comma-separated list of fields to order by (on server side).
Prefix the field name by '+' or '-' to sort in ascending or descending order, respectively.
Ascending order is used, if prefix is omitted.
Example: "cloudcoverpercentage, -beginposition".
limit: int, optional
Maximum number of products returned. Defaults to no limit.
offset: int, optional
The number of results to skip. Defaults to 0.
Returns
-------
dict[string, dict]
Products returned by the query as a dictionary with the product ID as the key and
the product's attributes (a dictionary) as the value.
"""
warnings.warn(
"query_raw() has been merged with query(). use query(raw=...) instead.",
PendingDeprecationWarning
)
return self.query(raw=query, order_by=order_by, limit=limit, offset=offset)
def count(self, area=None, date=None, raw=None, area_relation='Intersects', **keywords):
"""Get the number of products matching a query.
Accepted parameters are identical to :meth:`SentinelAPI.query()`.
This is a significantly more efficient alternative to doing `len(api.query())`,
which can take minutes to run for queries matching thousands of products.
Returns
-------
int
The number of products matching a query.
"""
for kw in ['order_by', 'limit', 'offset']:
# Allow these function arguments to be included for compatibility with query(),
# but ignore them.
if kw in keywords:
del keywords[kw]
query = self.format_query(area, date, raw, area_relation, **keywords)
_, total_count = self._load_query(query, limit=0)
return total_count
def _load_query(self, query, order_by=None, limit=None, offset=0):
products, count = self._load_subquery(query, order_by, limit, offset)
# repeat query until all results have been loaded
max_offset = count
if limit is not None:
max_offset = min(count, offset + limit)
if max_offset > offset + self.page_size:
progress = self._tqdm(desc="Querying products",
initial=self.page_size,
total=max_offset - offset,
unit=' products')
for new_offset in range(offset + self.page_size, max_offset, self.page_size):
new_limit = limit
if limit is not None:
new_limit = limit - new_offset + offset
ret = self._load_subquery(query, order_by, new_limit, new_offset)[0]
progress.update(len(ret))
products += ret
progress.close()
return products, count
def _load_subquery(self, query, order_by=None, limit=None, offset=0):
# store last query (for testing)
self._last_query = query
self.logger.debug("Sub-query: offset=%s, limit=%s", offset, limit)
# load query results
url = self._format_url(order_by, limit, offset)
response = self.session.post(url, {'q': query}, auth=self.session.auth,
headers={'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'},
timeout=self.timeout)
_check_scihub_response(response)
# store last status code (for testing)
self._last_response = response
# parse response content
try:
json_feed = response.json()['feed']
if json_feed['opensearch:totalResults'] is None:
# We are using some unintended behavior of the server that a null is
# returned as the total results value when the query string was incorrect.
raise SentinelAPIError(
'Invalid query string. Check the parameters and format.', response)
total_results = int(json_feed['opensearch:totalResults'])
except (ValueError, KeyError):
raise SentinelAPIError('API response not valid. JSON decoding failed.', response)
products = json_feed.get('entry', [])
# this verification is necessary because if the query returns only
# one product, self.products will be a dict not a list
if isinstance(products, dict):
products = [products]
return products, total_results
def _format_url(self, order_by=None, limit=None, offset=0):
if limit is None:
limit = self.page_size
limit = min(limit, self.page_size)
url = 'search?format=json&rows={}'.format(limit)
url += '&start={}'.format(offset)
if order_by:
url += '&orderby={}'.format(order_by)
return urljoin(self.api_url, url)
@staticmethod
def to_geojson(products):
"""Return the products from a query response as a GeoJSON with the values in their
appropriate Python types.
"""
feature_list = []
for i, (product_id, props) in enumerate(products.items()):
props = props.copy()
props['id'] = product_id
poly = geomet.wkt.loads(props['footprint'])
del props['footprint']
del props['gmlfootprint']
# Fix "'datetime' is not JSON serializable"
for k, v in props.items():
if isinstance(v, (date, datetime)):
props[k] = v.strftime('%Y-%m-%dT%H:%M:%S.%fZ')
feature_list.append(
geojson.Feature(geometry=poly, id=i, properties=props)
)
return geojson.FeatureCollection(feature_list)
@staticmethod
def to_dataframe(products):
"""Return the products from a query response as a Pandas DataFrame
with the values in their appropriate Python types.
"""
try:
import pandas as pd
except ImportError:
raise ImportError("to_dataframe requires the optional dependency Pandas.")
return pd.DataFrame.from_dict(products, orient='index')
@staticmethod
def to_geodataframe(products):
"""Return the products from a query response as a GeoPandas GeoDataFrame
with the values in their appropriate Python types.
"""
try:
import geopandas as gpd
import shapely.wkt
except ImportError:
raise ImportError("to_geodataframe requires the optional dependencies GeoPandas and Shapely.")
crs = {'init': 'epsg:4326'} # WGS84
if len(products) == 0:
return gpd.GeoDataFrame(crs=crs)
df = SentinelAPI.to_dataframe(products)
geometry = [shapely.wkt.loads(fp) for fp in df['footprint']]
# remove useless columns
df.drop(['footprint', 'gmlfootprint'], axis=1, inplace=True)
return gpd.GeoDataFrame(df, crs=crs, geometry=geometry)
def get_product_odata(self, id, full=False):
"""Access OData API to get info about a product.
Returns a dict containing the id, title, size, md5sum, date, footprint and download url
of the product. The date field corresponds to the Start ContentDate value.
If `full` is set to True, then the full, detailed metadata of the product is returned
in addition to the above.
Parameters
----------
id : string
The UUID of the product to query
full : bool
Whether to get the full metadata for the Product. False by default.
Returns
-------
dict[str, Any]
A dictionary with an item for each metadata attribute
Notes
-----
For a full list of mappings between the OpenSearch (Solr) and OData attribute names
see the following definition files:
https://github.com/SentinelDataHub/DataHubSystem/blob/master/addon/sentinel-1/src/main/resources/META-INF/sentinel-1.owl
https://github.com/SentinelDataHub/DataHubSystem/blob/master/addon/sentinel-2/src/main/resources/META-INF/sentinel-2.owl
https://github.com/SentinelDataHub/DataHubSystem/blob/master/addon/sentinel-3/src/main/resources/META-INF/sentinel-3.owl
"""
url = urljoin(self.api_url, u"odata/v1/Products('{}')?$format=json".format(id))
if full:
url += '&$expand=Attributes'
response = self.session.get(url, auth=self.session.auth,
timeout=self.timeout)
_check_scihub_response(response)
values = _parse_odata_response(response.json()['d'])
return values
def _trigger_offline_retrieval(self, url):
""" Triggers retrieval of an offline product
Trying to download an offline product triggers its retrieval from the long term archive.
The returned HTTP status code conveys whether this was successful.
Parameters
----------
url : string
URL for downloading the product
Notes
-----
https://scihub.copernicus.eu/userguide/LongTermArchive
"""
with self.session.get(url, auth=self.session.auth, timeout=self.timeout) as r:
# check https://scihub.copernicus.eu/userguide/LongTermArchive#HTTP_Status_codes
if r.status_code == 202:
self.logger.info("Accepted for retrieval")
elif r.status_code == 503:
self.logger.error("Request not accepted")
raise SentinelAPILTAError('Request for retrieval from LTA not accepted', r)
elif r.status_code == 403:
self.logger.error("Requests exceed user quota")
raise SentinelAPILTAError('Requests for retrieval from LTA exceed user quota', r)
elif r.status_code == 500:
# should not happen
self.logger.error("Trying to download an offline product")
raise SentinelAPILTAError('Trying to download an offline product', r)
return r.status_code
def download(self, id, directory_path='.', checksum=True):
"""Download a product.
Uses the filename on the server for the downloaded file, e.g.
"S1A_EW_GRDH_1SDH_20141003T003840_20141003T003920_002658_002F54_4DD1.zip".
Incomplete downloads are continued and complete files are skipped.
Parameters
----------
id : string
UUID of the product, e.g. 'a8dd0cfd-613e-45ce-868c-d79177b916ed'
directory_path : string, optional
Where the file will be downloaded
checksum : bool, optional
If True, verify the downloaded file's integrity by checking its MD5 checksum.
Throws InvalidChecksumError if the checksum does not match.
Defaults to True.
Returns
-------
product_info : dict
Dictionary containing the product's info from get_product_info() as well as
the path on disk.
Raises
------
InvalidChecksumError
If the MD5 checksum does not match the checksum on the server.
"""
product_info = self.get_product_odata(id)
path = join(directory_path, product_info['title'] + '.zip')
product_info['path'] = path
product_info['downloaded_bytes'] = 0
self.logger.info('Downloading %s to %s', id, path)
if exists(path):
# We assume that the product has been downloaded and is complete
return product_info
# An incomplete download triggers the retrieval from the LTA if the product is not online
if not product_info['Online']:
self.logger.warning(
'Product %s is not online. Triggering retrieval from long term archive.',
product_info['id'])
self._trigger_offline_retrieval(product_info['url'])
return product_info
# Use a temporary file for downloading
temp_path = path + '.incomplete'
skip_download = False
if exists(temp_path):
if getsize(temp_path) > product_info['size']:
self.logger.warning(
"Existing incomplete file %s is larger than the expected final size"
" (%s vs %s bytes). Deleting it.",
str(temp_path), getsize(temp_path), product_info['size'])
remove(temp_path)
elif getsize(temp_path) == product_info['size']:
if self._md5_compare(temp_path, product_info['md5']):
skip_download = True
else:
# Log a warning since this should never happen
self.logger.warning(
"Existing incomplete file %s appears to be fully downloaded but "
"its checksum is incorrect. Deleting it.",
str(temp_path))
remove(temp_path)
else:
# continue downloading
self.logger.info(
"Download will resume from existing incomplete file %s.", temp_path)
pass
if not skip_download:
# Store the number of downloaded bytes for unit tests
product_info['downloaded_bytes'] = self._download(
product_info['url'], temp_path, self.session, product_info['size'])
# Check integrity with MD5 checksum
if checksum is True:
if not self._md5_compare(temp_path, product_info['md5']):
remove(temp_path)
raise InvalidChecksumError('File corrupt: checksums do not match')
# Download successful, rename the temporary file to its proper name
shutil.move(temp_path, path)
return product_info
def download_all(self, products, directory_path='.', max_attempts=10, checksum=True):
"""Download a list of products.
Takes a list of product IDs as input. This means that the return value of query() can be
passed directly to this method.
File names on the server are used for the downloaded files, e.g.
"S1A_EW_GRDH_1SDH_20141003T003840_20141003T003920_002658_002F54_4DD1.zip".
In case of interruptions or other exceptions, downloading will restart from where it left
off. Downloading is attempted at most max_attempts times to avoid getting stuck with
unrecoverable errors.
Parameters
----------
products : list
List of product IDs
directory_path : string
Directory where the downloaded files will be downloaded
max_attempts : int, optional
Number of allowed retries before giving up downloading a product. Defaults to 10.
checksum : bool, optional
If True, verify the downloaded files' integrity by checking its MD5 checksum.
Throws InvalidChecksumError if the checksum does not match.
Defaults to True.
Raises
------
Raises the most recent downloading exception if all downloads failed.
Returns
-------
dict[string, dict]
A dictionary containing the return value from download() for each successfully
downloaded product.
dict[string, dict]
A dictionary containing the product information for products whose retrieval
from the long term archive was successfully triggered.
set[string]
The list of products that failed to download.
"""
product_ids = list(products)
self.logger.info("Will download %d products", len(product_ids))
return_values = OrderedDict()
last_exception = None
for i, product_id in enumerate(products):
for attempt_num in range(max_attempts):
try:
product_info = self.download(product_id, directory_path, checksum)
return_values[product_id] = product_info
break
except (KeyboardInterrupt, SystemExit):
raise
except InvalidChecksumError as e:
last_exception = e
self.logger.warning(
"Invalid checksum. The downloaded file for '%s' is corrupted.", product_id)
except SentinelAPILTAError as e:
last_exception = e
self.logger.exception("There was an error retrieving %s from the LTA", product_id)
break
except Exception as e:
last_exception = e
self.logger.exception("There was an error downloading %s", product_id)
self.logger.info("%s/%s products downloaded", i + 1, len(product_ids))
failed = set(products) - set(return_values)
# split up sucessfully processed products into downloaded and only triggered retrieval from the LTA
triggered = OrderedDict([(k, v) for k, v in return_values.items() if v['Online'] is False])
downloaded = OrderedDict([(k, v) for k, v in return_values.items() if v['Online'] is True])
if len(failed) == len(product_ids) and last_exception is not None:
raise last_exception
return downloaded, triggered, failed
@staticmethod
def get_products_size(products):
"""Return the total file size in GB of all products in the OpenSearch response."""
size_total = 0
for title, props in products.items():
size_product = props["size"]
size_value = float(size_product.split(" ")[0])
size_unit = str(size_product.split(" ")[1])
if size_unit == "MB":
size_value /= 1024.
if size_unit == "KB":
size_value /= 1024. * 1024.
size_total += size_value
return round(size_total, 2)
@staticmethod
def check_query_length(query):
"""Determine whether a query to the OpenSearch API is too long.
The length of a query string is limited to approximately 3938 characters but
any special characters (that is, not alphanumeric or -_.*) will take up more space.
Parameters
----------
query : str
The query string
Returns
-------
float
Ratio of the query length to the maximum length
"""
# The server uses the Java's URLEncoder implementation internally, which we are replicating here
effective_length = len(quote_plus(query, safe="-_.*").replace('~', '%7E'))
return effective_length / 3938
def _query_names(self, names):
"""Find products by their names, e.g.
S1A_EW_GRDH_1SDH_20141003T003840_20141003T003920_002658_002F54_4DD1.
Note that duplicates exist on server, so multiple products can be returned for each name.
Parameters
----------
names : list[string]
List of product names.
Returns
-------
dict[string, dict[str, dict]]
A dictionary mapping each name to a dictionary which contains the products with
that name (with ID as the key).
"""
def chunks(l, n):
"""Yield successive n-sized chunks from l."""
for i in range(0, len(l), n):
yield l[i:i + n]
products = {}
# 40 names per query fits reasonably well inside the query limit
for chunk in chunks(names, 40):
query = " OR ".join(chunk)
products.update(self.query(raw=query))
# Group the products
output = OrderedDict((name, dict()) for name in names)
for id, metadata in products.items():
name = metadata['identifier']
output[name][id] = metadata
return output
def check_files(self, paths=None, ids=None, directory=None, delete=False):
"""Verify the integrity of product files on disk.
Integrity is checked by comparing the size and checksum of the file with the respective
values on the server.
The input can be a list of products to check or a list of IDs and a directory.
In cases where multiple products with different IDs exist on the server for given product
name, the file is considered to be correct if any of them matches the file size and
checksum. A warning is logged in such situations.
The corrupt products' OData info is included in the return value to make it easier to
re-download the products, if necessary.
Parameters
----------
paths : list[string]
List of product file paths.
ids : list[string]
List of product IDs.
directory : string
Directory where the files are located, if checking based on product IDs.
delete : bool
Whether to delete corrupt products. Defaults to False.
Returns
-------
dict[str, list[dict]]
A dictionary listing the invalid or missing files. The dictionary maps the corrupt
file paths to a list of OData dictionaries of matching products on the server (as
returned by :meth:`SentinelAPI.get_product_odata()`).
"""
if not ids and not paths:
raise ValueError("Must provide either file paths or product IDs and a directory")
if ids and not directory:
raise ValueError("Directory value missing")
paths = paths or []
ids = ids or []
def name_from_path(path):
return splitext(basename(path))[0]
# Get product IDs corresponding to the files on disk
names = []
if paths:
names = list(map(name_from_path, paths))
result = self._query_names(names)
for product_dicts in result.values():
ids += list(product_dicts)
names_from_paths = set(names)
ids = set(ids)
# Collect the OData information for each product
# Product name -> list of matching odata dicts
product_infos = defaultdict(list)
for id in ids:
odata = self.get_product_odata(id)
name = odata['title']
product_infos[name].append(odata)
# Collect
if name not in names_from_paths:
paths.append(join(directory, name + '.zip'))
# Now go over the list of products and check them
corrupt = {}
for path in paths:
name = name_from_path(path)
if len(product_infos[name]) > 1:
self.logger.warning("{} matches multiple products on server".format(path))
if not exists(path):
# We will consider missing files as corrupt also
self.logger.info("{} does not exist on disk".format(path))
corrupt[path] = product_infos[name]
continue
is_fine = False
for product_info in product_infos[name]:
if (getsize(path) == product_info['size'] and
self._md5_compare(path, product_info['md5'])):
is_fine = True
break
if not is_fine:
self.logger.info("{} is corrupt".format(path))
corrupt[path] = product_infos[name]
if delete:
remove(path)
return corrupt
def _download(self, url, path, session, file_size):
headers = {}
continuing = exists(path)
if continuing:
already_downloaded_bytes = getsize(path)
headers = {'Range': 'bytes={}-'.format(already_downloaded_bytes)}
else:
already_downloaded_bytes = 0
downloaded_bytes = 0
with closing(session.get(url, stream=True, auth=session.auth,
headers=headers, timeout=self.timeout)) as r, \
closing(self._tqdm(desc="Downloading", total=file_size, unit="B",
unit_scale=True, initial=already_downloaded_bytes)) as progress:
_check_scihub_response(r, test_json=False)
chunk_size = 2 ** 20 # download in 1 MB chunks
mode = 'ab' if continuing else 'wb'
with open(path, mode) as f:
for chunk in r.iter_content(chunk_size=chunk_size):
if chunk: # filter out keep-alive new chunks
f.write(chunk)
progress.update(len(chunk))
downloaded_bytes += len(chunk)
# Return the number of bytes downloaded
return downloaded_bytes
def _tqdm(self, **kwargs):
"""tqdm progressbar wrapper. May be overridden to customize progressbar behavior"""
kwargs.update({'disable': not self.show_progressbars})
return tqdm(**kwargs)
|
deanmalmgren/textract | textract/parsers/odt_parser.py | Parser.to_string | python | def to_string(self):
buff = u""
for child in self.content.iter():
if child.tag in [self.qn('text:p'), self.qn('text:h')]:
buff += self.text_to_string(child) + "\n"
# remove last newline char
if buff:
buff = buff[:-1]
return buff | Converts the document to a string. | train | https://github.com/deanmalmgren/textract/blob/117ea191d93d80321e4bf01f23cc1ac54d69a075/textract/parsers/odt_parser.py#L19-L28 | [
"def qn(self, namespace):\n \"\"\"Connect tag prefix to longer namespace\"\"\"\n nsmap = {\n 'text': 'urn:oasis:names:tc:opendocument:xmlns:text:1.0',\n }\n spl = namespace.split(':')\n return '{{{}}}{}'.format(nsmap[spl[0]], spl[1])\n"
] | class Parser(BaseParser):
"""Extract text from open document files.
"""
def extract(self, filename, **kwargs):
# Inspiration from
# https://github.com/odoo/odoo/blob/master/addons/document/odt2txt.py
with open(filename, 'rb') as stream:
zip_stream = zipfile.ZipFile(stream)
self.content = ET.fromstring(zip_stream.read("content.xml"))
return self.to_string()
def text_to_string(self, element):
buff = u""
if element.text is not None:
buff += element.text
for child in element:
if child.tag == self.qn('text:tab'):
buff += "\t"
if child.tail is not None:
buff += child.tail
elif child.tag == self.qn('text:s'):
buff += u" "
if child.get(self.qn('text:c')) is not None:
buff += u" " * (int(child.get(self.qn('text:c'))) - 1)
if child.tail is not None:
buff += child.tail
else:
buff += self.text_to_string(child)
if element.tail is not None:
buff += element.tail
return buff
def qn(self, namespace):
"""Connect tag prefix to longer namespace"""
nsmap = {
'text': 'urn:oasis:names:tc:opendocument:xmlns:text:1.0',
}
spl = namespace.split(':')
return '{{{}}}{}'.format(nsmap[spl[0]], spl[1])
|
deanmalmgren/textract | textract/parsers/odt_parser.py | Parser.qn | python | def qn(self, namespace):
nsmap = {
'text': 'urn:oasis:names:tc:opendocument:xmlns:text:1.0',
}
spl = namespace.split(':')
return '{{{}}}{}'.format(nsmap[spl[0]], spl[1]) | Connect tag prefix to longer namespace | train | https://github.com/deanmalmgren/textract/blob/117ea191d93d80321e4bf01f23cc1ac54d69a075/textract/parsers/odt_parser.py#L51-L57 | null | class Parser(BaseParser):
"""Extract text from open document files.
"""
def extract(self, filename, **kwargs):
# Inspiration from
# https://github.com/odoo/odoo/blob/master/addons/document/odt2txt.py
with open(filename, 'rb') as stream:
zip_stream = zipfile.ZipFile(stream)
self.content = ET.fromstring(zip_stream.read("content.xml"))
return self.to_string()
def to_string(self):
""" Converts the document to a string. """
buff = u""
for child in self.content.iter():
if child.tag in [self.qn('text:p'), self.qn('text:h')]:
buff += self.text_to_string(child) + "\n"
# remove last newline char
if buff:
buff = buff[:-1]
return buff
def text_to_string(self, element):
buff = u""
if element.text is not None:
buff += element.text
for child in element:
if child.tag == self.qn('text:tab'):
buff += "\t"
if child.tail is not None:
buff += child.tail
elif child.tag == self.qn('text:s'):
buff += u" "
if child.get(self.qn('text:c')) is not None:
buff += u" " * (int(child.get(self.qn('text:c'))) - 1)
if child.tail is not None:
buff += child.tail
else:
buff += self.text_to_string(child)
if element.tail is not None:
buff += element.tail
return buff
|
deanmalmgren/textract | textract/cli.py | get_parser | python | def get_parser():
# initialize the parser
parser = argparse.ArgumentParser(
description=(
'Command line tool for extracting text from any document. '
) % locals(),
)
# define the command line options here
parser.add_argument(
'filename', help='Filename to extract text.',
).completer = argcomplete.completers.FilesCompleter
parser.add_argument(
'-e', '--encoding', type=str, default=DEFAULT_ENCODING,
choices=_get_available_encodings(),
help='Specify the encoding of the output.',
)
parser.add_argument(
'--extension', type=str, default=None,
choices=_get_available_extensions(),
help='Specify the extension of the file.',
)
parser.add_argument(
'-m', '--method', default='',
help='Specify a method of extraction for formats that support it',
)
parser.add_argument(
'-o', '--output', type=FileType('wb'), default='-',
help='Output raw text in this file',
)
parser.add_argument(
'-O', '--option', type=str, action=AddToNamespaceAction,
help=(
'Add arbitrary options to various parsers of the form '
'KEYWORD=VALUE. A full list of available KEYWORD options is '
'available at http://bit.ly/textract-options'
),
)
parser.add_argument(
'-v', '--version', action='version', version='%(prog)s '+VERSION,
)
# enable autocompletion with argcomplete
argcomplete.autocomplete(parser)
return parser | Initialize the parser for the command line interface and bind the
autocompletion functionality | train | https://github.com/deanmalmgren/textract/blob/117ea191d93d80321e4bf01f23cc1ac54d69a075/textract/cli.py#L45-L93 | [
"def _get_available_extensions():\n \"\"\"Get a list of available file extensions to make it easy for\n tab-completion and exception handling.\n \"\"\"\n extensions = []\n\n # from filenames\n parsers_dir = os.path.join(os.path.dirname(__file__))\n glob_filename = os.path.join(parsers_dir, \"*\" + _FILENAME_SUFFIX + \".py\")\n ext_re = re.compile(glob_filename.replace('*', \"(?P<ext>\\w+)\"))\n for filename in glob.glob(glob_filename):\n ext_match = ext_re.match(filename)\n ext = ext_match.groups()[0]\n extensions.append(ext)\n extensions.append('.' + ext)\n\n # from relevant synonyms (don't use the '' synonym)\n for ext in EXTENSION_SYNONYMS.keys():\n if ext:\n extensions.append(ext)\n extensions.append(ext.replace('.', '', 1))\n extensions.sort()\n return extensions\n",
"def _get_available_encodings():\n \"\"\"Get a list of the available encodings to make it easy to\n tab-complete the command line interface.\n\n Inspiration from http://stackoverflow.com/a/3824405/564709\n \"\"\"\n available_encodings = set(encodings.aliases.aliases.values())\n paths = [os.path.dirname(encodings.__file__)]\n for importer, modname, ispkg in pkgutil.walk_packages(path=paths):\n available_encodings.add(modname)\n available_encodings = list(available_encodings)\n available_encodings.sort()\n return available_encodings\n"
] | """
Use argparse to handle command-line arguments.
"""
import argparse
import encodings
import os
import pkgutil
import sys
import six
import re
import glob
import argcomplete
from . import VERSION
from .parsers import DEFAULT_ENCODING, _get_available_extensions
class AddToNamespaceAction(argparse.Action):
"""This adds KEY,VALUE arbitrary pairs to the argparse.Namespace object
"""
def __call__(self, parser, namespace, values, option_string=None):
key, val = values.strip().split('=')
if hasattr(namespace, key):
parser.error((
'Duplicate specification of the key "%(key)s" with --option.'
) % locals())
setattr(namespace, key, val)
# Fix FileType to honor 'b' flag, see: https://bugs.python.org/issue14156
class FileType(argparse.FileType):
def __call__(self, string):
if string == '-' and six.PY3:
if 'r' in self._mode:
string = sys.stdin.fileno()
elif 'w' in self._mode:
string = sys.stdout.fileno()
return super(FileType, self).__call__(string)
# This function is necessary to enable autodocumentation of the script
# output
def _get_available_encodings():
"""Get a list of the available encodings to make it easy to
tab-complete the command line interface.
Inspiration from http://stackoverflow.com/a/3824405/564709
"""
available_encodings = set(encodings.aliases.aliases.values())
paths = [os.path.dirname(encodings.__file__)]
for importer, modname, ispkg in pkgutil.walk_packages(path=paths):
available_encodings.add(modname)
available_encodings = list(available_encodings)
available_encodings.sort()
return available_encodings
|
deanmalmgren/textract | textract/cli.py | _get_available_encodings | python | def _get_available_encodings():
available_encodings = set(encodings.aliases.aliases.values())
paths = [os.path.dirname(encodings.__file__)]
for importer, modname, ispkg in pkgutil.walk_packages(path=paths):
available_encodings.add(modname)
available_encodings = list(available_encodings)
available_encodings.sort()
return available_encodings | Get a list of the available encodings to make it easy to
tab-complete the command line interface.
Inspiration from http://stackoverflow.com/a/3824405/564709 | train | https://github.com/deanmalmgren/textract/blob/117ea191d93d80321e4bf01f23cc1ac54d69a075/textract/cli.py#L96-L108 | null | """
Use argparse to handle command-line arguments.
"""
import argparse
import encodings
import os
import pkgutil
import sys
import six
import re
import glob
import argcomplete
from . import VERSION
from .parsers import DEFAULT_ENCODING, _get_available_extensions
class AddToNamespaceAction(argparse.Action):
"""This adds KEY,VALUE arbitrary pairs to the argparse.Namespace object
"""
def __call__(self, parser, namespace, values, option_string=None):
key, val = values.strip().split('=')
if hasattr(namespace, key):
parser.error((
'Duplicate specification of the key "%(key)s" with --option.'
) % locals())
setattr(namespace, key, val)
# Fix FileType to honor 'b' flag, see: https://bugs.python.org/issue14156
class FileType(argparse.FileType):
def __call__(self, string):
if string == '-' and six.PY3:
if 'r' in self._mode:
string = sys.stdin.fileno()
elif 'w' in self._mode:
string = sys.stdout.fileno()
return super(FileType, self).__call__(string)
# This function is necessary to enable autodocumentation of the script
# output
def get_parser():
"""Initialize the parser for the command line interface and bind the
autocompletion functionality"""
# initialize the parser
parser = argparse.ArgumentParser(
description=(
'Command line tool for extracting text from any document. '
) % locals(),
)
# define the command line options here
parser.add_argument(
'filename', help='Filename to extract text.',
).completer = argcomplete.completers.FilesCompleter
parser.add_argument(
'-e', '--encoding', type=str, default=DEFAULT_ENCODING,
choices=_get_available_encodings(),
help='Specify the encoding of the output.',
)
parser.add_argument(
'--extension', type=str, default=None,
choices=_get_available_extensions(),
help='Specify the extension of the file.',
)
parser.add_argument(
'-m', '--method', default='',
help='Specify a method of extraction for formats that support it',
)
parser.add_argument(
'-o', '--output', type=FileType('wb'), default='-',
help='Output raw text in this file',
)
parser.add_argument(
'-O', '--option', type=str, action=AddToNamespaceAction,
help=(
'Add arbitrary options to various parsers of the form '
'KEYWORD=VALUE. A full list of available KEYWORD options is '
'available at http://bit.ly/textract-options'
),
)
parser.add_argument(
'-v', '--version', action='version', version='%(prog)s '+VERSION,
)
# enable autocompletion with argcomplete
argcomplete.autocomplete(parser)
return parser
|
deanmalmgren/textract | textract/parsers/json_parser.py | Parser.get_text | python | def get_text(self, deserialized_json):
if isinstance(deserialized_json, dict):
result = ''
for key in sorted(deserialized_json):
result += self.get_text(deserialized_json[key]) + ' '
return result
if isinstance(deserialized_json, list):
result = ''
for item in deserialized_json:
result += self.get_text(item) + ' '
return result
if isinstance(deserialized_json, six.string_types):
return deserialized_json
else:
return '' | Recursively get text from subcomponents of a deserialized json. To
enforce the same order on the documents, make sure to read keys of
deserialized_json in a consistent (alphabetical) order. | train | https://github.com/deanmalmgren/textract/blob/117ea191d93d80321e4bf01f23cc1ac54d69a075/textract/parsers/json_parser.py#L18-L38 | [
"def get_text(self, deserialized_json):\n \"\"\"Recursively get text from subcomponents of a deserialized json. To\n enforce the same order on the documents, make sure to read keys of\n deserialized_json in a consistent (alphabetical) order.\n \"\"\"\n if isinstance(deserialized_json, dict):\n result = ''\n for key in sorted(deserialized_json):\n result += self.get_text(deserialized_json[key]) + ' '\n return result\n\n if isinstance(deserialized_json, list):\n result = ''\n for item in deserialized_json:\n result += self.get_text(item) + ' '\n return result\n\n if isinstance(deserialized_json, six.string_types):\n return deserialized_json\n else:\n return ''\n"
] | class Parser(BaseParser):
"""Extract all of the string values of a json file (no keys as those
are, in some sense, markup). This is useful for parsing content
from mongodb dumps, for example.
"""
def extract(self, filename, **kwargs):
with open(filename, 'r') as raw:
deserialized_json = json.load(raw)
return self.get_text(deserialized_json)
|
deanmalmgren/textract | textract/parsers/pdf_parser.py | Parser.extract_pdftotext | python | def extract_pdftotext(self, filename, **kwargs):
if 'layout' in kwargs:
args = ['pdftotext', '-layout', filename, '-']
else:
args = ['pdftotext', filename, '-']
stdout, _ = self.run(args)
return stdout | Extract text from pdfs using the pdftotext command line utility. | train | https://github.com/deanmalmgren/textract/blob/117ea191d93d80321e4bf01f23cc1ac54d69a075/textract/parsers/pdf_parser.py#L37-L44 | [
"def run(self, args):\n \"\"\"Run ``command`` and return the subsequent ``stdout`` and ``stderr``\n as a tuple. If the command is not successful, this raises a\n :exc:`textract.exceptions.ShellError`.\n \"\"\"\n\n # run a subprocess and put the stdout and stderr on the pipe object\n try:\n pipe = subprocess.Popen(\n args,\n stdout=subprocess.PIPE, stderr=subprocess.PIPE,\n )\n except OSError as e:\n if e.errno == errno.ENOENT:\n # File not found.\n # This is equivalent to getting exitcode 127 from sh\n raise exceptions.ShellError(\n ' '.join(args), 127, '', '',\n )\n\n # pipe.wait() ends up hanging on large files. using\n # pipe.communicate appears to avoid this issue\n stdout, stderr = pipe.communicate()\n\n # if pipe is busted, raise an error (unlike Fabric)\n if pipe.returncode != 0:\n raise exceptions.ShellError(\n ' '.join(args), pipe.returncode, stdout, stderr,\n )\n\n return stdout, stderr\n"
] | class Parser(ShellParser):
"""Extract text from pdf files using either the ``pdftotext`` method
(default) or the ``pdfminer`` method.
"""
def extract(self, filename, method='', **kwargs):
if method == '' or method == 'pdftotext':
try:
return self.extract_pdftotext(filename, **kwargs)
except ShellError as ex:
# If pdftotext isn't installed and the pdftotext method
# wasn't specified, then gracefully fallback to using
# pdfminer instead.
if method == '' and ex.is_not_installed():
return self.extract_pdfminer(filename, **kwargs)
else:
raise ex
elif method == 'pdfminer':
return self.extract_pdfminer(filename, **kwargs)
elif method == 'tesseract':
return self.extract_tesseract(filename, **kwargs)
else:
raise UnknownMethod(method)
def extract_pdfminer(self, filename, **kwargs):
"""Extract text from pdfs using pdfminer."""
stdout, _ = self.run(['pdf2txt.py', filename])
return stdout
def extract_tesseract(self, filename, **kwargs):
"""Extract text from pdfs using tesseract (per-page OCR)."""
temp_dir = mkdtemp()
base = os.path.join(temp_dir, 'conv')
contents = []
try:
stdout, _ = self.run(['pdftoppm', filename, base])
for page in sorted(os.listdir(temp_dir)):
page_path = os.path.join(temp_dir, page)
page_content = TesseractParser().extract(page_path, **kwargs)
contents.append(page_content)
return six.b('').join(contents)
finally:
shutil.rmtree(temp_dir)
|
deanmalmgren/textract | textract/parsers/pdf_parser.py | Parser.extract_pdfminer | python | def extract_pdfminer(self, filename, **kwargs):
stdout, _ = self.run(['pdf2txt.py', filename])
return stdout | Extract text from pdfs using pdfminer. | train | https://github.com/deanmalmgren/textract/blob/117ea191d93d80321e4bf01f23cc1ac54d69a075/textract/parsers/pdf_parser.py#L46-L49 | [
"def run(self, args):\n \"\"\"Run ``command`` and return the subsequent ``stdout`` and ``stderr``\n as a tuple. If the command is not successful, this raises a\n :exc:`textract.exceptions.ShellError`.\n \"\"\"\n\n # run a subprocess and put the stdout and stderr on the pipe object\n try:\n pipe = subprocess.Popen(\n args,\n stdout=subprocess.PIPE, stderr=subprocess.PIPE,\n )\n except OSError as e:\n if e.errno == errno.ENOENT:\n # File not found.\n # This is equivalent to getting exitcode 127 from sh\n raise exceptions.ShellError(\n ' '.join(args), 127, '', '',\n )\n\n # pipe.wait() ends up hanging on large files. using\n # pipe.communicate appears to avoid this issue\n stdout, stderr = pipe.communicate()\n\n # if pipe is busted, raise an error (unlike Fabric)\n if pipe.returncode != 0:\n raise exceptions.ShellError(\n ' '.join(args), pipe.returncode, stdout, stderr,\n )\n\n return stdout, stderr\n"
] | class Parser(ShellParser):
"""Extract text from pdf files using either the ``pdftotext`` method
(default) or the ``pdfminer`` method.
"""
def extract(self, filename, method='', **kwargs):
if method == '' or method == 'pdftotext':
try:
return self.extract_pdftotext(filename, **kwargs)
except ShellError as ex:
# If pdftotext isn't installed and the pdftotext method
# wasn't specified, then gracefully fallback to using
# pdfminer instead.
if method == '' and ex.is_not_installed():
return self.extract_pdfminer(filename, **kwargs)
else:
raise ex
elif method == 'pdfminer':
return self.extract_pdfminer(filename, **kwargs)
elif method == 'tesseract':
return self.extract_tesseract(filename, **kwargs)
else:
raise UnknownMethod(method)
def extract_pdftotext(self, filename, **kwargs):
"""Extract text from pdfs using the pdftotext command line utility."""
if 'layout' in kwargs:
args = ['pdftotext', '-layout', filename, '-']
else:
args = ['pdftotext', filename, '-']
stdout, _ = self.run(args)
return stdout
def extract_tesseract(self, filename, **kwargs):
"""Extract text from pdfs using tesseract (per-page OCR)."""
temp_dir = mkdtemp()
base = os.path.join(temp_dir, 'conv')
contents = []
try:
stdout, _ = self.run(['pdftoppm', filename, base])
for page in sorted(os.listdir(temp_dir)):
page_path = os.path.join(temp_dir, page)
page_content = TesseractParser().extract(page_path, **kwargs)
contents.append(page_content)
return six.b('').join(contents)
finally:
shutil.rmtree(temp_dir)
|
deanmalmgren/textract | textract/parsers/pdf_parser.py | Parser.extract_tesseract | python | def extract_tesseract(self, filename, **kwargs):
temp_dir = mkdtemp()
base = os.path.join(temp_dir, 'conv')
contents = []
try:
stdout, _ = self.run(['pdftoppm', filename, base])
for page in sorted(os.listdir(temp_dir)):
page_path = os.path.join(temp_dir, page)
page_content = TesseractParser().extract(page_path, **kwargs)
contents.append(page_content)
return six.b('').join(contents)
finally:
shutil.rmtree(temp_dir) | Extract text from pdfs using tesseract (per-page OCR). | train | https://github.com/deanmalmgren/textract/blob/117ea191d93d80321e4bf01f23cc1ac54d69a075/textract/parsers/pdf_parser.py#L51-L65 | [
"def extract(self, filename, **kwargs):\n\n # if language given as argument, specify language for tesseract to use\n if 'language' in kwargs:\n args = ['tesseract', filename, 'stdout', '-l', kwargs['language']]\n else:\n args = ['tesseract', filename, 'stdout']\n\n stdout, _ = self.run(args)\n return stdout\n",
"def run(self, args):\n \"\"\"Run ``command`` and return the subsequent ``stdout`` and ``stderr``\n as a tuple. If the command is not successful, this raises a\n :exc:`textract.exceptions.ShellError`.\n \"\"\"\n\n # run a subprocess and put the stdout and stderr on the pipe object\n try:\n pipe = subprocess.Popen(\n args,\n stdout=subprocess.PIPE, stderr=subprocess.PIPE,\n )\n except OSError as e:\n if e.errno == errno.ENOENT:\n # File not found.\n # This is equivalent to getting exitcode 127 from sh\n raise exceptions.ShellError(\n ' '.join(args), 127, '', '',\n )\n\n # pipe.wait() ends up hanging on large files. using\n # pipe.communicate appears to avoid this issue\n stdout, stderr = pipe.communicate()\n\n # if pipe is busted, raise an error (unlike Fabric)\n if pipe.returncode != 0:\n raise exceptions.ShellError(\n ' '.join(args), pipe.returncode, stdout, stderr,\n )\n\n return stdout, stderr\n"
] | class Parser(ShellParser):
"""Extract text from pdf files using either the ``pdftotext`` method
(default) or the ``pdfminer`` method.
"""
def extract(self, filename, method='', **kwargs):
if method == '' or method == 'pdftotext':
try:
return self.extract_pdftotext(filename, **kwargs)
except ShellError as ex:
# If pdftotext isn't installed and the pdftotext method
# wasn't specified, then gracefully fallback to using
# pdfminer instead.
if method == '' and ex.is_not_installed():
return self.extract_pdfminer(filename, **kwargs)
else:
raise ex
elif method == 'pdfminer':
return self.extract_pdfminer(filename, **kwargs)
elif method == 'tesseract':
return self.extract_tesseract(filename, **kwargs)
else:
raise UnknownMethod(method)
def extract_pdftotext(self, filename, **kwargs):
"""Extract text from pdfs using the pdftotext command line utility."""
if 'layout' in kwargs:
args = ['pdftotext', '-layout', filename, '-']
else:
args = ['pdftotext', filename, '-']
stdout, _ = self.run(args)
return stdout
def extract_pdfminer(self, filename, **kwargs):
"""Extract text from pdfs using pdfminer."""
stdout, _ = self.run(['pdf2txt.py', filename])
return stdout
|
deanmalmgren/textract | textract/parsers/audio.py | Parser.convert_to_wav | python | def convert_to_wav(self, filename):
temp_filename = '{0}.wav'.format(self.temp_filename())
self.run(['sox', '-G', '-c', '1', filename, temp_filename])
return temp_filename | Uses sox cmdline tool, to convert audio file to .wav
Note: for testing, use -
http://www.text2speech.org/,
with American Male 2 for best results | train | https://github.com/deanmalmgren/textract/blob/117ea191d93d80321e4bf01f23cc1ac54d69a075/textract/parsers/audio.py#L56-L66 | [
"def run(self, args):\n \"\"\"Run ``command`` and return the subsequent ``stdout`` and ``stderr``\n as a tuple. If the command is not successful, this raises a\n :exc:`textract.exceptions.ShellError`.\n \"\"\"\n\n # run a subprocess and put the stdout and stderr on the pipe object\n try:\n pipe = subprocess.Popen(\n args,\n stdout=subprocess.PIPE, stderr=subprocess.PIPE,\n )\n except OSError as e:\n if e.errno == errno.ENOENT:\n # File not found.\n # This is equivalent to getting exitcode 127 from sh\n raise exceptions.ShellError(\n ' '.join(args), 127, '', '',\n )\n\n # pipe.wait() ends up hanging on large files. using\n # pipe.communicate appears to avoid this issue\n stdout, stderr = pipe.communicate()\n\n # if pipe is busted, raise an error (unlike Fabric)\n if pipe.returncode != 0:\n raise exceptions.ShellError(\n ' '.join(args), pipe.returncode, stdout, stderr,\n )\n\n return stdout, stderr\n",
"def temp_filename(self):\n \"\"\"Return a unique tempfile name.\n \"\"\"\n # TODO: it would be nice to get this to behave more like a\n # context so we can make sure these temporary files are\n # removed, regardless of whether an error occurs or the\n # program is terminated.\n handle, filename = tempfile.mkstemp()\n os.close(handle)\n return filename\n"
] | class Parser(ShellParser):
"""
Extract text (i.e. speech) from an audio file, using SpeechRecognition.
Since SpeechRecognition expects a .wav file, with 1 channel,
the audio file has to be converted, via sox, if not compliant
Note: for testing, use -
http://www2.research.att.com/~ttsweb/tts/demo.php,
with Rich (US English) for best results
"""
def extract(self, filename, method='', **kwargs):
speech = ''
# convert to wav, if not already .wav
base, ext = os.path.splitext(filename)
if ext != '.wav':
temp_filename = self.convert_to_wav(filename)
try:
speech = self.extract(temp_filename, method, **kwargs)
finally: # make sure temp_file is deleted
os.remove(temp_filename)
else:
r = sr.Recognizer()
with sr.WavFile(filename) as source:
audio = r.record(source)
try:
if method == 'google' or method == '':
speech = r.recognize_google(audio)
elif method == 'sphinx':
speech = r.recognize_sphinx(audio)
else:
raise UnknownMethod(method)
except LookupError: # audio is not understandable
speech = ''
except sr.UnknownValueError:
speech = ''
except sr.RequestError as e:
speech = ''
# add a newline, to make output cleaner
speech += '\n'
return speech
|
deanmalmgren/textract | textract/parsers/html_parser.py | Parser._visible | python | def _visible(self, element):
if element.name in self._disallowed_names:
return False
elif re.match(u'<!--.*-->', six.text_type(element.extract())):
return False
return True | Used to filter text elements that have invisible text on the page. | train | https://github.com/deanmalmgren/textract/blob/117ea191d93d80321e4bf01f23cc1ac54d69a075/textract/parsers/html_parser.py#L27-L34 | null | class Parser(BaseParser):
"""Extract text from html file using beautifulsoup4. Filter text to
only show the visible parts of the page. Insipration from `here
<http://stackoverflow.com/a/1983219/564709>`_.
"""
_disallowed_names = [
'style', 'script', '[document]', 'head', 'title', 'html', 'meta',
'link', 'body',
]
_inline_tags = [
'b', 'big', 'i', 'small', 'tt', 'abbr', 'acronym', 'cite', 'code',
'dfn', 'em', 'kbd', 'strong', 'samp', 'var', 'a', 'bdo', 'br', 'img',
'map', 'object', 'q', 'script', 'span', 'sub', 'sup', 'button',
'input', 'label', 'select', 'textarea',
]
def _inline(self, element):
"""Used to check whether given element can be treated as inline
element (without new line after).
"""
if element.name in self._inline_tags:
return True
return False
def _find_any_text(self, tag):
"""Looks for any possible text within given tag.
"""
text = ''
if tag is not None:
text = six.text_type(tag)
text = re.sub(r'(<[^>]+>)', '', text)
text = re.sub(r'\s', ' ', text)
text = text.strip()
return text
def _parse_tables(self, soup):
"""Returns array containing basic informations about tables for ASCII
replacement (look: _replace_tables()).
"""
tables = []
for t in soup.find_all('table'):
t_dict = {'width': 0, 'table': t, 'trs': [], 'col_width': {}}
trs = t.find_all('tr')
if len(trs) > 0:
for tr in trs:
tr_dict = []
tds = tr.find_all('th') + tr.find_all('td')
if len(tds) > 0:
for i, td in enumerate(tds):
td_text = self._find_any_text(td)
length = len(td_text)
if i in t_dict['col_width']:
t_dict['col_width'][i] = max(
length,
t_dict['col_width'][i]
)
else:
t_dict['col_width'][i] = length
tr_dict.append({
'text': td_text,
'colspan': int(td.get('colspan', 1)),
})
t_dict['trs'].append(tr_dict)
for col in t_dict['col_width']:
t_dict['width'] += t_dict['col_width'][col]
tables.append(t_dict)
return tables
def _replace_tables(self, soup, v_separator=' | ', h_separator='-'):
"""Replaces <table> elements with its ASCII equivalent.
"""
tables = self._parse_tables(soup)
v_sep_len = len(v_separator)
v_left_sep = v_separator.lstrip()
for t in tables:
html = ''
trs = t['trs']
h_length = 1 + (v_sep_len * len(t['col_width'])) + t['width']
head_foot = (h_separator * h_length) + "\n"
html += head_foot
for tr in trs:
html += v_left_sep
for i, td in enumerate(tr):
text = td['text']
col_width = t['col_width'][i] + v_sep_len
if td['colspan'] > 1:
for j in range(td['colspan']-1):
j = j + 1
if (i+j) < len(t['col_width']):
col_width += t['col_width'][i+j] + v_sep_len
html += ('%' + str(col_width) + 's') % (text + v_separator)
html += "\n"
html += head_foot
new_table = soup.new_tag('div')
new_table.string = html
t['table'].replace_with(new_table)
return soup
def _join_inlines(self, soup):
"""Unwraps inline elements defined in self._inline_tags.
"""
elements = soup.find_all(True)
for elem in elements:
if self._inline(elem):
elem.unwrap()
return soup
def extract(self, filename, **kwargs):
with open(filename, "rb") as stream:
soup = BeautifulSoup(stream, 'lxml')
# Convert tables to ASCII ones
soup = self._replace_tables(soup)
# Join inline elements
soup = self._join_inlines(soup)
# Make HTML
html = ''
elements = soup.find_all(True)
elements = [el for el in filter(self._visible, elements)]
for elem in elements:
string = elem.string
if string is None:
string = self._find_any_text(elem)
string = string.strip()
if len(string) > 0:
html += "\n" + string + "\n"
return html
|
deanmalmgren/textract | textract/parsers/html_parser.py | Parser._find_any_text | python | def _find_any_text(self, tag):
text = ''
if tag is not None:
text = six.text_type(tag)
text = re.sub(r'(<[^>]+>)', '', text)
text = re.sub(r'\s', ' ', text)
text = text.strip()
return text | Looks for any possible text within given tag. | train | https://github.com/deanmalmgren/textract/blob/117ea191d93d80321e4bf01f23cc1ac54d69a075/textract/parsers/html_parser.py#L44-L53 | null | class Parser(BaseParser):
"""Extract text from html file using beautifulsoup4. Filter text to
only show the visible parts of the page. Insipration from `here
<http://stackoverflow.com/a/1983219/564709>`_.
"""
_disallowed_names = [
'style', 'script', '[document]', 'head', 'title', 'html', 'meta',
'link', 'body',
]
_inline_tags = [
'b', 'big', 'i', 'small', 'tt', 'abbr', 'acronym', 'cite', 'code',
'dfn', 'em', 'kbd', 'strong', 'samp', 'var', 'a', 'bdo', 'br', 'img',
'map', 'object', 'q', 'script', 'span', 'sub', 'sup', 'button',
'input', 'label', 'select', 'textarea',
]
def _visible(self, element):
"""Used to filter text elements that have invisible text on the page.
"""
if element.name in self._disallowed_names:
return False
elif re.match(u'<!--.*-->', six.text_type(element.extract())):
return False
return True
def _inline(self, element):
"""Used to check whether given element can be treated as inline
element (without new line after).
"""
if element.name in self._inline_tags:
return True
return False
def _parse_tables(self, soup):
"""Returns array containing basic informations about tables for ASCII
replacement (look: _replace_tables()).
"""
tables = []
for t in soup.find_all('table'):
t_dict = {'width': 0, 'table': t, 'trs': [], 'col_width': {}}
trs = t.find_all('tr')
if len(trs) > 0:
for tr in trs:
tr_dict = []
tds = tr.find_all('th') + tr.find_all('td')
if len(tds) > 0:
for i, td in enumerate(tds):
td_text = self._find_any_text(td)
length = len(td_text)
if i in t_dict['col_width']:
t_dict['col_width'][i] = max(
length,
t_dict['col_width'][i]
)
else:
t_dict['col_width'][i] = length
tr_dict.append({
'text': td_text,
'colspan': int(td.get('colspan', 1)),
})
t_dict['trs'].append(tr_dict)
for col in t_dict['col_width']:
t_dict['width'] += t_dict['col_width'][col]
tables.append(t_dict)
return tables
def _replace_tables(self, soup, v_separator=' | ', h_separator='-'):
"""Replaces <table> elements with its ASCII equivalent.
"""
tables = self._parse_tables(soup)
v_sep_len = len(v_separator)
v_left_sep = v_separator.lstrip()
for t in tables:
html = ''
trs = t['trs']
h_length = 1 + (v_sep_len * len(t['col_width'])) + t['width']
head_foot = (h_separator * h_length) + "\n"
html += head_foot
for tr in trs:
html += v_left_sep
for i, td in enumerate(tr):
text = td['text']
col_width = t['col_width'][i] + v_sep_len
if td['colspan'] > 1:
for j in range(td['colspan']-1):
j = j + 1
if (i+j) < len(t['col_width']):
col_width += t['col_width'][i+j] + v_sep_len
html += ('%' + str(col_width) + 's') % (text + v_separator)
html += "\n"
html += head_foot
new_table = soup.new_tag('div')
new_table.string = html
t['table'].replace_with(new_table)
return soup
def _join_inlines(self, soup):
"""Unwraps inline elements defined in self._inline_tags.
"""
elements = soup.find_all(True)
for elem in elements:
if self._inline(elem):
elem.unwrap()
return soup
def extract(self, filename, **kwargs):
with open(filename, "rb") as stream:
soup = BeautifulSoup(stream, 'lxml')
# Convert tables to ASCII ones
soup = self._replace_tables(soup)
# Join inline elements
soup = self._join_inlines(soup)
# Make HTML
html = ''
elements = soup.find_all(True)
elements = [el for el in filter(self._visible, elements)]
for elem in elements:
string = elem.string
if string is None:
string = self._find_any_text(elem)
string = string.strip()
if len(string) > 0:
html += "\n" + string + "\n"
return html
|
deanmalmgren/textract | textract/parsers/html_parser.py | Parser._parse_tables | python | def _parse_tables(self, soup):
tables = []
for t in soup.find_all('table'):
t_dict = {'width': 0, 'table': t, 'trs': [], 'col_width': {}}
trs = t.find_all('tr')
if len(trs) > 0:
for tr in trs:
tr_dict = []
tds = tr.find_all('th') + tr.find_all('td')
if len(tds) > 0:
for i, td in enumerate(tds):
td_text = self._find_any_text(td)
length = len(td_text)
if i in t_dict['col_width']:
t_dict['col_width'][i] = max(
length,
t_dict['col_width'][i]
)
else:
t_dict['col_width'][i] = length
tr_dict.append({
'text': td_text,
'colspan': int(td.get('colspan', 1)),
})
t_dict['trs'].append(tr_dict)
for col in t_dict['col_width']:
t_dict['width'] += t_dict['col_width'][col]
tables.append(t_dict)
return tables | Returns array containing basic informations about tables for ASCII
replacement (look: _replace_tables()). | train | https://github.com/deanmalmgren/textract/blob/117ea191d93d80321e4bf01f23cc1ac54d69a075/textract/parsers/html_parser.py#L55-L86 | null | class Parser(BaseParser):
"""Extract text from html file using beautifulsoup4. Filter text to
only show the visible parts of the page. Insipration from `here
<http://stackoverflow.com/a/1983219/564709>`_.
"""
_disallowed_names = [
'style', 'script', '[document]', 'head', 'title', 'html', 'meta',
'link', 'body',
]
_inline_tags = [
'b', 'big', 'i', 'small', 'tt', 'abbr', 'acronym', 'cite', 'code',
'dfn', 'em', 'kbd', 'strong', 'samp', 'var', 'a', 'bdo', 'br', 'img',
'map', 'object', 'q', 'script', 'span', 'sub', 'sup', 'button',
'input', 'label', 'select', 'textarea',
]
def _visible(self, element):
"""Used to filter text elements that have invisible text on the page.
"""
if element.name in self._disallowed_names:
return False
elif re.match(u'<!--.*-->', six.text_type(element.extract())):
return False
return True
def _inline(self, element):
"""Used to check whether given element can be treated as inline
element (without new line after).
"""
if element.name in self._inline_tags:
return True
return False
def _find_any_text(self, tag):
"""Looks for any possible text within given tag.
"""
text = ''
if tag is not None:
text = six.text_type(tag)
text = re.sub(r'(<[^>]+>)', '', text)
text = re.sub(r'\s', ' ', text)
text = text.strip()
return text
def _replace_tables(self, soup, v_separator=' | ', h_separator='-'):
"""Replaces <table> elements with its ASCII equivalent.
"""
tables = self._parse_tables(soup)
v_sep_len = len(v_separator)
v_left_sep = v_separator.lstrip()
for t in tables:
html = ''
trs = t['trs']
h_length = 1 + (v_sep_len * len(t['col_width'])) + t['width']
head_foot = (h_separator * h_length) + "\n"
html += head_foot
for tr in trs:
html += v_left_sep
for i, td in enumerate(tr):
text = td['text']
col_width = t['col_width'][i] + v_sep_len
if td['colspan'] > 1:
for j in range(td['colspan']-1):
j = j + 1
if (i+j) < len(t['col_width']):
col_width += t['col_width'][i+j] + v_sep_len
html += ('%' + str(col_width) + 's') % (text + v_separator)
html += "\n"
html += head_foot
new_table = soup.new_tag('div')
new_table.string = html
t['table'].replace_with(new_table)
return soup
def _join_inlines(self, soup):
"""Unwraps inline elements defined in self._inline_tags.
"""
elements = soup.find_all(True)
for elem in elements:
if self._inline(elem):
elem.unwrap()
return soup
def extract(self, filename, **kwargs):
with open(filename, "rb") as stream:
soup = BeautifulSoup(stream, 'lxml')
# Convert tables to ASCII ones
soup = self._replace_tables(soup)
# Join inline elements
soup = self._join_inlines(soup)
# Make HTML
html = ''
elements = soup.find_all(True)
elements = [el for el in filter(self._visible, elements)]
for elem in elements:
string = elem.string
if string is None:
string = self._find_any_text(elem)
string = string.strip()
if len(string) > 0:
html += "\n" + string + "\n"
return html
|
deanmalmgren/textract | textract/parsers/html_parser.py | Parser._replace_tables | python | def _replace_tables(self, soup, v_separator=' | ', h_separator='-'):
tables = self._parse_tables(soup)
v_sep_len = len(v_separator)
v_left_sep = v_separator.lstrip()
for t in tables:
html = ''
trs = t['trs']
h_length = 1 + (v_sep_len * len(t['col_width'])) + t['width']
head_foot = (h_separator * h_length) + "\n"
html += head_foot
for tr in trs:
html += v_left_sep
for i, td in enumerate(tr):
text = td['text']
col_width = t['col_width'][i] + v_sep_len
if td['colspan'] > 1:
for j in range(td['colspan']-1):
j = j + 1
if (i+j) < len(t['col_width']):
col_width += t['col_width'][i+j] + v_sep_len
html += ('%' + str(col_width) + 's') % (text + v_separator)
html += "\n"
html += head_foot
new_table = soup.new_tag('div')
new_table.string = html
t['table'].replace_with(new_table)
return soup | Replaces <table> elements with its ASCII equivalent. | train | https://github.com/deanmalmgren/textract/blob/117ea191d93d80321e4bf01f23cc1ac54d69a075/textract/parsers/html_parser.py#L88-L116 | [
"def _parse_tables(self, soup):\n \"\"\"Returns array containing basic informations about tables for ASCII\n replacement (look: _replace_tables()).\n \"\"\"\n tables = []\n for t in soup.find_all('table'):\n t_dict = {'width': 0, 'table': t, 'trs': [], 'col_width': {}}\n trs = t.find_all('tr')\n if len(trs) > 0:\n for tr in trs:\n tr_dict = []\n tds = tr.find_all('th') + tr.find_all('td')\n if len(tds) > 0:\n for i, td in enumerate(tds):\n td_text = self._find_any_text(td)\n length = len(td_text)\n if i in t_dict['col_width']:\n t_dict['col_width'][i] = max(\n length,\n t_dict['col_width'][i]\n )\n else:\n t_dict['col_width'][i] = length\n tr_dict.append({\n 'text': td_text,\n 'colspan': int(td.get('colspan', 1)),\n })\n t_dict['trs'].append(tr_dict)\n for col in t_dict['col_width']:\n t_dict['width'] += t_dict['col_width'][col]\n tables.append(t_dict)\n return tables\n"
] | class Parser(BaseParser):
"""Extract text from html file using beautifulsoup4. Filter text to
only show the visible parts of the page. Insipration from `here
<http://stackoverflow.com/a/1983219/564709>`_.
"""
_disallowed_names = [
'style', 'script', '[document]', 'head', 'title', 'html', 'meta',
'link', 'body',
]
_inline_tags = [
'b', 'big', 'i', 'small', 'tt', 'abbr', 'acronym', 'cite', 'code',
'dfn', 'em', 'kbd', 'strong', 'samp', 'var', 'a', 'bdo', 'br', 'img',
'map', 'object', 'q', 'script', 'span', 'sub', 'sup', 'button',
'input', 'label', 'select', 'textarea',
]
def _visible(self, element):
"""Used to filter text elements that have invisible text on the page.
"""
if element.name in self._disallowed_names:
return False
elif re.match(u'<!--.*-->', six.text_type(element.extract())):
return False
return True
def _inline(self, element):
"""Used to check whether given element can be treated as inline
element (without new line after).
"""
if element.name in self._inline_tags:
return True
return False
def _find_any_text(self, tag):
"""Looks for any possible text within given tag.
"""
text = ''
if tag is not None:
text = six.text_type(tag)
text = re.sub(r'(<[^>]+>)', '', text)
text = re.sub(r'\s', ' ', text)
text = text.strip()
return text
def _parse_tables(self, soup):
"""Returns array containing basic informations about tables for ASCII
replacement (look: _replace_tables()).
"""
tables = []
for t in soup.find_all('table'):
t_dict = {'width': 0, 'table': t, 'trs': [], 'col_width': {}}
trs = t.find_all('tr')
if len(trs) > 0:
for tr in trs:
tr_dict = []
tds = tr.find_all('th') + tr.find_all('td')
if len(tds) > 0:
for i, td in enumerate(tds):
td_text = self._find_any_text(td)
length = len(td_text)
if i in t_dict['col_width']:
t_dict['col_width'][i] = max(
length,
t_dict['col_width'][i]
)
else:
t_dict['col_width'][i] = length
tr_dict.append({
'text': td_text,
'colspan': int(td.get('colspan', 1)),
})
t_dict['trs'].append(tr_dict)
for col in t_dict['col_width']:
t_dict['width'] += t_dict['col_width'][col]
tables.append(t_dict)
return tables
def _join_inlines(self, soup):
"""Unwraps inline elements defined in self._inline_tags.
"""
elements = soup.find_all(True)
for elem in elements:
if self._inline(elem):
elem.unwrap()
return soup
def extract(self, filename, **kwargs):
with open(filename, "rb") as stream:
soup = BeautifulSoup(stream, 'lxml')
# Convert tables to ASCII ones
soup = self._replace_tables(soup)
# Join inline elements
soup = self._join_inlines(soup)
# Make HTML
html = ''
elements = soup.find_all(True)
elements = [el for el in filter(self._visible, elements)]
for elem in elements:
string = elem.string
if string is None:
string = self._find_any_text(elem)
string = string.strip()
if len(string) > 0:
html += "\n" + string + "\n"
return html
|
deanmalmgren/textract | textract/parsers/html_parser.py | Parser._join_inlines | python | def _join_inlines(self, soup):
elements = soup.find_all(True)
for elem in elements:
if self._inline(elem):
elem.unwrap()
return soup | Unwraps inline elements defined in self._inline_tags. | train | https://github.com/deanmalmgren/textract/blob/117ea191d93d80321e4bf01f23cc1ac54d69a075/textract/parsers/html_parser.py#L118-L125 | [
"def _inline(self, element):\n \"\"\"Used to check whether given element can be treated as inline\n element (without new line after).\n \"\"\"\n if element.name in self._inline_tags:\n return True\n return False\n"
] | class Parser(BaseParser):
"""Extract text from html file using beautifulsoup4. Filter text to
only show the visible parts of the page. Insipration from `here
<http://stackoverflow.com/a/1983219/564709>`_.
"""
_disallowed_names = [
'style', 'script', '[document]', 'head', 'title', 'html', 'meta',
'link', 'body',
]
_inline_tags = [
'b', 'big', 'i', 'small', 'tt', 'abbr', 'acronym', 'cite', 'code',
'dfn', 'em', 'kbd', 'strong', 'samp', 'var', 'a', 'bdo', 'br', 'img',
'map', 'object', 'q', 'script', 'span', 'sub', 'sup', 'button',
'input', 'label', 'select', 'textarea',
]
def _visible(self, element):
"""Used to filter text elements that have invisible text on the page.
"""
if element.name in self._disallowed_names:
return False
elif re.match(u'<!--.*-->', six.text_type(element.extract())):
return False
return True
def _inline(self, element):
"""Used to check whether given element can be treated as inline
element (without new line after).
"""
if element.name in self._inline_tags:
return True
return False
def _find_any_text(self, tag):
"""Looks for any possible text within given tag.
"""
text = ''
if tag is not None:
text = six.text_type(tag)
text = re.sub(r'(<[^>]+>)', '', text)
text = re.sub(r'\s', ' ', text)
text = text.strip()
return text
def _parse_tables(self, soup):
"""Returns array containing basic informations about tables for ASCII
replacement (look: _replace_tables()).
"""
tables = []
for t in soup.find_all('table'):
t_dict = {'width': 0, 'table': t, 'trs': [], 'col_width': {}}
trs = t.find_all('tr')
if len(trs) > 0:
for tr in trs:
tr_dict = []
tds = tr.find_all('th') + tr.find_all('td')
if len(tds) > 0:
for i, td in enumerate(tds):
td_text = self._find_any_text(td)
length = len(td_text)
if i in t_dict['col_width']:
t_dict['col_width'][i] = max(
length,
t_dict['col_width'][i]
)
else:
t_dict['col_width'][i] = length
tr_dict.append({
'text': td_text,
'colspan': int(td.get('colspan', 1)),
})
t_dict['trs'].append(tr_dict)
for col in t_dict['col_width']:
t_dict['width'] += t_dict['col_width'][col]
tables.append(t_dict)
return tables
def _replace_tables(self, soup, v_separator=' | ', h_separator='-'):
"""Replaces <table> elements with its ASCII equivalent.
"""
tables = self._parse_tables(soup)
v_sep_len = len(v_separator)
v_left_sep = v_separator.lstrip()
for t in tables:
html = ''
trs = t['trs']
h_length = 1 + (v_sep_len * len(t['col_width'])) + t['width']
head_foot = (h_separator * h_length) + "\n"
html += head_foot
for tr in trs:
html += v_left_sep
for i, td in enumerate(tr):
text = td['text']
col_width = t['col_width'][i] + v_sep_len
if td['colspan'] > 1:
for j in range(td['colspan']-1):
j = j + 1
if (i+j) < len(t['col_width']):
col_width += t['col_width'][i+j] + v_sep_len
html += ('%' + str(col_width) + 's') % (text + v_separator)
html += "\n"
html += head_foot
new_table = soup.new_tag('div')
new_table.string = html
t['table'].replace_with(new_table)
return soup
def extract(self, filename, **kwargs):
with open(filename, "rb") as stream:
soup = BeautifulSoup(stream, 'lxml')
# Convert tables to ASCII ones
soup = self._replace_tables(soup)
# Join inline elements
soup = self._join_inlines(soup)
# Make HTML
html = ''
elements = soup.find_all(True)
elements = [el for el in filter(self._visible, elements)]
for elem in elements:
string = elem.string
if string is None:
string = self._find_any_text(elem)
string = string.strip()
if len(string) > 0:
html += "\n" + string + "\n"
return html
|
deanmalmgren/textract | textract/parsers/utils.py | BaseParser.process | python | def process(self, filename, encoding, **kwargs):
# make a "unicode sandwich" to handle dealing with unknown
# input byte strings and converting them to a predictable
# output encoding
# http://nedbatchelder.com/text/unipain/unipain.html#35
byte_string = self.extract(filename, **kwargs)
unicode_string = self.decode(byte_string)
return self.encode(unicode_string, encoding) | Process ``filename`` and encode byte-string with ``encoding``. This
method is called by :func:`textract.parsers.process` and wraps
the :meth:`.BaseParser.extract` method in `a delicious unicode
sandwich <http://nedbatchelder.com/text/unipain.html>`_. | train | https://github.com/deanmalmgren/textract/blob/117ea191d93d80321e4bf01f23cc1ac54d69a075/textract/parsers/utils.py#L35-L48 | [
"def extract(self, filename, **kwargs):\n \"\"\"This method must be overwritten by child classes to extract raw\n text from a filename. This method can return either a\n byte-encoded string or unicode.\n \"\"\"\n raise NotImplementedError('must be overwritten by child classes')\n",
"def encode(self, text, encoding):\n \"\"\"Encode the ``text`` in ``encoding`` byte-encoding. This ignores\n code points that can't be encoded in byte-strings.\n \"\"\"\n return text.encode(encoding, 'ignore')\n",
"def decode(self, text):\n \"\"\"Decode ``text`` using the `chardet\n <https://github.com/chardet/chardet>`_ package.\n \"\"\"\n # only decode byte strings into unicode if it hasn't already\n # been done by a subclass\n if isinstance(text, six.text_type):\n return text\n\n # empty text? nothing to decode\n if not text:\n return u''\n\n # use chardet to automatically detect the encoding text\n result = chardet.detect(text)\n return text.decode(result['encoding'])\n"
] | class BaseParser(object):
"""The :class:`.BaseParser` abstracts out some common functionality
that is used across all document Parsers. In particular, it has
the responsibility of handling all unicode and byte-encoding.
"""
def extract(self, filename, **kwargs):
"""This method must be overwritten by child classes to extract raw
text from a filename. This method can return either a
byte-encoded string or unicode.
"""
raise NotImplementedError('must be overwritten by child classes')
def encode(self, text, encoding):
"""Encode the ``text`` in ``encoding`` byte-encoding. This ignores
code points that can't be encoded in byte-strings.
"""
return text.encode(encoding, 'ignore')
def decode(self, text):
"""Decode ``text`` using the `chardet
<https://github.com/chardet/chardet>`_ package.
"""
# only decode byte strings into unicode if it hasn't already
# been done by a subclass
if isinstance(text, six.text_type):
return text
# empty text? nothing to decode
if not text:
return u''
# use chardet to automatically detect the encoding text
result = chardet.detect(text)
return text.decode(result['encoding'])
|
deanmalmgren/textract | textract/parsers/utils.py | BaseParser.decode | python | def decode(self, text):
# only decode byte strings into unicode if it hasn't already
# been done by a subclass
if isinstance(text, six.text_type):
return text
# empty text? nothing to decode
if not text:
return u''
# use chardet to automatically detect the encoding text
result = chardet.detect(text)
return text.decode(result['encoding']) | Decode ``text`` using the `chardet
<https://github.com/chardet/chardet>`_ package. | train | https://github.com/deanmalmgren/textract/blob/117ea191d93d80321e4bf01f23cc1ac54d69a075/textract/parsers/utils.py#L50-L65 | null | class BaseParser(object):
"""The :class:`.BaseParser` abstracts out some common functionality
that is used across all document Parsers. In particular, it has
the responsibility of handling all unicode and byte-encoding.
"""
def extract(self, filename, **kwargs):
"""This method must be overwritten by child classes to extract raw
text from a filename. This method can return either a
byte-encoded string or unicode.
"""
raise NotImplementedError('must be overwritten by child classes')
def encode(self, text, encoding):
"""Encode the ``text`` in ``encoding`` byte-encoding. This ignores
code points that can't be encoded in byte-strings.
"""
return text.encode(encoding, 'ignore')
def process(self, filename, encoding, **kwargs):
"""Process ``filename`` and encode byte-string with ``encoding``. This
method is called by :func:`textract.parsers.process` and wraps
the :meth:`.BaseParser.extract` method in `a delicious unicode
sandwich <http://nedbatchelder.com/text/unipain.html>`_.
"""
# make a "unicode sandwich" to handle dealing with unknown
# input byte strings and converting them to a predictable
# output encoding
# http://nedbatchelder.com/text/unipain/unipain.html#35
byte_string = self.extract(filename, **kwargs)
unicode_string = self.decode(byte_string)
return self.encode(unicode_string, encoding)
|
deanmalmgren/textract | textract/parsers/utils.py | ShellParser.run | python | def run(self, args):
# run a subprocess and put the stdout and stderr on the pipe object
try:
pipe = subprocess.Popen(
args,
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
)
except OSError as e:
if e.errno == errno.ENOENT:
# File not found.
# This is equivalent to getting exitcode 127 from sh
raise exceptions.ShellError(
' '.join(args), 127, '', '',
)
# pipe.wait() ends up hanging on large files. using
# pipe.communicate appears to avoid this issue
stdout, stderr = pipe.communicate()
# if pipe is busted, raise an error (unlike Fabric)
if pipe.returncode != 0:
raise exceptions.ShellError(
' '.join(args), pipe.returncode, stdout, stderr,
)
return stdout, stderr | Run ``command`` and return the subsequent ``stdout`` and ``stderr``
as a tuple. If the command is not successful, this raises a
:exc:`textract.exceptions.ShellError`. | train | https://github.com/deanmalmgren/textract/blob/117ea191d93d80321e4bf01f23cc1ac54d69a075/textract/parsers/utils.py#L74-L104 | null | class ShellParser(BaseParser):
"""The :class:`.ShellParser` extends the :class:`.BaseParser` to make
it easy to run external programs from the command line with
`Fabric <http://www.fabfile.org/>`_-like behavior.
"""
def temp_filename(self):
"""Return a unique tempfile name.
"""
# TODO: it would be nice to get this to behave more like a
# context so we can make sure these temporary files are
# removed, regardless of whether an error occurs or the
# program is terminated.
handle, filename = tempfile.mkstemp()
os.close(handle)
return filename
|
deanmalmgren/textract | textract/parsers/utils.py | ShellParser.temp_filename | python | def temp_filename(self):
# TODO: it would be nice to get this to behave more like a
# context so we can make sure these temporary files are
# removed, regardless of whether an error occurs or the
# program is terminated.
handle, filename = tempfile.mkstemp()
os.close(handle)
return filename | Return a unique tempfile name. | train | https://github.com/deanmalmgren/textract/blob/117ea191d93d80321e4bf01f23cc1ac54d69a075/textract/parsers/utils.py#L106-L115 | null | class ShellParser(BaseParser):
"""The :class:`.ShellParser` extends the :class:`.BaseParser` to make
it easy to run external programs from the command line with
`Fabric <http://www.fabfile.org/>`_-like behavior.
"""
def run(self, args):
"""Run ``command`` and return the subsequent ``stdout`` and ``stderr``
as a tuple. If the command is not successful, this raises a
:exc:`textract.exceptions.ShellError`.
"""
# run a subprocess and put the stdout and stderr on the pipe object
try:
pipe = subprocess.Popen(
args,
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
)
except OSError as e:
if e.errno == errno.ENOENT:
# File not found.
# This is equivalent to getting exitcode 127 from sh
raise exceptions.ShellError(
' '.join(args), 127, '', '',
)
# pipe.wait() ends up hanging on large files. using
# pipe.communicate appears to avoid this issue
stdout, stderr = pipe.communicate()
# if pipe is busted, raise an error (unlike Fabric)
if pipe.returncode != 0:
raise exceptions.ShellError(
' '.join(args), pipe.returncode, stdout, stderr,
)
return stdout, stderr
|
deanmalmgren/textract | textract/parsers/__init__.py | process | python | def process(filename, encoding=DEFAULT_ENCODING, extension=None, **kwargs):
# make sure the filename exists
if not os.path.exists(filename):
raise exceptions.MissingFileError(filename)
# get the filename extension, which is something like .docx for
# example, and import the module dynamically using importlib. This
# is a relative import so the name of the package is necessary
# normally, file extension will be extracted from the file name
# if the file name has no extension, then the user can pass the
# extension as an argument
if extension:
ext = extension
# check if the extension has the leading .
if not ext.startswith('.'):
ext = '.' + ext
ext = ext.lower()
else:
_, ext = os.path.splitext(filename)
ext = ext.lower()
# check the EXTENSION_SYNONYMS dictionary
ext = EXTENSION_SYNONYMS.get(ext, ext)
# to avoid conflicts with packages that are installed globally
# (e.g. python's json module), all extension parser modules have
# the _parser extension
rel_module = ext + _FILENAME_SUFFIX
# If we can't import the module, the file extension isn't currently
# supported
try:
filetype_module = importlib.import_module(
rel_module, 'textract.parsers'
)
except ImportError:
raise exceptions.ExtensionNotSupported(ext)
# do the extraction
parser = filetype_module.Parser()
return parser.process(filename, encoding, **kwargs) | This is the core function used for extracting text. It routes the
``filename`` to the appropriate parser and returns the extracted
text as a byte-string encoded with ``encoding``. | train | https://github.com/deanmalmgren/textract/blob/117ea191d93d80321e4bf01f23cc1ac54d69a075/textract/parsers/__init__.py#L31-L77 | null | """
Route the request to the appropriate parser based on file type.
"""
import os
import importlib
import glob
import re
from .. import exceptions
# Dictionary structure for synonymous file extension types
EXTENSION_SYNONYMS = {
".jpeg": ".jpg",
".tff": ".tiff",
".tif": ".tiff",
".htm": ".html",
"": ".txt",
".log": ".txt",
}
# default encoding that is returned by the process method. specify it
# here so the default is used on both the process function and also by
# the command line interface
DEFAULT_ENCODING = 'utf_8'
# filename format
_FILENAME_SUFFIX = '_parser'
def _get_available_extensions():
"""Get a list of available file extensions to make it easy for
tab-completion and exception handling.
"""
extensions = []
# from filenames
parsers_dir = os.path.join(os.path.dirname(__file__))
glob_filename = os.path.join(parsers_dir, "*" + _FILENAME_SUFFIX + ".py")
ext_re = re.compile(glob_filename.replace('*', "(?P<ext>\w+)"))
for filename in glob.glob(glob_filename):
ext_match = ext_re.match(filename)
ext = ext_match.groups()[0]
extensions.append(ext)
extensions.append('.' + ext)
# from relevant synonyms (don't use the '' synonym)
for ext in EXTENSION_SYNONYMS.keys():
if ext:
extensions.append(ext)
extensions.append(ext.replace('.', '', 1))
extensions.sort()
return extensions
|
deanmalmgren/textract | textract/parsers/__init__.py | _get_available_extensions | python | def _get_available_extensions():
extensions = []
# from filenames
parsers_dir = os.path.join(os.path.dirname(__file__))
glob_filename = os.path.join(parsers_dir, "*" + _FILENAME_SUFFIX + ".py")
ext_re = re.compile(glob_filename.replace('*', "(?P<ext>\w+)"))
for filename in glob.glob(glob_filename):
ext_match = ext_re.match(filename)
ext = ext_match.groups()[0]
extensions.append(ext)
extensions.append('.' + ext)
# from relevant synonyms (don't use the '' synonym)
for ext in EXTENSION_SYNONYMS.keys():
if ext:
extensions.append(ext)
extensions.append(ext.replace('.', '', 1))
extensions.sort()
return extensions | Get a list of available file extensions to make it easy for
tab-completion and exception handling. | train | https://github.com/deanmalmgren/textract/blob/117ea191d93d80321e4bf01f23cc1ac54d69a075/textract/parsers/__init__.py#L80-L102 | null | """
Route the request to the appropriate parser based on file type.
"""
import os
import importlib
import glob
import re
from .. import exceptions
# Dictionary structure for synonymous file extension types
EXTENSION_SYNONYMS = {
".jpeg": ".jpg",
".tff": ".tiff",
".tif": ".tiff",
".htm": ".html",
"": ".txt",
".log": ".txt",
}
# default encoding that is returned by the process method. specify it
# here so the default is used on both the process function and also by
# the command line interface
DEFAULT_ENCODING = 'utf_8'
# filename format
_FILENAME_SUFFIX = '_parser'
def process(filename, encoding=DEFAULT_ENCODING, extension=None, **kwargs):
"""This is the core function used for extracting text. It routes the
``filename`` to the appropriate parser and returns the extracted
text as a byte-string encoded with ``encoding``.
"""
# make sure the filename exists
if not os.path.exists(filename):
raise exceptions.MissingFileError(filename)
# get the filename extension, which is something like .docx for
# example, and import the module dynamically using importlib. This
# is a relative import so the name of the package is necessary
# normally, file extension will be extracted from the file name
# if the file name has no extension, then the user can pass the
# extension as an argument
if extension:
ext = extension
# check if the extension has the leading .
if not ext.startswith('.'):
ext = '.' + ext
ext = ext.lower()
else:
_, ext = os.path.splitext(filename)
ext = ext.lower()
# check the EXTENSION_SYNONYMS dictionary
ext = EXTENSION_SYNONYMS.get(ext, ext)
# to avoid conflicts with packages that are installed globally
# (e.g. python's json module), all extension parser modules have
# the _parser extension
rel_module = ext + _FILENAME_SUFFIX
# If we can't import the module, the file extension isn't currently
# supported
try:
filetype_module = importlib.import_module(
rel_module, 'textract.parsers'
)
except ImportError:
raise exceptions.ExtensionNotSupported(ext)
# do the extraction
parser = filetype_module.Parser()
return parser.process(filename, encoding, **kwargs)
|
deanmalmgren/textract | setup.py | parse_requirements | python | def parse_requirements(requirements_filename):
dependencies, dependency_links = [], []
requirements_dir = os.path.dirname(requirements_filename)
with open(requirements_filename, 'r') as stream:
for line in stream:
line = line.strip()
if line.startswith("-r"):
filename = os.path.join(requirements_dir, line[2:].strip())
_dependencies, _dependency_links = parse_requirements(filename)
dependencies.extend(_dependencies)
dependency_links.extend(_dependency_links)
elif line.startswith("http"):
dependency_links.append(line)
else:
package = line.split('#')[0]
if package:
dependencies.append(package)
return dependencies, dependency_links | read in the dependencies from the requirements files | train | https://github.com/deanmalmgren/textract/blob/117ea191d93d80321e4bf01f23cc1ac54d69a075/setup.py#L18-L37 | null | import glob
import os
import sys
from setuptools import setup
import textract
# get all of the scripts
scripts = glob.glob("bin/*")
# read in the description from README
with open("README.rst") as stream:
long_description = stream.read()
github_url = 'https://github.com/deanmalmgren/textract'
requirements_filename = os.path.join("requirements", "python")
dependencies, dependency_links = parse_requirements(requirements_filename)
setup(
name=textract.__name__,
version="1.6.1",
description="extract text from any document. no muss. no fuss.",
long_description=long_description,
url=github_url,
download_url="%s/archives/master" % github_url,
author='Dean Malmgren',
author_email='dean.malmgren@datascopeanalytics.com',
license='MIT',
scripts=scripts,
packages=[
'textract',
'textract.parsers',
],
install_requires=dependencies,
dependency_links=dependency_links,
zip_safe=False,
)
|
PyCQA/pyflakes | pyflakes/reporter.py | Reporter.syntaxError | python | def syntaxError(self, filename, msg, lineno, offset, text):
line = text.splitlines()[-1]
if offset is not None:
if sys.version_info < (3, 8):
offset = offset - (len(text) - len(line)) + 1
self._stderr.write('%s:%d:%d: %s\n' %
(filename, lineno, offset, msg))
else:
self._stderr.write('%s:%d: %s\n' % (filename, lineno, msg))
self._stderr.write(line)
self._stderr.write('\n')
if offset is not None:
self._stderr.write(re.sub(r'\S', ' ', line[:offset - 1]) +
"^\n") | There was a syntax error in C{filename}.
@param filename: The path to the file with the syntax error.
@ptype filename: C{unicode}
@param msg: An explanation of the syntax error.
@ptype msg: C{unicode}
@param lineno: The line number where the syntax error occurred.
@ptype lineno: C{int}
@param offset: The column on which the syntax error occurred, or None.
@ptype offset: C{int}
@param text: The source code containing the syntax error.
@ptype text: C{unicode} | train | https://github.com/PyCQA/pyflakes/blob/232cb1d27ee134bf96adc8f37e53589dc259b159/pyflakes/reporter.py#L39-L66 | null | class Reporter(object):
"""
Formats the results of pyflakes checks to users.
"""
def __init__(self, warningStream, errorStream):
"""
Construct a L{Reporter}.
@param warningStream: A file-like object where warnings will be
written to. The stream's C{write} method must accept unicode.
C{sys.stdout} is a good value.
@param errorStream: A file-like object where error output will be
written to. The stream's C{write} method must accept unicode.
C{sys.stderr} is a good value.
"""
self._stdout = warningStream
self._stderr = errorStream
def unexpectedError(self, filename, msg):
"""
An unexpected error occurred trying to process C{filename}.
@param filename: The path to a file that we could not process.
@ptype filename: C{unicode}
@param msg: A message explaining the problem.
@ptype msg: C{unicode}
"""
self._stderr.write("%s: %s\n" % (filename, msg))
def flake(self, message):
"""
pyflakes found something wrong with the code.
@param: A L{pyflakes.messages.Message}.
"""
self._stdout.write(str(message))
self._stdout.write('\n')
|
PyCQA/pyflakes | pyflakes/reporter.py | Reporter.flake | python | def flake(self, message):
self._stdout.write(str(message))
self._stdout.write('\n') | pyflakes found something wrong with the code.
@param: A L{pyflakes.messages.Message}. | train | https://github.com/PyCQA/pyflakes/blob/232cb1d27ee134bf96adc8f37e53589dc259b159/pyflakes/reporter.py#L68-L75 | null | class Reporter(object):
"""
Formats the results of pyflakes checks to users.
"""
def __init__(self, warningStream, errorStream):
"""
Construct a L{Reporter}.
@param warningStream: A file-like object where warnings will be
written to. The stream's C{write} method must accept unicode.
C{sys.stdout} is a good value.
@param errorStream: A file-like object where error output will be
written to. The stream's C{write} method must accept unicode.
C{sys.stderr} is a good value.
"""
self._stdout = warningStream
self._stderr = errorStream
def unexpectedError(self, filename, msg):
"""
An unexpected error occurred trying to process C{filename}.
@param filename: The path to a file that we could not process.
@ptype filename: C{unicode}
@param msg: A message explaining the problem.
@ptype msg: C{unicode}
"""
self._stderr.write("%s: %s\n" % (filename, msg))
def syntaxError(self, filename, msg, lineno, offset, text):
"""
There was a syntax error in C{filename}.
@param filename: The path to the file with the syntax error.
@ptype filename: C{unicode}
@param msg: An explanation of the syntax error.
@ptype msg: C{unicode}
@param lineno: The line number where the syntax error occurred.
@ptype lineno: C{int}
@param offset: The column on which the syntax error occurred, or None.
@ptype offset: C{int}
@param text: The source code containing the syntax error.
@ptype text: C{unicode}
"""
line = text.splitlines()[-1]
if offset is not None:
if sys.version_info < (3, 8):
offset = offset - (len(text) - len(line)) + 1
self._stderr.write('%s:%d:%d: %s\n' %
(filename, lineno, offset, msg))
else:
self._stderr.write('%s:%d: %s\n' % (filename, lineno, msg))
self._stderr.write(line)
self._stderr.write('\n')
if offset is not None:
self._stderr.write(re.sub(r'\S', ' ', line[:offset - 1]) +
"^\n")
|
PyCQA/pyflakes | pyflakes/checker.py | counter | python | def counter(items):
results = {}
for item in items:
results[item] = results.get(item, 0) + 1
return results | Simplest required implementation of collections.Counter. Required as 2.6
does not have Counter in collections. | train | https://github.com/PyCQA/pyflakes/blob/232cb1d27ee134bf96adc8f37e53589dc259b159/pyflakes/checker.py#L103-L111 | null | """
Main module.
Implement the central Checker class.
Also, it models the Bindings and Scopes.
"""
import __future__
import ast
import bisect
import collections
import doctest
import functools
import os
import re
import sys
import tokenize
from pyflakes import messages
PY2 = sys.version_info < (3, 0)
PY35_PLUS = sys.version_info >= (3, 5) # Python 3.5 and above
PY36_PLUS = sys.version_info >= (3, 6) # Python 3.6 and above
PY38_PLUS = sys.version_info >= (3, 8)
try:
sys.pypy_version_info
PYPY = True
except AttributeError:
PYPY = False
builtin_vars = dir(__import__('__builtin__' if PY2 else 'builtins'))
if PY2:
tokenize_tokenize = tokenize.generate_tokens
else:
tokenize_tokenize = tokenize.tokenize
if PY2:
def getNodeType(node_class):
# workaround str.upper() which is locale-dependent
return str(unicode(node_class.__name__).upper())
def get_raise_argument(node):
return node.type
else:
def getNodeType(node_class):
return node_class.__name__.upper()
def get_raise_argument(node):
return node.exc
# Silence `pyflakes` from reporting `undefined name 'unicode'` in Python 3.
unicode = str
# Python >= 3.3 uses ast.Try instead of (ast.TryExcept + ast.TryFinally)
if PY2:
def getAlternatives(n):
if isinstance(n, (ast.If, ast.TryFinally)):
return [n.body]
if isinstance(n, ast.TryExcept):
return [n.body + n.orelse] + [[hdl] for hdl in n.handlers]
else:
def getAlternatives(n):
if isinstance(n, ast.If):
return [n.body]
if isinstance(n, ast.Try):
return [n.body + n.orelse] + [[hdl] for hdl in n.handlers]
if PY35_PLUS:
FOR_TYPES = (ast.For, ast.AsyncFor)
LOOP_TYPES = (ast.While, ast.For, ast.AsyncFor)
else:
FOR_TYPES = (ast.For,)
LOOP_TYPES = (ast.While, ast.For)
# https://github.com/python/typed_ast/blob/55420396/ast27/Parser/tokenizer.c#L102-L104
TYPE_COMMENT_RE = re.compile(r'^#\s*type:\s*')
# https://github.com/python/typed_ast/blob/55420396/ast27/Parser/tokenizer.c#L1400
TYPE_IGNORE_RE = re.compile(TYPE_COMMENT_RE.pattern + r'ignore\s*(#|$)')
# https://github.com/python/typed_ast/blob/55420396/ast27/Grammar/Grammar#L147
TYPE_FUNC_RE = re.compile(r'^(\(.*?\))\s*->\s*(.*)$')
class _FieldsOrder(dict):
"""Fix order of AST node fields."""
def _get_fields(self, node_class):
# handle iter before target, and generators before element
fields = node_class._fields
if 'iter' in fields:
key_first = 'iter'.find
elif 'generators' in fields:
key_first = 'generators'.find
else:
key_first = 'value'.find
return tuple(sorted(fields, key=key_first, reverse=True))
def __missing__(self, node_class):
self[node_class] = fields = self._get_fields(node_class)
return fields
def iter_child_nodes(node, omit=None, _fields_order=_FieldsOrder()):
"""
Yield all direct child nodes of *node*, that is, all fields that
are nodes and all items of fields that are lists of nodes.
:param node: AST node to be iterated upon
:param omit: String or tuple of strings denoting the
attributes of the node to be omitted from
further parsing
:param _fields_order: Order of AST node fields
"""
for name in _fields_order[node.__class__]:
if omit and name in omit:
continue
field = getattr(node, name, None)
if isinstance(field, ast.AST):
yield field
elif isinstance(field, list):
for item in field:
yield item
def convert_to_value(item):
if isinstance(item, ast.Str):
return item.s
elif hasattr(ast, 'Bytes') and isinstance(item, ast.Bytes):
return item.s
elif isinstance(item, ast.Tuple):
return tuple(convert_to_value(i) for i in item.elts)
elif isinstance(item, ast.Num):
return item.n
elif isinstance(item, ast.Name):
result = VariableKey(item=item)
constants_lookup = {
'True': True,
'False': False,
'None': None,
}
return constants_lookup.get(
result.name,
result,
)
elif (not PY2) and isinstance(item, ast.NameConstant):
# None, True, False are nameconstants in python3, but names in 2
return item.value
else:
return UnhandledKeyType()
def is_notimplemented_name_node(node):
return isinstance(node, ast.Name) and getNodeName(node) == 'NotImplemented'
class Binding(object):
"""
Represents the binding of a value to a name.
The checker uses this to keep track of which names have been bound and
which names have not. See L{Assignment} for a special type of binding that
is checked with stricter rules.
@ivar used: pair of (L{Scope}, node) indicating the scope and
the node that this binding was last used.
"""
def __init__(self, name, source):
self.name = name
self.source = source
self.used = False
def __str__(self):
return self.name
def __repr__(self):
return '<%s object %r from line %r at 0x%x>' % (self.__class__.__name__,
self.name,
self.source.lineno,
id(self))
def redefines(self, other):
return isinstance(other, Definition) and self.name == other.name
class Definition(Binding):
"""
A binding that defines a function or a class.
"""
class Builtin(Definition):
"""A definition created for all Python builtins."""
def __init__(self, name):
super(Builtin, self).__init__(name, None)
def __repr__(self):
return '<%s object %r at 0x%x>' % (self.__class__.__name__,
self.name,
id(self))
class UnhandledKeyType(object):
"""
A dictionary key of a type that we cannot or do not check for duplicates.
"""
class VariableKey(object):
"""
A dictionary key which is a variable.
@ivar item: The variable AST object.
"""
def __init__(self, item):
self.name = item.id
def __eq__(self, compare):
return (
compare.__class__ == self.__class__ and
compare.name == self.name
)
def __hash__(self):
return hash(self.name)
class Importation(Definition):
"""
A binding created by an import statement.
@ivar fullName: The complete name given to the import statement,
possibly including multiple dotted components.
@type fullName: C{str}
"""
def __init__(self, name, source, full_name=None):
self.fullName = full_name or name
self.redefined = []
super(Importation, self).__init__(name, source)
def redefines(self, other):
if isinstance(other, SubmoduleImportation):
# See note in SubmoduleImportation about RedefinedWhileUnused
return self.fullName == other.fullName
return isinstance(other, Definition) and self.name == other.name
def _has_alias(self):
"""Return whether importation needs an as clause."""
return not self.fullName.split('.')[-1] == self.name
@property
def source_statement(self):
"""Generate a source statement equivalent to the import."""
if self._has_alias():
return 'import %s as %s' % (self.fullName, self.name)
else:
return 'import %s' % self.fullName
def __str__(self):
"""Return import full name with alias."""
if self._has_alias():
return self.fullName + ' as ' + self.name
else:
return self.fullName
class SubmoduleImportation(Importation):
"""
A binding created by a submodule import statement.
A submodule import is a special case where the root module is implicitly
imported, without an 'as' clause, and the submodule is also imported.
Python does not restrict which attributes of the root module may be used.
This class is only used when the submodule import is without an 'as' clause.
pyflakes handles this case by registering the root module name in the scope,
allowing any attribute of the root module to be accessed.
RedefinedWhileUnused is suppressed in `redefines` unless the submodule
name is also the same, to avoid false positives.
"""
def __init__(self, name, source):
# A dot should only appear in the name when it is a submodule import
assert '.' in name and (not source or isinstance(source, ast.Import))
package_name = name.split('.')[0]
super(SubmoduleImportation, self).__init__(package_name, source)
self.fullName = name
def redefines(self, other):
if isinstance(other, Importation):
return self.fullName == other.fullName
return super(SubmoduleImportation, self).redefines(other)
def __str__(self):
return self.fullName
@property
def source_statement(self):
return 'import ' + self.fullName
class ImportationFrom(Importation):
def __init__(self, name, source, module, real_name=None):
self.module = module
self.real_name = real_name or name
if module.endswith('.'):
full_name = module + self.real_name
else:
full_name = module + '.' + self.real_name
super(ImportationFrom, self).__init__(name, source, full_name)
def __str__(self):
"""Return import full name with alias."""
if self.real_name != self.name:
return self.fullName + ' as ' + self.name
else:
return self.fullName
@property
def source_statement(self):
if self.real_name != self.name:
return 'from %s import %s as %s' % (self.module,
self.real_name,
self.name)
else:
return 'from %s import %s' % (self.module, self.name)
class StarImportation(Importation):
"""A binding created by a 'from x import *' statement."""
def __init__(self, name, source):
super(StarImportation, self).__init__('*', source)
# Each star importation needs a unique name, and
# may not be the module name otherwise it will be deemed imported
self.name = name + '.*'
self.fullName = name
@property
def source_statement(self):
return 'from ' + self.fullName + ' import *'
def __str__(self):
# When the module ends with a ., avoid the ambiguous '..*'
if self.fullName.endswith('.'):
return self.source_statement
else:
return self.name
class FutureImportation(ImportationFrom):
"""
A binding created by a from `__future__` import statement.
`__future__` imports are implicitly used.
"""
def __init__(self, name, source, scope):
super(FutureImportation, self).__init__(name, source, '__future__')
self.used = (scope, source)
class Argument(Binding):
"""
Represents binding a name as an argument.
"""
class Assignment(Binding):
"""
Represents binding a name with an explicit assignment.
The checker will raise warnings for any Assignment that isn't used. Also,
the checker does not consider assignments in tuple/list unpacking to be
Assignments, rather it treats them as simple Bindings.
"""
class FunctionDefinition(Definition):
pass
class ClassDefinition(Definition):
pass
class ExportBinding(Binding):
"""
A binding created by an C{__all__} assignment. If the names in the list
can be determined statically, they will be treated as names for export and
additional checking applied to them.
The only recognized C{__all__} assignment via list concatenation is in the
following format:
__all__ = ['a'] + ['b'] + ['c']
Names which are imported and not otherwise used but appear in the value of
C{__all__} will not have an unused import warning reported for them.
"""
def __init__(self, name, source, scope):
if '__all__' in scope and isinstance(source, ast.AugAssign):
self.names = list(scope['__all__'].names)
else:
self.names = []
def _add_to_names(container):
for node in container.elts:
if isinstance(node, ast.Str):
self.names.append(node.s)
if isinstance(source.value, (ast.List, ast.Tuple)):
_add_to_names(source.value)
# If concatenating lists
elif isinstance(source.value, ast.BinOp):
currentValue = source.value
while isinstance(currentValue.right, ast.List):
left = currentValue.left
right = currentValue.right
_add_to_names(right)
# If more lists are being added
if isinstance(left, ast.BinOp):
currentValue = left
# If just two lists are being added
elif isinstance(left, ast.List):
_add_to_names(left)
# All lists accounted for - done
break
# If not list concatenation
else:
break
super(ExportBinding, self).__init__(name, source)
class Scope(dict):
importStarred = False # set to True when import * is found
def __repr__(self):
scope_cls = self.__class__.__name__
return '<%s at 0x%x %s>' % (scope_cls, id(self), dict.__repr__(self))
class ClassScope(Scope):
pass
class FunctionScope(Scope):
"""
I represent a name scope for a function.
@ivar globals: Names declared 'global' in this function.
"""
usesLocals = False
alwaysUsed = {'__tracebackhide__', '__traceback_info__',
'__traceback_supplement__'}
def __init__(self):
super(FunctionScope, self).__init__()
# Simplify: manage the special locals as globals
self.globals = self.alwaysUsed.copy()
self.returnValue = None # First non-empty return
self.isGenerator = False # Detect a generator
def unusedAssignments(self):
"""
Return a generator for the assignments which have not been used.
"""
for name, binding in self.items():
if (not binding.used and
name != '_' and # see issue #202
name not in self.globals and
not self.usesLocals and
isinstance(binding, Assignment)):
yield name, binding
class GeneratorScope(Scope):
pass
class ModuleScope(Scope):
"""Scope for a module."""
_futures_allowed = True
_annotations_future_enabled = False
class DoctestScope(ModuleScope):
"""Scope for a doctest."""
class DummyNode(object):
"""Used in place of an `ast.AST` to set error message positions"""
def __init__(self, lineno, col_offset):
self.lineno = lineno
self.col_offset = col_offset
# Globally defined names which are not attributes of the builtins module, or
# are only present on some platforms.
_MAGIC_GLOBALS = ['__file__', '__builtins__', 'WindowsError']
# module scope annotation will store in `__annotations__`, see also PEP 526.
if PY36_PLUS:
_MAGIC_GLOBALS.append('__annotations__')
def getNodeName(node):
# Returns node.id, or node.name, or None
if hasattr(node, 'id'): # One of the many nodes with an id
return node.id
if hasattr(node, 'name'): # an ExceptHandler node
return node.name
def is_typing_overload(value, scope_stack):
def name_is_typing_overload(name): # type: (str) -> bool
for scope in reversed(scope_stack):
if name in scope:
return (
isinstance(scope[name], ImportationFrom) and
scope[name].fullName == 'typing.overload'
)
else:
return False
def is_typing_overload_decorator(node):
return (
(
isinstance(node, ast.Name) and name_is_typing_overload(node.id)
) or (
isinstance(node, ast.Attribute) and
isinstance(node.value, ast.Name) and
node.value.id == 'typing' and
node.attr == 'overload'
)
)
return (
isinstance(value.source, ast.FunctionDef) and
any(
is_typing_overload_decorator(dec)
for dec in value.source.decorator_list
)
)
def make_tokens(code):
# PY3: tokenize.tokenize requires readline of bytes
if not isinstance(code, bytes):
code = code.encode('UTF-8')
lines = iter(code.splitlines(True))
# next(lines, b'') is to prevent an error in pypy3
return tuple(tokenize_tokenize(lambda: next(lines, b'')))
class _TypeableVisitor(ast.NodeVisitor):
"""Collect the line number and nodes which are deemed typeable by
PEP 484
https://www.python.org/dev/peps/pep-0484/#type-comments
"""
def __init__(self):
self.typeable_lines = [] # type: List[int]
self.typeable_nodes = {} # type: Dict[int, ast.AST]
def _typeable(self, node):
# if there is more than one typeable thing on a line last one wins
self.typeable_lines.append(node.lineno)
self.typeable_nodes[node.lineno] = node
self.generic_visit(node)
visit_Assign = visit_For = visit_FunctionDef = visit_With = _typeable
visit_AsyncFor = visit_AsyncFunctionDef = visit_AsyncWith = _typeable
def _collect_type_comments(tree, tokens):
visitor = _TypeableVisitor()
visitor.visit(tree)
type_comments = collections.defaultdict(list)
for tp, text, start, _, _ in tokens:
if (
tp != tokenize.COMMENT or # skip non comments
not TYPE_COMMENT_RE.match(text) or # skip non-type comments
TYPE_IGNORE_RE.match(text) # skip ignores
):
continue
# search for the typeable node at or before the line number of the
# type comment.
# if the bisection insertion point is before any nodes this is an
# invalid type comment which is ignored.
lineno, _ = start
idx = bisect.bisect_right(visitor.typeable_lines, lineno)
if idx == 0:
continue
node = visitor.typeable_nodes[visitor.typeable_lines[idx - 1]]
type_comments[node].append((start, text))
return type_comments
class Checker(object):
"""
I check the cleanliness and sanity of Python code.
@ivar _deferredFunctions: Tracking list used by L{deferFunction}. Elements
of the list are two-tuples. The first element is the callable passed
to L{deferFunction}. The second element is a copy of the scope stack
at the time L{deferFunction} was called.
@ivar _deferredAssignments: Similar to C{_deferredFunctions}, but for
callables which are deferred assignment checks.
"""
_ast_node_scope = {
ast.Module: ModuleScope,
ast.ClassDef: ClassScope,
ast.FunctionDef: FunctionScope,
ast.Lambda: FunctionScope,
ast.ListComp: GeneratorScope,
ast.SetComp: GeneratorScope,
ast.GeneratorExp: GeneratorScope,
ast.DictComp: GeneratorScope,
}
if PY35_PLUS:
_ast_node_scope[ast.AsyncFunctionDef] = FunctionScope,
nodeDepth = 0
offset = None
traceTree = False
builtIns = set(builtin_vars).union(_MAGIC_GLOBALS)
_customBuiltIns = os.environ.get('PYFLAKES_BUILTINS')
if _customBuiltIns:
builtIns.update(_customBuiltIns.split(','))
del _customBuiltIns
# TODO: file_tokens= is required to perform checks on type comments,
# eventually make this a required positional argument. For now it
# is defaulted to `()` for api compatibility.
def __init__(self, tree, filename='(none)', builtins=None,
withDoctest='PYFLAKES_DOCTEST' in os.environ, file_tokens=()):
self._nodeHandlers = {}
self._deferredFunctions = []
self._deferredAssignments = []
self.deadScopes = []
self.messages = []
self.filename = filename
if builtins:
self.builtIns = self.builtIns.union(builtins)
self.withDoctest = withDoctest
try:
self.scopeStack = [Checker._ast_node_scope[type(tree)]()]
except KeyError:
raise RuntimeError('No scope implemented for the node %r' % tree)
self.exceptHandlers = [()]
self.root = tree
self._type_comments = _collect_type_comments(tree, file_tokens)
for builtin in self.builtIns:
self.addBinding(None, Builtin(builtin))
self.handleChildren(tree)
self.runDeferred(self._deferredFunctions)
# Set _deferredFunctions to None so that deferFunction will fail
# noisily if called after we've run through the deferred functions.
self._deferredFunctions = None
self.runDeferred(self._deferredAssignments)
# Set _deferredAssignments to None so that deferAssignment will fail
# noisily if called after we've run through the deferred assignments.
self._deferredAssignments = None
del self.scopeStack[1:]
self.popScope()
self.checkDeadScopes()
def deferFunction(self, callable):
"""
Schedule a function handler to be called just before completion.
This is used for handling function bodies, which must be deferred
because code later in the file might modify the global scope. When
`callable` is called, the scope at the time this is called will be
restored, however it will contain any new bindings added to it.
"""
self._deferredFunctions.append((callable, self.scopeStack[:], self.offset))
def deferAssignment(self, callable):
"""
Schedule an assignment handler to be called just after deferred
function handlers.
"""
self._deferredAssignments.append((callable, self.scopeStack[:], self.offset))
def runDeferred(self, deferred):
"""
Run the callables in C{deferred} using their associated scope stack.
"""
for handler, scope, offset in deferred:
self.scopeStack = scope
self.offset = offset
handler()
def _in_doctest(self):
return (len(self.scopeStack) >= 2 and
isinstance(self.scopeStack[1], DoctestScope))
@property
def futuresAllowed(self):
if not all(isinstance(scope, ModuleScope)
for scope in self.scopeStack):
return False
return self.scope._futures_allowed
@futuresAllowed.setter
def futuresAllowed(self, value):
assert value is False
if isinstance(self.scope, ModuleScope):
self.scope._futures_allowed = False
@property
def annotationsFutureEnabled(self):
scope = self.scopeStack[0]
if not isinstance(scope, ModuleScope):
return False
return scope._annotations_future_enabled
@annotationsFutureEnabled.setter
def annotationsFutureEnabled(self, value):
assert value is True
assert isinstance(self.scope, ModuleScope)
self.scope._annotations_future_enabled = True
@property
def scope(self):
return self.scopeStack[-1]
def popScope(self):
self.deadScopes.append(self.scopeStack.pop())
def checkDeadScopes(self):
"""
Look at scopes which have been fully examined and report names in them
which were imported but unused.
"""
for scope in self.deadScopes:
# imports in classes are public members
if isinstance(scope, ClassScope):
continue
all_binding = scope.get('__all__')
if all_binding and not isinstance(all_binding, ExportBinding):
all_binding = None
if all_binding:
all_names = set(all_binding.names)
undefined = all_names.difference(scope)
else:
all_names = undefined = []
if undefined:
if not scope.importStarred and \
os.path.basename(self.filename) != '__init__.py':
# Look for possible mistakes in the export list
for name in undefined:
self.report(messages.UndefinedExport,
scope['__all__'].source, name)
# mark all import '*' as used by the undefined in __all__
if scope.importStarred:
from_list = []
for binding in scope.values():
if isinstance(binding, StarImportation):
binding.used = all_binding
from_list.append(binding.fullName)
# report * usage, with a list of possible sources
from_list = ', '.join(sorted(from_list))
for name in undefined:
self.report(messages.ImportStarUsage,
scope['__all__'].source, name, from_list)
# Look for imported names that aren't used.
for value in scope.values():
if isinstance(value, Importation):
used = value.used or value.name in all_names
if not used:
messg = messages.UnusedImport
self.report(messg, value.source, str(value))
for node in value.redefined:
if isinstance(self.getParent(node), FOR_TYPES):
messg = messages.ImportShadowedByLoopVar
elif used:
continue
else:
messg = messages.RedefinedWhileUnused
self.report(messg, node, value.name, value.source)
def pushScope(self, scopeClass=FunctionScope):
self.scopeStack.append(scopeClass())
def report(self, messageClass, *args, **kwargs):
self.messages.append(messageClass(self.filename, *args, **kwargs))
def getParent(self, node):
# Lookup the first parent which is not Tuple, List or Starred
while True:
node = node.parent
if not hasattr(node, 'elts') and not hasattr(node, 'ctx'):
return node
def getCommonAncestor(self, lnode, rnode, stop):
if stop in (lnode, rnode) or not (hasattr(lnode, 'parent') and
hasattr(rnode, 'parent')):
return None
if lnode is rnode:
return lnode
if (lnode.depth > rnode.depth):
return self.getCommonAncestor(lnode.parent, rnode, stop)
if (lnode.depth < rnode.depth):
return self.getCommonAncestor(lnode, rnode.parent, stop)
return self.getCommonAncestor(lnode.parent, rnode.parent, stop)
def descendantOf(self, node, ancestors, stop):
for a in ancestors:
if self.getCommonAncestor(node, a, stop):
return True
return False
def _getAncestor(self, node, ancestor_type):
parent = node
while True:
if parent is self.root:
return None
parent = self.getParent(parent)
if isinstance(parent, ancestor_type):
return parent
def getScopeNode(self, node):
return self._getAncestor(node, tuple(Checker._ast_node_scope.keys()))
def differentForks(self, lnode, rnode):
"""True, if lnode and rnode are located on different forks of IF/TRY"""
ancestor = self.getCommonAncestor(lnode, rnode, self.root)
parts = getAlternatives(ancestor)
if parts:
for items in parts:
if self.descendantOf(lnode, items, ancestor) ^ \
self.descendantOf(rnode, items, ancestor):
return True
return False
def addBinding(self, node, value):
"""
Called when a binding is altered.
- `node` is the statement responsible for the change
- `value` is the new value, a Binding instance
"""
# assert value.source in (node, node.parent):
for scope in self.scopeStack[::-1]:
if value.name in scope:
break
existing = scope.get(value.name)
if (existing and not isinstance(existing, Builtin) and
not self.differentForks(node, existing.source)):
parent_stmt = self.getParent(value.source)
if isinstance(existing, Importation) and isinstance(parent_stmt, FOR_TYPES):
self.report(messages.ImportShadowedByLoopVar,
node, value.name, existing.source)
elif scope is self.scope:
if (isinstance(parent_stmt, ast.comprehension) and
not isinstance(self.getParent(existing.source),
(FOR_TYPES, ast.comprehension))):
self.report(messages.RedefinedInListComp,
node, value.name, existing.source)
elif not existing.used and value.redefines(existing):
if value.name != '_' or isinstance(existing, Importation):
if not is_typing_overload(existing, self.scopeStack):
self.report(messages.RedefinedWhileUnused,
node, value.name, existing.source)
elif isinstance(existing, Importation) and value.redefines(existing):
existing.redefined.append(node)
if value.name in self.scope:
# then assume the rebound name is used as a global or within a loop
value.used = self.scope[value.name].used
self.scope[value.name] = value
def getNodeHandler(self, node_class):
try:
return self._nodeHandlers[node_class]
except KeyError:
nodeType = getNodeType(node_class)
self._nodeHandlers[node_class] = handler = getattr(self, nodeType)
return handler
def handleNodeLoad(self, node):
name = getNodeName(node)
if not name:
return
in_generators = None
importStarred = None
# try enclosing function scopes and global scope
for scope in self.scopeStack[-1::-1]:
if isinstance(scope, ClassScope):
if not PY2 and name == '__class__':
return
elif in_generators is False:
# only generators used in a class scope can access the
# names of the class. this is skipped during the first
# iteration
continue
if (name == 'print' and
isinstance(scope.get(name, None), Builtin)):
parent = self.getParent(node)
if (isinstance(parent, ast.BinOp) and
isinstance(parent.op, ast.RShift)):
self.report(messages.InvalidPrintSyntax, node)
try:
scope[name].used = (self.scope, node)
# if the name of SubImportation is same as
# alias of other Importation and the alias
# is used, SubImportation also should be marked as used.
n = scope[name]
if isinstance(n, Importation) and n._has_alias():
try:
scope[n.fullName].used = (self.scope, node)
except KeyError:
pass
except KeyError:
pass
else:
return
importStarred = importStarred or scope.importStarred
if in_generators is not False:
in_generators = isinstance(scope, GeneratorScope)
if importStarred:
from_list = []
for scope in self.scopeStack[-1::-1]:
for binding in scope.values():
if isinstance(binding, StarImportation):
# mark '*' imports as used for each scope
binding.used = (self.scope, node)
from_list.append(binding.fullName)
# report * usage, with a list of possible sources
from_list = ', '.join(sorted(from_list))
self.report(messages.ImportStarUsage, node, name, from_list)
return
if name == '__path__' and os.path.basename(self.filename) == '__init__.py':
# the special name __path__ is valid only in packages
return
if name == '__module__' and isinstance(self.scope, ClassScope):
return
# protected with a NameError handler?
if 'NameError' not in self.exceptHandlers[-1]:
self.report(messages.UndefinedName, node, name)
def handleNodeStore(self, node):
name = getNodeName(node)
if not name:
return
# if the name hasn't already been defined in the current scope
if isinstance(self.scope, FunctionScope) and name not in self.scope:
# for each function or module scope above us
for scope in self.scopeStack[:-1]:
if not isinstance(scope, (FunctionScope, ModuleScope)):
continue
# if the name was defined in that scope, and the name has
# been accessed already in the current scope, and hasn't
# been declared global
used = name in scope and scope[name].used
if used and used[0] is self.scope and name not in self.scope.globals:
# then it's probably a mistake
self.report(messages.UndefinedLocal,
scope[name].used[1], name, scope[name].source)
break
parent_stmt = self.getParent(node)
if isinstance(parent_stmt, (FOR_TYPES, ast.comprehension)) or (
parent_stmt != node.parent and
not self.isLiteralTupleUnpacking(parent_stmt)):
binding = Binding(name, node)
elif name == '__all__' and isinstance(self.scope, ModuleScope):
binding = ExportBinding(name, node.parent, self.scope)
elif isinstance(getattr(node, 'ctx', None), ast.Param):
binding = Argument(name, self.getScopeNode(node))
else:
binding = Assignment(name, node)
self.addBinding(node, binding)
def handleNodeDelete(self, node):
def on_conditional_branch():
"""
Return `True` if node is part of a conditional body.
"""
current = getattr(node, 'parent', None)
while current:
if isinstance(current, (ast.If, ast.While, ast.IfExp)):
return True
current = getattr(current, 'parent', None)
return False
name = getNodeName(node)
if not name:
return
if on_conditional_branch():
# We cannot predict if this conditional branch is going to
# be executed.
return
if isinstance(self.scope, FunctionScope) and name in self.scope.globals:
self.scope.globals.remove(name)
else:
try:
del self.scope[name]
except KeyError:
self.report(messages.UndefinedName, node, name)
def _handle_type_comments(self, node):
for (lineno, col_offset), comment in self._type_comments.get(node, ()):
comment = comment.split(':', 1)[1].strip()
func_match = TYPE_FUNC_RE.match(comment)
if func_match:
parts = (
func_match.group(1).replace('*', ''),
func_match.group(2).strip(),
)
else:
parts = (comment,)
for part in parts:
if PY2:
part = part.replace('...', 'Ellipsis')
self.deferFunction(functools.partial(
self.handleStringAnnotation,
part, DummyNode(lineno, col_offset), lineno, col_offset,
messages.CommentAnnotationSyntaxError,
))
def handleChildren(self, tree, omit=None):
self._handle_type_comments(tree)
for node in iter_child_nodes(tree, omit=omit):
self.handleNode(node, tree)
def isLiteralTupleUnpacking(self, node):
if isinstance(node, ast.Assign):
for child in node.targets + [node.value]:
if not hasattr(child, 'elts'):
return False
return True
def isDocstring(self, node):
"""
Determine if the given node is a docstring, as long as it is at the
correct place in the node tree.
"""
return isinstance(node, ast.Str) or (isinstance(node, ast.Expr) and
isinstance(node.value, ast.Str))
def getDocstring(self, node):
if isinstance(node, ast.Expr):
node = node.value
if not isinstance(node, ast.Str):
return (None, None)
if PYPY or PY38_PLUS:
doctest_lineno = node.lineno - 1
else:
# Computed incorrectly if the docstring has backslash
doctest_lineno = node.lineno - node.s.count('\n') - 1
return (node.s, doctest_lineno)
def handleNode(self, node, parent):
if node is None:
return
if self.offset and getattr(node, 'lineno', None) is not None:
node.lineno += self.offset[0]
node.col_offset += self.offset[1]
if self.traceTree:
print(' ' * self.nodeDepth + node.__class__.__name__)
if self.futuresAllowed and not (isinstance(node, ast.ImportFrom) or
self.isDocstring(node)):
self.futuresAllowed = False
self.nodeDepth += 1
node.depth = self.nodeDepth
node.parent = parent
try:
handler = self.getNodeHandler(node.__class__)
handler(node)
finally:
self.nodeDepth -= 1
if self.traceTree:
print(' ' * self.nodeDepth + 'end ' + node.__class__.__name__)
_getDoctestExamples = doctest.DocTestParser().get_examples
def handleDoctests(self, node):
try:
if hasattr(node, 'docstring'):
docstring = node.docstring
# This is just a reasonable guess. In Python 3.7, docstrings no
# longer have line numbers associated with them. This will be
# incorrect if there are empty lines between the beginning
# of the function and the docstring.
node_lineno = node.lineno
if hasattr(node, 'args'):
node_lineno = max([node_lineno] +
[arg.lineno for arg in node.args.args])
else:
(docstring, node_lineno) = self.getDocstring(node.body[0])
examples = docstring and self._getDoctestExamples(docstring)
except (ValueError, IndexError):
# e.g. line 6 of the docstring for <string> has inconsistent
# leading whitespace: ...
return
if not examples:
return
# Place doctest in module scope
saved_stack = self.scopeStack
self.scopeStack = [self.scopeStack[0]]
node_offset = self.offset or (0, 0)
self.pushScope(DoctestScope)
self.addBinding(None, Builtin('_'))
for example in examples:
try:
tree = ast.parse(example.source, "<doctest>")
except SyntaxError:
e = sys.exc_info()[1]
if PYPY:
e.offset += 1
position = (node_lineno + example.lineno + e.lineno,
example.indent + 4 + (e.offset or 0))
self.report(messages.DoctestSyntaxError, node, position)
else:
self.offset = (node_offset[0] + node_lineno + example.lineno,
node_offset[1] + example.indent + 4)
self.handleChildren(tree)
self.offset = node_offset
self.popScope()
self.scopeStack = saved_stack
def handleStringAnnotation(self, s, node, ref_lineno, ref_col_offset, err):
try:
tree = ast.parse(s)
except SyntaxError:
self.report(err, node, s)
return
body = tree.body
if len(body) != 1 or not isinstance(body[0], ast.Expr):
self.report(err, node, s)
return
parsed_annotation = tree.body[0].value
for descendant in ast.walk(parsed_annotation):
if (
'lineno' in descendant._attributes and
'col_offset' in descendant._attributes
):
descendant.lineno = ref_lineno
descendant.col_offset = ref_col_offset
self.handleNode(parsed_annotation, node)
def handleAnnotation(self, annotation, node):
if isinstance(annotation, ast.Str):
# Defer handling forward annotation.
self.deferFunction(functools.partial(
self.handleStringAnnotation,
annotation.s,
node,
annotation.lineno,
annotation.col_offset,
messages.ForwardAnnotationSyntaxError,
))
elif self.annotationsFutureEnabled:
self.deferFunction(lambda: self.handleNode(annotation, node))
else:
self.handleNode(annotation, node)
def ignore(self, node):
pass
# "stmt" type nodes
DELETE = PRINT = FOR = ASYNCFOR = WHILE = IF = WITH = WITHITEM = \
ASYNCWITH = ASYNCWITHITEM = TRYFINALLY = EXEC = \
EXPR = ASSIGN = handleChildren
PASS = ignore
# "expr" type nodes
BOOLOP = BINOP = UNARYOP = IFEXP = SET = \
CALL = REPR = ATTRIBUTE = SUBSCRIPT = \
STARRED = NAMECONSTANT = handleChildren
NUM = STR = BYTES = ELLIPSIS = CONSTANT = ignore
# "slice" type nodes
SLICE = EXTSLICE = INDEX = handleChildren
# expression contexts are node instances too, though being constants
LOAD = STORE = DEL = AUGLOAD = AUGSTORE = PARAM = ignore
# same for operators
AND = OR = ADD = SUB = MULT = DIV = MOD = POW = LSHIFT = RSHIFT = \
BITOR = BITXOR = BITAND = FLOORDIV = INVERT = NOT = UADD = USUB = \
EQ = NOTEQ = LT = LTE = GT = GTE = IS = ISNOT = IN = NOTIN = \
MATMULT = ignore
def RAISE(self, node):
self.handleChildren(node)
arg = get_raise_argument(node)
if isinstance(arg, ast.Call):
if is_notimplemented_name_node(arg.func):
# Handle "raise NotImplemented(...)"
self.report(messages.RaiseNotImplemented, node)
elif is_notimplemented_name_node(arg):
# Handle "raise NotImplemented"
self.report(messages.RaiseNotImplemented, node)
# additional node types
COMPREHENSION = KEYWORD = FORMATTEDVALUE = JOINEDSTR = handleChildren
def DICT(self, node):
# Complain if there are duplicate keys with different values
# If they have the same value it's not going to cause potentially
# unexpected behaviour so we'll not complain.
keys = [
convert_to_value(key) for key in node.keys
]
key_counts = counter(keys)
duplicate_keys = [
key for key, count in key_counts.items()
if count > 1
]
for key in duplicate_keys:
key_indices = [i for i, i_key in enumerate(keys) if i_key == key]
values = counter(
convert_to_value(node.values[index])
for index in key_indices
)
if any(count == 1 for value, count in values.items()):
for key_index in key_indices:
key_node = node.keys[key_index]
if isinstance(key, VariableKey):
self.report(messages.MultiValueRepeatedKeyVariable,
key_node,
key.name)
else:
self.report(
messages.MultiValueRepeatedKeyLiteral,
key_node,
key,
)
self.handleChildren(node)
def ASSERT(self, node):
if isinstance(node.test, ast.Tuple) and node.test.elts != []:
self.report(messages.AssertTuple, node)
self.handleChildren(node)
def GLOBAL(self, node):
"""
Keep track of globals declarations.
"""
global_scope_index = 1 if self._in_doctest() else 0
global_scope = self.scopeStack[global_scope_index]
# Ignore 'global' statement in global scope.
if self.scope is not global_scope:
# One 'global' statement can bind multiple (comma-delimited) names.
for node_name in node.names:
node_value = Assignment(node_name, node)
# Remove UndefinedName messages already reported for this name.
# TODO: if the global is not used in this scope, it does not
# become a globally defined name. See test_unused_global.
self.messages = [
m for m in self.messages if not
isinstance(m, messages.UndefinedName) or
m.message_args[0] != node_name]
# Bind name to global scope if it doesn't exist already.
global_scope.setdefault(node_name, node_value)
# Bind name to non-global scopes, but as already "used".
node_value.used = (global_scope, node)
for scope in self.scopeStack[global_scope_index + 1:]:
scope[node_name] = node_value
NONLOCAL = GLOBAL
def GENERATOREXP(self, node):
self.pushScope(GeneratorScope)
self.handleChildren(node)
self.popScope()
LISTCOMP = handleChildren if PY2 else GENERATOREXP
DICTCOMP = SETCOMP = GENERATOREXP
def NAME(self, node):
"""
Handle occurrence of Name (which can be a load/store/delete access.)
"""
# Locate the name in locals / function / globals scopes.
if isinstance(node.ctx, (ast.Load, ast.AugLoad)):
self.handleNodeLoad(node)
if (node.id == 'locals' and isinstance(self.scope, FunctionScope) and
isinstance(node.parent, ast.Call)):
# we are doing locals() call in current scope
self.scope.usesLocals = True
elif isinstance(node.ctx, (ast.Store, ast.AugStore, ast.Param)):
self.handleNodeStore(node)
elif isinstance(node.ctx, ast.Del):
self.handleNodeDelete(node)
else:
# Unknown context
raise RuntimeError("Got impossible expression context: %r" % (node.ctx,))
def CONTINUE(self, node):
# Walk the tree up until we see a loop (OK), a function or class
# definition (not OK), for 'continue', a finally block (not OK), or
# the top module scope (not OK)
n = node
while hasattr(n, 'parent'):
n, n_child = n.parent, n
if isinstance(n, LOOP_TYPES):
# Doesn't apply unless it's in the loop itself
if n_child not in n.orelse:
return
if isinstance(n, (ast.FunctionDef, ast.ClassDef)):
break
# Handle Try/TryFinally difference in Python < and >= 3.3
if hasattr(n, 'finalbody') and isinstance(node, ast.Continue):
if n_child in n.finalbody:
self.report(messages.ContinueInFinally, node)
return
if isinstance(node, ast.Continue):
self.report(messages.ContinueOutsideLoop, node)
else: # ast.Break
self.report(messages.BreakOutsideLoop, node)
BREAK = CONTINUE
def RETURN(self, node):
if isinstance(self.scope, (ClassScope, ModuleScope)):
self.report(messages.ReturnOutsideFunction, node)
return
if (
node.value and
hasattr(self.scope, 'returnValue') and
not self.scope.returnValue
):
self.scope.returnValue = node.value
self.handleNode(node.value, node)
def YIELD(self, node):
if isinstance(self.scope, (ClassScope, ModuleScope)):
self.report(messages.YieldOutsideFunction, node)
return
self.scope.isGenerator = True
self.handleNode(node.value, node)
AWAIT = YIELDFROM = YIELD
def FUNCTIONDEF(self, node):
for deco in node.decorator_list:
self.handleNode(deco, node)
self.LAMBDA(node)
self.addBinding(node, FunctionDefinition(node.name, node))
# doctest does not process doctest within a doctest,
# or in nested functions.
if (self.withDoctest and
not self._in_doctest() and
not isinstance(self.scope, FunctionScope)):
self.deferFunction(lambda: self.handleDoctests(node))
ASYNCFUNCTIONDEF = FUNCTIONDEF
def LAMBDA(self, node):
args = []
annotations = []
if PY2:
def addArgs(arglist):
for arg in arglist:
if isinstance(arg, ast.Tuple):
addArgs(arg.elts)
else:
args.append(arg.id)
addArgs(node.args.args)
defaults = node.args.defaults
else:
for arg in node.args.args + node.args.kwonlyargs:
args.append(arg.arg)
annotations.append(arg.annotation)
defaults = node.args.defaults + node.args.kw_defaults
# Only for Python3 FunctionDefs
is_py3_func = hasattr(node, 'returns')
for arg_name in ('vararg', 'kwarg'):
wildcard = getattr(node.args, arg_name)
if not wildcard:
continue
args.append(wildcard if PY2 else wildcard.arg)
if is_py3_func:
if PY2: # Python 2.7
argannotation = arg_name + 'annotation'
annotations.append(getattr(node.args, argannotation))
else: # Python >= 3.4
annotations.append(wildcard.annotation)
if is_py3_func:
annotations.append(node.returns)
if len(set(args)) < len(args):
for (idx, arg) in enumerate(args):
if arg in args[:idx]:
self.report(messages.DuplicateArgument, node, arg)
for annotation in annotations:
self.handleAnnotation(annotation, node)
for default in defaults:
self.handleNode(default, node)
def runFunction():
self.pushScope()
self.handleChildren(node, omit='decorator_list')
def checkUnusedAssignments():
"""
Check to see if any assignments have not been used.
"""
for name, binding in self.scope.unusedAssignments():
self.report(messages.UnusedVariable, binding.source, name)
self.deferAssignment(checkUnusedAssignments)
if PY2:
def checkReturnWithArgumentInsideGenerator():
"""
Check to see if there is any return statement with
arguments but the function is a generator.
"""
if self.scope.isGenerator and self.scope.returnValue:
self.report(messages.ReturnWithArgsInsideGenerator,
self.scope.returnValue)
self.deferAssignment(checkReturnWithArgumentInsideGenerator)
self.popScope()
self.deferFunction(runFunction)
def ARGUMENTS(self, node):
self.handleChildren(node, omit=('defaults', 'kw_defaults'))
if PY2:
scope_node = self.getScopeNode(node)
if node.vararg:
self.addBinding(node, Argument(node.vararg, scope_node))
if node.kwarg:
self.addBinding(node, Argument(node.kwarg, scope_node))
def ARG(self, node):
self.addBinding(node, Argument(node.arg, self.getScopeNode(node)))
def CLASSDEF(self, node):
"""
Check names used in a class definition, including its decorators, base
classes, and the body of its definition. Additionally, add its name to
the current scope.
"""
for deco in node.decorator_list:
self.handleNode(deco, node)
for baseNode in node.bases:
self.handleNode(baseNode, node)
if not PY2:
for keywordNode in node.keywords:
self.handleNode(keywordNode, node)
self.pushScope(ClassScope)
# doctest does not process doctest within a doctest
# classes within classes are processed.
if (self.withDoctest and
not self._in_doctest() and
not isinstance(self.scope, FunctionScope)):
self.deferFunction(lambda: self.handleDoctests(node))
for stmt in node.body:
self.handleNode(stmt, node)
self.popScope()
self.addBinding(node, ClassDefinition(node.name, node))
def AUGASSIGN(self, node):
self.handleNodeLoad(node.target)
self.handleNode(node.value, node)
self.handleNode(node.target, node)
def TUPLE(self, node):
if not PY2 and isinstance(node.ctx, ast.Store):
# Python 3 advanced tuple unpacking: a, *b, c = d.
# Only one starred expression is allowed, and no more than 1<<8
# assignments are allowed before a stared expression. There is
# also a limit of 1<<24 expressions after the starred expression,
# which is impossible to test due to memory restrictions, but we
# add it here anyway
has_starred = False
star_loc = -1
for i, n in enumerate(node.elts):
if isinstance(n, ast.Starred):
if has_starred:
self.report(messages.TwoStarredExpressions, node)
# The SyntaxError doesn't distinguish two from more
# than two.
break
has_starred = True
star_loc = i
if star_loc >= 1 << 8 or len(node.elts) - star_loc - 1 >= 1 << 24:
self.report(messages.TooManyExpressionsInStarredAssignment, node)
self.handleChildren(node)
LIST = TUPLE
def IMPORT(self, node):
for alias in node.names:
if '.' in alias.name and not alias.asname:
importation = SubmoduleImportation(alias.name, node)
else:
name = alias.asname or alias.name
importation = Importation(name, node, alias.name)
self.addBinding(node, importation)
def IMPORTFROM(self, node):
if node.module == '__future__':
if not self.futuresAllowed:
self.report(messages.LateFutureImport,
node, [n.name for n in node.names])
else:
self.futuresAllowed = False
module = ('.' * node.level) + (node.module or '')
for alias in node.names:
name = alias.asname or alias.name
if node.module == '__future__':
importation = FutureImportation(name, node, self.scope)
if alias.name not in __future__.all_feature_names:
self.report(messages.FutureFeatureNotDefined,
node, alias.name)
if alias.name == 'annotations':
self.annotationsFutureEnabled = True
elif alias.name == '*':
# Only Python 2, local import * is a SyntaxWarning
if not PY2 and not isinstance(self.scope, ModuleScope):
self.report(messages.ImportStarNotPermitted,
node, module)
continue
self.scope.importStarred = True
self.report(messages.ImportStarUsed, node, module)
importation = StarImportation(module, node)
else:
importation = ImportationFrom(name, node,
module, alias.name)
self.addBinding(node, importation)
def TRY(self, node):
handler_names = []
# List the exception handlers
for i, handler in enumerate(node.handlers):
if isinstance(handler.type, ast.Tuple):
for exc_type in handler.type.elts:
handler_names.append(getNodeName(exc_type))
elif handler.type:
handler_names.append(getNodeName(handler.type))
if handler.type is None and i < len(node.handlers) - 1:
self.report(messages.DefaultExceptNotLast, handler)
# Memorize the except handlers and process the body
self.exceptHandlers.append(handler_names)
for child in node.body:
self.handleNode(child, node)
self.exceptHandlers.pop()
# Process the other nodes: "except:", "else:", "finally:"
self.handleChildren(node, omit='body')
TRYEXCEPT = TRY
def EXCEPTHANDLER(self, node):
if PY2 or node.name is None:
self.handleChildren(node)
return
# If the name already exists in the scope, modify state of existing
# binding.
if node.name in self.scope:
self.handleNodeStore(node)
# 3.x: the name of the exception, which is not a Name node, but a
# simple string, creates a local that is only bound within the scope of
# the except: block. As such, temporarily remove the existing binding
# to more accurately determine if the name is used in the except:
# block.
try:
prev_definition = self.scope.pop(node.name)
except KeyError:
prev_definition = None
self.handleNodeStore(node)
self.handleChildren(node)
# See discussion on https://github.com/PyCQA/pyflakes/pull/59
# We're removing the local name since it's being unbound after leaving
# the except: block and it's always unbound if the except: block is
# never entered. This will cause an "undefined name" error raised if
# the checked code tries to use the name afterwards.
#
# Unless it's been removed already. Then do nothing.
try:
binding = self.scope.pop(node.name)
except KeyError:
pass
else:
if not binding.used:
self.report(messages.UnusedVariable, node, node.name)
# Restore.
if prev_definition:
self.scope[node.name] = prev_definition
def ANNASSIGN(self, node):
if node.value:
# Only bind the *targets* if the assignment has a value.
# Otherwise it's not really ast.Store and shouldn't silence
# UndefinedLocal warnings.
self.handleNode(node.target, node)
self.handleAnnotation(node.annotation, node)
if node.value:
# If the assignment has value, handle the *value* now.
self.handleNode(node.value, node)
def COMPARE(self, node):
literals = (ast.Str, ast.Num)
if not PY2:
literals += (ast.Bytes,)
left = node.left
for op, right in zip(node.ops, node.comparators):
if (isinstance(op, (ast.Is, ast.IsNot)) and
(isinstance(left, literals) or isinstance(right, literals))):
self.report(messages.IsLiteral, node)
left = right
self.handleChildren(node)
|
PyCQA/pyflakes | pyflakes/checker.py | iter_child_nodes | python | def iter_child_nodes(node, omit=None, _fields_order=_FieldsOrder()):
for name in _fields_order[node.__class__]:
if omit and name in omit:
continue
field = getattr(node, name, None)
if isinstance(field, ast.AST):
yield field
elif isinstance(field, list):
for item in field:
yield item | Yield all direct child nodes of *node*, that is, all fields that
are nodes and all items of fields that are lists of nodes.
:param node: AST node to be iterated upon
:param omit: String or tuple of strings denoting the
attributes of the node to be omitted from
further parsing
:param _fields_order: Order of AST node fields | train | https://github.com/PyCQA/pyflakes/blob/232cb1d27ee134bf96adc8f37e53589dc259b159/pyflakes/checker.py#L114-L133 | null | """
Main module.
Implement the central Checker class.
Also, it models the Bindings and Scopes.
"""
import __future__
import ast
import bisect
import collections
import doctest
import functools
import os
import re
import sys
import tokenize
from pyflakes import messages
PY2 = sys.version_info < (3, 0)
PY35_PLUS = sys.version_info >= (3, 5) # Python 3.5 and above
PY36_PLUS = sys.version_info >= (3, 6) # Python 3.6 and above
PY38_PLUS = sys.version_info >= (3, 8)
try:
sys.pypy_version_info
PYPY = True
except AttributeError:
PYPY = False
builtin_vars = dir(__import__('__builtin__' if PY2 else 'builtins'))
if PY2:
tokenize_tokenize = tokenize.generate_tokens
else:
tokenize_tokenize = tokenize.tokenize
if PY2:
def getNodeType(node_class):
# workaround str.upper() which is locale-dependent
return str(unicode(node_class.__name__).upper())
def get_raise_argument(node):
return node.type
else:
def getNodeType(node_class):
return node_class.__name__.upper()
def get_raise_argument(node):
return node.exc
# Silence `pyflakes` from reporting `undefined name 'unicode'` in Python 3.
unicode = str
# Python >= 3.3 uses ast.Try instead of (ast.TryExcept + ast.TryFinally)
if PY2:
def getAlternatives(n):
if isinstance(n, (ast.If, ast.TryFinally)):
return [n.body]
if isinstance(n, ast.TryExcept):
return [n.body + n.orelse] + [[hdl] for hdl in n.handlers]
else:
def getAlternatives(n):
if isinstance(n, ast.If):
return [n.body]
if isinstance(n, ast.Try):
return [n.body + n.orelse] + [[hdl] for hdl in n.handlers]
if PY35_PLUS:
FOR_TYPES = (ast.For, ast.AsyncFor)
LOOP_TYPES = (ast.While, ast.For, ast.AsyncFor)
else:
FOR_TYPES = (ast.For,)
LOOP_TYPES = (ast.While, ast.For)
# https://github.com/python/typed_ast/blob/55420396/ast27/Parser/tokenizer.c#L102-L104
TYPE_COMMENT_RE = re.compile(r'^#\s*type:\s*')
# https://github.com/python/typed_ast/blob/55420396/ast27/Parser/tokenizer.c#L1400
TYPE_IGNORE_RE = re.compile(TYPE_COMMENT_RE.pattern + r'ignore\s*(#|$)')
# https://github.com/python/typed_ast/blob/55420396/ast27/Grammar/Grammar#L147
TYPE_FUNC_RE = re.compile(r'^(\(.*?\))\s*->\s*(.*)$')
class _FieldsOrder(dict):
"""Fix order of AST node fields."""
def _get_fields(self, node_class):
# handle iter before target, and generators before element
fields = node_class._fields
if 'iter' in fields:
key_first = 'iter'.find
elif 'generators' in fields:
key_first = 'generators'.find
else:
key_first = 'value'.find
return tuple(sorted(fields, key=key_first, reverse=True))
def __missing__(self, node_class):
self[node_class] = fields = self._get_fields(node_class)
return fields
def counter(items):
"""
Simplest required implementation of collections.Counter. Required as 2.6
does not have Counter in collections.
"""
results = {}
for item in items:
results[item] = results.get(item, 0) + 1
return results
def convert_to_value(item):
if isinstance(item, ast.Str):
return item.s
elif hasattr(ast, 'Bytes') and isinstance(item, ast.Bytes):
return item.s
elif isinstance(item, ast.Tuple):
return tuple(convert_to_value(i) for i in item.elts)
elif isinstance(item, ast.Num):
return item.n
elif isinstance(item, ast.Name):
result = VariableKey(item=item)
constants_lookup = {
'True': True,
'False': False,
'None': None,
}
return constants_lookup.get(
result.name,
result,
)
elif (not PY2) and isinstance(item, ast.NameConstant):
# None, True, False are nameconstants in python3, but names in 2
return item.value
else:
return UnhandledKeyType()
def is_notimplemented_name_node(node):
return isinstance(node, ast.Name) and getNodeName(node) == 'NotImplemented'
class Binding(object):
"""
Represents the binding of a value to a name.
The checker uses this to keep track of which names have been bound and
which names have not. See L{Assignment} for a special type of binding that
is checked with stricter rules.
@ivar used: pair of (L{Scope}, node) indicating the scope and
the node that this binding was last used.
"""
def __init__(self, name, source):
self.name = name
self.source = source
self.used = False
def __str__(self):
return self.name
def __repr__(self):
return '<%s object %r from line %r at 0x%x>' % (self.__class__.__name__,
self.name,
self.source.lineno,
id(self))
def redefines(self, other):
return isinstance(other, Definition) and self.name == other.name
class Definition(Binding):
"""
A binding that defines a function or a class.
"""
class Builtin(Definition):
"""A definition created for all Python builtins."""
def __init__(self, name):
super(Builtin, self).__init__(name, None)
def __repr__(self):
return '<%s object %r at 0x%x>' % (self.__class__.__name__,
self.name,
id(self))
class UnhandledKeyType(object):
"""
A dictionary key of a type that we cannot or do not check for duplicates.
"""
class VariableKey(object):
"""
A dictionary key which is a variable.
@ivar item: The variable AST object.
"""
def __init__(self, item):
self.name = item.id
def __eq__(self, compare):
return (
compare.__class__ == self.__class__ and
compare.name == self.name
)
def __hash__(self):
return hash(self.name)
class Importation(Definition):
"""
A binding created by an import statement.
@ivar fullName: The complete name given to the import statement,
possibly including multiple dotted components.
@type fullName: C{str}
"""
def __init__(self, name, source, full_name=None):
self.fullName = full_name or name
self.redefined = []
super(Importation, self).__init__(name, source)
def redefines(self, other):
if isinstance(other, SubmoduleImportation):
# See note in SubmoduleImportation about RedefinedWhileUnused
return self.fullName == other.fullName
return isinstance(other, Definition) and self.name == other.name
def _has_alias(self):
"""Return whether importation needs an as clause."""
return not self.fullName.split('.')[-1] == self.name
@property
def source_statement(self):
"""Generate a source statement equivalent to the import."""
if self._has_alias():
return 'import %s as %s' % (self.fullName, self.name)
else:
return 'import %s' % self.fullName
def __str__(self):
"""Return import full name with alias."""
if self._has_alias():
return self.fullName + ' as ' + self.name
else:
return self.fullName
class SubmoduleImportation(Importation):
"""
A binding created by a submodule import statement.
A submodule import is a special case where the root module is implicitly
imported, without an 'as' clause, and the submodule is also imported.
Python does not restrict which attributes of the root module may be used.
This class is only used when the submodule import is without an 'as' clause.
pyflakes handles this case by registering the root module name in the scope,
allowing any attribute of the root module to be accessed.
RedefinedWhileUnused is suppressed in `redefines` unless the submodule
name is also the same, to avoid false positives.
"""
def __init__(self, name, source):
# A dot should only appear in the name when it is a submodule import
assert '.' in name and (not source or isinstance(source, ast.Import))
package_name = name.split('.')[0]
super(SubmoduleImportation, self).__init__(package_name, source)
self.fullName = name
def redefines(self, other):
if isinstance(other, Importation):
return self.fullName == other.fullName
return super(SubmoduleImportation, self).redefines(other)
def __str__(self):
return self.fullName
@property
def source_statement(self):
return 'import ' + self.fullName
class ImportationFrom(Importation):
def __init__(self, name, source, module, real_name=None):
self.module = module
self.real_name = real_name or name
if module.endswith('.'):
full_name = module + self.real_name
else:
full_name = module + '.' + self.real_name
super(ImportationFrom, self).__init__(name, source, full_name)
def __str__(self):
"""Return import full name with alias."""
if self.real_name != self.name:
return self.fullName + ' as ' + self.name
else:
return self.fullName
@property
def source_statement(self):
if self.real_name != self.name:
return 'from %s import %s as %s' % (self.module,
self.real_name,
self.name)
else:
return 'from %s import %s' % (self.module, self.name)
class StarImportation(Importation):
"""A binding created by a 'from x import *' statement."""
def __init__(self, name, source):
super(StarImportation, self).__init__('*', source)
# Each star importation needs a unique name, and
# may not be the module name otherwise it will be deemed imported
self.name = name + '.*'
self.fullName = name
@property
def source_statement(self):
return 'from ' + self.fullName + ' import *'
def __str__(self):
# When the module ends with a ., avoid the ambiguous '..*'
if self.fullName.endswith('.'):
return self.source_statement
else:
return self.name
class FutureImportation(ImportationFrom):
"""
A binding created by a from `__future__` import statement.
`__future__` imports are implicitly used.
"""
def __init__(self, name, source, scope):
super(FutureImportation, self).__init__(name, source, '__future__')
self.used = (scope, source)
class Argument(Binding):
"""
Represents binding a name as an argument.
"""
class Assignment(Binding):
"""
Represents binding a name with an explicit assignment.
The checker will raise warnings for any Assignment that isn't used. Also,
the checker does not consider assignments in tuple/list unpacking to be
Assignments, rather it treats them as simple Bindings.
"""
class FunctionDefinition(Definition):
pass
class ClassDefinition(Definition):
pass
class ExportBinding(Binding):
"""
A binding created by an C{__all__} assignment. If the names in the list
can be determined statically, they will be treated as names for export and
additional checking applied to them.
The only recognized C{__all__} assignment via list concatenation is in the
following format:
__all__ = ['a'] + ['b'] + ['c']
Names which are imported and not otherwise used but appear in the value of
C{__all__} will not have an unused import warning reported for them.
"""
def __init__(self, name, source, scope):
if '__all__' in scope and isinstance(source, ast.AugAssign):
self.names = list(scope['__all__'].names)
else:
self.names = []
def _add_to_names(container):
for node in container.elts:
if isinstance(node, ast.Str):
self.names.append(node.s)
if isinstance(source.value, (ast.List, ast.Tuple)):
_add_to_names(source.value)
# If concatenating lists
elif isinstance(source.value, ast.BinOp):
currentValue = source.value
while isinstance(currentValue.right, ast.List):
left = currentValue.left
right = currentValue.right
_add_to_names(right)
# If more lists are being added
if isinstance(left, ast.BinOp):
currentValue = left
# If just two lists are being added
elif isinstance(left, ast.List):
_add_to_names(left)
# All lists accounted for - done
break
# If not list concatenation
else:
break
super(ExportBinding, self).__init__(name, source)
class Scope(dict):
importStarred = False # set to True when import * is found
def __repr__(self):
scope_cls = self.__class__.__name__
return '<%s at 0x%x %s>' % (scope_cls, id(self), dict.__repr__(self))
class ClassScope(Scope):
pass
class FunctionScope(Scope):
"""
I represent a name scope for a function.
@ivar globals: Names declared 'global' in this function.
"""
usesLocals = False
alwaysUsed = {'__tracebackhide__', '__traceback_info__',
'__traceback_supplement__'}
def __init__(self):
super(FunctionScope, self).__init__()
# Simplify: manage the special locals as globals
self.globals = self.alwaysUsed.copy()
self.returnValue = None # First non-empty return
self.isGenerator = False # Detect a generator
def unusedAssignments(self):
"""
Return a generator for the assignments which have not been used.
"""
for name, binding in self.items():
if (not binding.used and
name != '_' and # see issue #202
name not in self.globals and
not self.usesLocals and
isinstance(binding, Assignment)):
yield name, binding
class GeneratorScope(Scope):
pass
class ModuleScope(Scope):
"""Scope for a module."""
_futures_allowed = True
_annotations_future_enabled = False
class DoctestScope(ModuleScope):
"""Scope for a doctest."""
class DummyNode(object):
"""Used in place of an `ast.AST` to set error message positions"""
def __init__(self, lineno, col_offset):
self.lineno = lineno
self.col_offset = col_offset
# Globally defined names which are not attributes of the builtins module, or
# are only present on some platforms.
_MAGIC_GLOBALS = ['__file__', '__builtins__', 'WindowsError']
# module scope annotation will store in `__annotations__`, see also PEP 526.
if PY36_PLUS:
_MAGIC_GLOBALS.append('__annotations__')
def getNodeName(node):
# Returns node.id, or node.name, or None
if hasattr(node, 'id'): # One of the many nodes with an id
return node.id
if hasattr(node, 'name'): # an ExceptHandler node
return node.name
def is_typing_overload(value, scope_stack):
def name_is_typing_overload(name): # type: (str) -> bool
for scope in reversed(scope_stack):
if name in scope:
return (
isinstance(scope[name], ImportationFrom) and
scope[name].fullName == 'typing.overload'
)
else:
return False
def is_typing_overload_decorator(node):
return (
(
isinstance(node, ast.Name) and name_is_typing_overload(node.id)
) or (
isinstance(node, ast.Attribute) and
isinstance(node.value, ast.Name) and
node.value.id == 'typing' and
node.attr == 'overload'
)
)
return (
isinstance(value.source, ast.FunctionDef) and
any(
is_typing_overload_decorator(dec)
for dec in value.source.decorator_list
)
)
def make_tokens(code):
# PY3: tokenize.tokenize requires readline of bytes
if not isinstance(code, bytes):
code = code.encode('UTF-8')
lines = iter(code.splitlines(True))
# next(lines, b'') is to prevent an error in pypy3
return tuple(tokenize_tokenize(lambda: next(lines, b'')))
class _TypeableVisitor(ast.NodeVisitor):
"""Collect the line number and nodes which are deemed typeable by
PEP 484
https://www.python.org/dev/peps/pep-0484/#type-comments
"""
def __init__(self):
self.typeable_lines = [] # type: List[int]
self.typeable_nodes = {} # type: Dict[int, ast.AST]
def _typeable(self, node):
# if there is more than one typeable thing on a line last one wins
self.typeable_lines.append(node.lineno)
self.typeable_nodes[node.lineno] = node
self.generic_visit(node)
visit_Assign = visit_For = visit_FunctionDef = visit_With = _typeable
visit_AsyncFor = visit_AsyncFunctionDef = visit_AsyncWith = _typeable
def _collect_type_comments(tree, tokens):
visitor = _TypeableVisitor()
visitor.visit(tree)
type_comments = collections.defaultdict(list)
for tp, text, start, _, _ in tokens:
if (
tp != tokenize.COMMENT or # skip non comments
not TYPE_COMMENT_RE.match(text) or # skip non-type comments
TYPE_IGNORE_RE.match(text) # skip ignores
):
continue
# search for the typeable node at or before the line number of the
# type comment.
# if the bisection insertion point is before any nodes this is an
# invalid type comment which is ignored.
lineno, _ = start
idx = bisect.bisect_right(visitor.typeable_lines, lineno)
if idx == 0:
continue
node = visitor.typeable_nodes[visitor.typeable_lines[idx - 1]]
type_comments[node].append((start, text))
return type_comments
class Checker(object):
"""
I check the cleanliness and sanity of Python code.
@ivar _deferredFunctions: Tracking list used by L{deferFunction}. Elements
of the list are two-tuples. The first element is the callable passed
to L{deferFunction}. The second element is a copy of the scope stack
at the time L{deferFunction} was called.
@ivar _deferredAssignments: Similar to C{_deferredFunctions}, but for
callables which are deferred assignment checks.
"""
_ast_node_scope = {
ast.Module: ModuleScope,
ast.ClassDef: ClassScope,
ast.FunctionDef: FunctionScope,
ast.Lambda: FunctionScope,
ast.ListComp: GeneratorScope,
ast.SetComp: GeneratorScope,
ast.GeneratorExp: GeneratorScope,
ast.DictComp: GeneratorScope,
}
if PY35_PLUS:
_ast_node_scope[ast.AsyncFunctionDef] = FunctionScope,
nodeDepth = 0
offset = None
traceTree = False
builtIns = set(builtin_vars).union(_MAGIC_GLOBALS)
_customBuiltIns = os.environ.get('PYFLAKES_BUILTINS')
if _customBuiltIns:
builtIns.update(_customBuiltIns.split(','))
del _customBuiltIns
# TODO: file_tokens= is required to perform checks on type comments,
# eventually make this a required positional argument. For now it
# is defaulted to `()` for api compatibility.
def __init__(self, tree, filename='(none)', builtins=None,
withDoctest='PYFLAKES_DOCTEST' in os.environ, file_tokens=()):
self._nodeHandlers = {}
self._deferredFunctions = []
self._deferredAssignments = []
self.deadScopes = []
self.messages = []
self.filename = filename
if builtins:
self.builtIns = self.builtIns.union(builtins)
self.withDoctest = withDoctest
try:
self.scopeStack = [Checker._ast_node_scope[type(tree)]()]
except KeyError:
raise RuntimeError('No scope implemented for the node %r' % tree)
self.exceptHandlers = [()]
self.root = tree
self._type_comments = _collect_type_comments(tree, file_tokens)
for builtin in self.builtIns:
self.addBinding(None, Builtin(builtin))
self.handleChildren(tree)
self.runDeferred(self._deferredFunctions)
# Set _deferredFunctions to None so that deferFunction will fail
# noisily if called after we've run through the deferred functions.
self._deferredFunctions = None
self.runDeferred(self._deferredAssignments)
# Set _deferredAssignments to None so that deferAssignment will fail
# noisily if called after we've run through the deferred assignments.
self._deferredAssignments = None
del self.scopeStack[1:]
self.popScope()
self.checkDeadScopes()
def deferFunction(self, callable):
"""
Schedule a function handler to be called just before completion.
This is used for handling function bodies, which must be deferred
because code later in the file might modify the global scope. When
`callable` is called, the scope at the time this is called will be
restored, however it will contain any new bindings added to it.
"""
self._deferredFunctions.append((callable, self.scopeStack[:], self.offset))
def deferAssignment(self, callable):
"""
Schedule an assignment handler to be called just after deferred
function handlers.
"""
self._deferredAssignments.append((callable, self.scopeStack[:], self.offset))
def runDeferred(self, deferred):
"""
Run the callables in C{deferred} using their associated scope stack.
"""
for handler, scope, offset in deferred:
self.scopeStack = scope
self.offset = offset
handler()
def _in_doctest(self):
return (len(self.scopeStack) >= 2 and
isinstance(self.scopeStack[1], DoctestScope))
@property
def futuresAllowed(self):
if not all(isinstance(scope, ModuleScope)
for scope in self.scopeStack):
return False
return self.scope._futures_allowed
@futuresAllowed.setter
def futuresAllowed(self, value):
assert value is False
if isinstance(self.scope, ModuleScope):
self.scope._futures_allowed = False
@property
def annotationsFutureEnabled(self):
scope = self.scopeStack[0]
if not isinstance(scope, ModuleScope):
return False
return scope._annotations_future_enabled
@annotationsFutureEnabled.setter
def annotationsFutureEnabled(self, value):
assert value is True
assert isinstance(self.scope, ModuleScope)
self.scope._annotations_future_enabled = True
@property
def scope(self):
return self.scopeStack[-1]
def popScope(self):
self.deadScopes.append(self.scopeStack.pop())
def checkDeadScopes(self):
"""
Look at scopes which have been fully examined and report names in them
which were imported but unused.
"""
for scope in self.deadScopes:
# imports in classes are public members
if isinstance(scope, ClassScope):
continue
all_binding = scope.get('__all__')
if all_binding and not isinstance(all_binding, ExportBinding):
all_binding = None
if all_binding:
all_names = set(all_binding.names)
undefined = all_names.difference(scope)
else:
all_names = undefined = []
if undefined:
if not scope.importStarred and \
os.path.basename(self.filename) != '__init__.py':
# Look for possible mistakes in the export list
for name in undefined:
self.report(messages.UndefinedExport,
scope['__all__'].source, name)
# mark all import '*' as used by the undefined in __all__
if scope.importStarred:
from_list = []
for binding in scope.values():
if isinstance(binding, StarImportation):
binding.used = all_binding
from_list.append(binding.fullName)
# report * usage, with a list of possible sources
from_list = ', '.join(sorted(from_list))
for name in undefined:
self.report(messages.ImportStarUsage,
scope['__all__'].source, name, from_list)
# Look for imported names that aren't used.
for value in scope.values():
if isinstance(value, Importation):
used = value.used or value.name in all_names
if not used:
messg = messages.UnusedImport
self.report(messg, value.source, str(value))
for node in value.redefined:
if isinstance(self.getParent(node), FOR_TYPES):
messg = messages.ImportShadowedByLoopVar
elif used:
continue
else:
messg = messages.RedefinedWhileUnused
self.report(messg, node, value.name, value.source)
def pushScope(self, scopeClass=FunctionScope):
self.scopeStack.append(scopeClass())
def report(self, messageClass, *args, **kwargs):
self.messages.append(messageClass(self.filename, *args, **kwargs))
def getParent(self, node):
# Lookup the first parent which is not Tuple, List or Starred
while True:
node = node.parent
if not hasattr(node, 'elts') and not hasattr(node, 'ctx'):
return node
def getCommonAncestor(self, lnode, rnode, stop):
if stop in (lnode, rnode) or not (hasattr(lnode, 'parent') and
hasattr(rnode, 'parent')):
return None
if lnode is rnode:
return lnode
if (lnode.depth > rnode.depth):
return self.getCommonAncestor(lnode.parent, rnode, stop)
if (lnode.depth < rnode.depth):
return self.getCommonAncestor(lnode, rnode.parent, stop)
return self.getCommonAncestor(lnode.parent, rnode.parent, stop)
def descendantOf(self, node, ancestors, stop):
for a in ancestors:
if self.getCommonAncestor(node, a, stop):
return True
return False
def _getAncestor(self, node, ancestor_type):
parent = node
while True:
if parent is self.root:
return None
parent = self.getParent(parent)
if isinstance(parent, ancestor_type):
return parent
def getScopeNode(self, node):
return self._getAncestor(node, tuple(Checker._ast_node_scope.keys()))
def differentForks(self, lnode, rnode):
"""True, if lnode and rnode are located on different forks of IF/TRY"""
ancestor = self.getCommonAncestor(lnode, rnode, self.root)
parts = getAlternatives(ancestor)
if parts:
for items in parts:
if self.descendantOf(lnode, items, ancestor) ^ \
self.descendantOf(rnode, items, ancestor):
return True
return False
def addBinding(self, node, value):
"""
Called when a binding is altered.
- `node` is the statement responsible for the change
- `value` is the new value, a Binding instance
"""
# assert value.source in (node, node.parent):
for scope in self.scopeStack[::-1]:
if value.name in scope:
break
existing = scope.get(value.name)
if (existing and not isinstance(existing, Builtin) and
not self.differentForks(node, existing.source)):
parent_stmt = self.getParent(value.source)
if isinstance(existing, Importation) and isinstance(parent_stmt, FOR_TYPES):
self.report(messages.ImportShadowedByLoopVar,
node, value.name, existing.source)
elif scope is self.scope:
if (isinstance(parent_stmt, ast.comprehension) and
not isinstance(self.getParent(existing.source),
(FOR_TYPES, ast.comprehension))):
self.report(messages.RedefinedInListComp,
node, value.name, existing.source)
elif not existing.used and value.redefines(existing):
if value.name != '_' or isinstance(existing, Importation):
if not is_typing_overload(existing, self.scopeStack):
self.report(messages.RedefinedWhileUnused,
node, value.name, existing.source)
elif isinstance(existing, Importation) and value.redefines(existing):
existing.redefined.append(node)
if value.name in self.scope:
# then assume the rebound name is used as a global or within a loop
value.used = self.scope[value.name].used
self.scope[value.name] = value
def getNodeHandler(self, node_class):
try:
return self._nodeHandlers[node_class]
except KeyError:
nodeType = getNodeType(node_class)
self._nodeHandlers[node_class] = handler = getattr(self, nodeType)
return handler
def handleNodeLoad(self, node):
name = getNodeName(node)
if not name:
return
in_generators = None
importStarred = None
# try enclosing function scopes and global scope
for scope in self.scopeStack[-1::-1]:
if isinstance(scope, ClassScope):
if not PY2 and name == '__class__':
return
elif in_generators is False:
# only generators used in a class scope can access the
# names of the class. this is skipped during the first
# iteration
continue
if (name == 'print' and
isinstance(scope.get(name, None), Builtin)):
parent = self.getParent(node)
if (isinstance(parent, ast.BinOp) and
isinstance(parent.op, ast.RShift)):
self.report(messages.InvalidPrintSyntax, node)
try:
scope[name].used = (self.scope, node)
# if the name of SubImportation is same as
# alias of other Importation and the alias
# is used, SubImportation also should be marked as used.
n = scope[name]
if isinstance(n, Importation) and n._has_alias():
try:
scope[n.fullName].used = (self.scope, node)
except KeyError:
pass
except KeyError:
pass
else:
return
importStarred = importStarred or scope.importStarred
if in_generators is not False:
in_generators = isinstance(scope, GeneratorScope)
if importStarred:
from_list = []
for scope in self.scopeStack[-1::-1]:
for binding in scope.values():
if isinstance(binding, StarImportation):
# mark '*' imports as used for each scope
binding.used = (self.scope, node)
from_list.append(binding.fullName)
# report * usage, with a list of possible sources
from_list = ', '.join(sorted(from_list))
self.report(messages.ImportStarUsage, node, name, from_list)
return
if name == '__path__' and os.path.basename(self.filename) == '__init__.py':
# the special name __path__ is valid only in packages
return
if name == '__module__' and isinstance(self.scope, ClassScope):
return
# protected with a NameError handler?
if 'NameError' not in self.exceptHandlers[-1]:
self.report(messages.UndefinedName, node, name)
def handleNodeStore(self, node):
name = getNodeName(node)
if not name:
return
# if the name hasn't already been defined in the current scope
if isinstance(self.scope, FunctionScope) and name not in self.scope:
# for each function or module scope above us
for scope in self.scopeStack[:-1]:
if not isinstance(scope, (FunctionScope, ModuleScope)):
continue
# if the name was defined in that scope, and the name has
# been accessed already in the current scope, and hasn't
# been declared global
used = name in scope and scope[name].used
if used and used[0] is self.scope and name not in self.scope.globals:
# then it's probably a mistake
self.report(messages.UndefinedLocal,
scope[name].used[1], name, scope[name].source)
break
parent_stmt = self.getParent(node)
if isinstance(parent_stmt, (FOR_TYPES, ast.comprehension)) or (
parent_stmt != node.parent and
not self.isLiteralTupleUnpacking(parent_stmt)):
binding = Binding(name, node)
elif name == '__all__' and isinstance(self.scope, ModuleScope):
binding = ExportBinding(name, node.parent, self.scope)
elif isinstance(getattr(node, 'ctx', None), ast.Param):
binding = Argument(name, self.getScopeNode(node))
else:
binding = Assignment(name, node)
self.addBinding(node, binding)
def handleNodeDelete(self, node):
def on_conditional_branch():
"""
Return `True` if node is part of a conditional body.
"""
current = getattr(node, 'parent', None)
while current:
if isinstance(current, (ast.If, ast.While, ast.IfExp)):
return True
current = getattr(current, 'parent', None)
return False
name = getNodeName(node)
if not name:
return
if on_conditional_branch():
# We cannot predict if this conditional branch is going to
# be executed.
return
if isinstance(self.scope, FunctionScope) and name in self.scope.globals:
self.scope.globals.remove(name)
else:
try:
del self.scope[name]
except KeyError:
self.report(messages.UndefinedName, node, name)
def _handle_type_comments(self, node):
for (lineno, col_offset), comment in self._type_comments.get(node, ()):
comment = comment.split(':', 1)[1].strip()
func_match = TYPE_FUNC_RE.match(comment)
if func_match:
parts = (
func_match.group(1).replace('*', ''),
func_match.group(2).strip(),
)
else:
parts = (comment,)
for part in parts:
if PY2:
part = part.replace('...', 'Ellipsis')
self.deferFunction(functools.partial(
self.handleStringAnnotation,
part, DummyNode(lineno, col_offset), lineno, col_offset,
messages.CommentAnnotationSyntaxError,
))
def handleChildren(self, tree, omit=None):
self._handle_type_comments(tree)
for node in iter_child_nodes(tree, omit=omit):
self.handleNode(node, tree)
def isLiteralTupleUnpacking(self, node):
if isinstance(node, ast.Assign):
for child in node.targets + [node.value]:
if not hasattr(child, 'elts'):
return False
return True
def isDocstring(self, node):
"""
Determine if the given node is a docstring, as long as it is at the
correct place in the node tree.
"""
return isinstance(node, ast.Str) or (isinstance(node, ast.Expr) and
isinstance(node.value, ast.Str))
def getDocstring(self, node):
if isinstance(node, ast.Expr):
node = node.value
if not isinstance(node, ast.Str):
return (None, None)
if PYPY or PY38_PLUS:
doctest_lineno = node.lineno - 1
else:
# Computed incorrectly if the docstring has backslash
doctest_lineno = node.lineno - node.s.count('\n') - 1
return (node.s, doctest_lineno)
def handleNode(self, node, parent):
if node is None:
return
if self.offset and getattr(node, 'lineno', None) is not None:
node.lineno += self.offset[0]
node.col_offset += self.offset[1]
if self.traceTree:
print(' ' * self.nodeDepth + node.__class__.__name__)
if self.futuresAllowed and not (isinstance(node, ast.ImportFrom) or
self.isDocstring(node)):
self.futuresAllowed = False
self.nodeDepth += 1
node.depth = self.nodeDepth
node.parent = parent
try:
handler = self.getNodeHandler(node.__class__)
handler(node)
finally:
self.nodeDepth -= 1
if self.traceTree:
print(' ' * self.nodeDepth + 'end ' + node.__class__.__name__)
_getDoctestExamples = doctest.DocTestParser().get_examples
def handleDoctests(self, node):
try:
if hasattr(node, 'docstring'):
docstring = node.docstring
# This is just a reasonable guess. In Python 3.7, docstrings no
# longer have line numbers associated with them. This will be
# incorrect if there are empty lines between the beginning
# of the function and the docstring.
node_lineno = node.lineno
if hasattr(node, 'args'):
node_lineno = max([node_lineno] +
[arg.lineno for arg in node.args.args])
else:
(docstring, node_lineno) = self.getDocstring(node.body[0])
examples = docstring and self._getDoctestExamples(docstring)
except (ValueError, IndexError):
# e.g. line 6 of the docstring for <string> has inconsistent
# leading whitespace: ...
return
if not examples:
return
# Place doctest in module scope
saved_stack = self.scopeStack
self.scopeStack = [self.scopeStack[0]]
node_offset = self.offset or (0, 0)
self.pushScope(DoctestScope)
self.addBinding(None, Builtin('_'))
for example in examples:
try:
tree = ast.parse(example.source, "<doctest>")
except SyntaxError:
e = sys.exc_info()[1]
if PYPY:
e.offset += 1
position = (node_lineno + example.lineno + e.lineno,
example.indent + 4 + (e.offset or 0))
self.report(messages.DoctestSyntaxError, node, position)
else:
self.offset = (node_offset[0] + node_lineno + example.lineno,
node_offset[1] + example.indent + 4)
self.handleChildren(tree)
self.offset = node_offset
self.popScope()
self.scopeStack = saved_stack
def handleStringAnnotation(self, s, node, ref_lineno, ref_col_offset, err):
try:
tree = ast.parse(s)
except SyntaxError:
self.report(err, node, s)
return
body = tree.body
if len(body) != 1 or not isinstance(body[0], ast.Expr):
self.report(err, node, s)
return
parsed_annotation = tree.body[0].value
for descendant in ast.walk(parsed_annotation):
if (
'lineno' in descendant._attributes and
'col_offset' in descendant._attributes
):
descendant.lineno = ref_lineno
descendant.col_offset = ref_col_offset
self.handleNode(parsed_annotation, node)
def handleAnnotation(self, annotation, node):
if isinstance(annotation, ast.Str):
# Defer handling forward annotation.
self.deferFunction(functools.partial(
self.handleStringAnnotation,
annotation.s,
node,
annotation.lineno,
annotation.col_offset,
messages.ForwardAnnotationSyntaxError,
))
elif self.annotationsFutureEnabled:
self.deferFunction(lambda: self.handleNode(annotation, node))
else:
self.handleNode(annotation, node)
def ignore(self, node):
pass
# "stmt" type nodes
DELETE = PRINT = FOR = ASYNCFOR = WHILE = IF = WITH = WITHITEM = \
ASYNCWITH = ASYNCWITHITEM = TRYFINALLY = EXEC = \
EXPR = ASSIGN = handleChildren
PASS = ignore
# "expr" type nodes
BOOLOP = BINOP = UNARYOP = IFEXP = SET = \
CALL = REPR = ATTRIBUTE = SUBSCRIPT = \
STARRED = NAMECONSTANT = handleChildren
NUM = STR = BYTES = ELLIPSIS = CONSTANT = ignore
# "slice" type nodes
SLICE = EXTSLICE = INDEX = handleChildren
# expression contexts are node instances too, though being constants
LOAD = STORE = DEL = AUGLOAD = AUGSTORE = PARAM = ignore
# same for operators
AND = OR = ADD = SUB = MULT = DIV = MOD = POW = LSHIFT = RSHIFT = \
BITOR = BITXOR = BITAND = FLOORDIV = INVERT = NOT = UADD = USUB = \
EQ = NOTEQ = LT = LTE = GT = GTE = IS = ISNOT = IN = NOTIN = \
MATMULT = ignore
def RAISE(self, node):
self.handleChildren(node)
arg = get_raise_argument(node)
if isinstance(arg, ast.Call):
if is_notimplemented_name_node(arg.func):
# Handle "raise NotImplemented(...)"
self.report(messages.RaiseNotImplemented, node)
elif is_notimplemented_name_node(arg):
# Handle "raise NotImplemented"
self.report(messages.RaiseNotImplemented, node)
# additional node types
COMPREHENSION = KEYWORD = FORMATTEDVALUE = JOINEDSTR = handleChildren
def DICT(self, node):
# Complain if there are duplicate keys with different values
# If they have the same value it's not going to cause potentially
# unexpected behaviour so we'll not complain.
keys = [
convert_to_value(key) for key in node.keys
]
key_counts = counter(keys)
duplicate_keys = [
key for key, count in key_counts.items()
if count > 1
]
for key in duplicate_keys:
key_indices = [i for i, i_key in enumerate(keys) if i_key == key]
values = counter(
convert_to_value(node.values[index])
for index in key_indices
)
if any(count == 1 for value, count in values.items()):
for key_index in key_indices:
key_node = node.keys[key_index]
if isinstance(key, VariableKey):
self.report(messages.MultiValueRepeatedKeyVariable,
key_node,
key.name)
else:
self.report(
messages.MultiValueRepeatedKeyLiteral,
key_node,
key,
)
self.handleChildren(node)
def ASSERT(self, node):
if isinstance(node.test, ast.Tuple) and node.test.elts != []:
self.report(messages.AssertTuple, node)
self.handleChildren(node)
def GLOBAL(self, node):
"""
Keep track of globals declarations.
"""
global_scope_index = 1 if self._in_doctest() else 0
global_scope = self.scopeStack[global_scope_index]
# Ignore 'global' statement in global scope.
if self.scope is not global_scope:
# One 'global' statement can bind multiple (comma-delimited) names.
for node_name in node.names:
node_value = Assignment(node_name, node)
# Remove UndefinedName messages already reported for this name.
# TODO: if the global is not used in this scope, it does not
# become a globally defined name. See test_unused_global.
self.messages = [
m for m in self.messages if not
isinstance(m, messages.UndefinedName) or
m.message_args[0] != node_name]
# Bind name to global scope if it doesn't exist already.
global_scope.setdefault(node_name, node_value)
# Bind name to non-global scopes, but as already "used".
node_value.used = (global_scope, node)
for scope in self.scopeStack[global_scope_index + 1:]:
scope[node_name] = node_value
NONLOCAL = GLOBAL
def GENERATOREXP(self, node):
self.pushScope(GeneratorScope)
self.handleChildren(node)
self.popScope()
LISTCOMP = handleChildren if PY2 else GENERATOREXP
DICTCOMP = SETCOMP = GENERATOREXP
def NAME(self, node):
"""
Handle occurrence of Name (which can be a load/store/delete access.)
"""
# Locate the name in locals / function / globals scopes.
if isinstance(node.ctx, (ast.Load, ast.AugLoad)):
self.handleNodeLoad(node)
if (node.id == 'locals' and isinstance(self.scope, FunctionScope) and
isinstance(node.parent, ast.Call)):
# we are doing locals() call in current scope
self.scope.usesLocals = True
elif isinstance(node.ctx, (ast.Store, ast.AugStore, ast.Param)):
self.handleNodeStore(node)
elif isinstance(node.ctx, ast.Del):
self.handleNodeDelete(node)
else:
# Unknown context
raise RuntimeError("Got impossible expression context: %r" % (node.ctx,))
def CONTINUE(self, node):
# Walk the tree up until we see a loop (OK), a function or class
# definition (not OK), for 'continue', a finally block (not OK), or
# the top module scope (not OK)
n = node
while hasattr(n, 'parent'):
n, n_child = n.parent, n
if isinstance(n, LOOP_TYPES):
# Doesn't apply unless it's in the loop itself
if n_child not in n.orelse:
return
if isinstance(n, (ast.FunctionDef, ast.ClassDef)):
break
# Handle Try/TryFinally difference in Python < and >= 3.3
if hasattr(n, 'finalbody') and isinstance(node, ast.Continue):
if n_child in n.finalbody:
self.report(messages.ContinueInFinally, node)
return
if isinstance(node, ast.Continue):
self.report(messages.ContinueOutsideLoop, node)
else: # ast.Break
self.report(messages.BreakOutsideLoop, node)
BREAK = CONTINUE
def RETURN(self, node):
if isinstance(self.scope, (ClassScope, ModuleScope)):
self.report(messages.ReturnOutsideFunction, node)
return
if (
node.value and
hasattr(self.scope, 'returnValue') and
not self.scope.returnValue
):
self.scope.returnValue = node.value
self.handleNode(node.value, node)
def YIELD(self, node):
if isinstance(self.scope, (ClassScope, ModuleScope)):
self.report(messages.YieldOutsideFunction, node)
return
self.scope.isGenerator = True
self.handleNode(node.value, node)
AWAIT = YIELDFROM = YIELD
def FUNCTIONDEF(self, node):
for deco in node.decorator_list:
self.handleNode(deco, node)
self.LAMBDA(node)
self.addBinding(node, FunctionDefinition(node.name, node))
# doctest does not process doctest within a doctest,
# or in nested functions.
if (self.withDoctest and
not self._in_doctest() and
not isinstance(self.scope, FunctionScope)):
self.deferFunction(lambda: self.handleDoctests(node))
ASYNCFUNCTIONDEF = FUNCTIONDEF
def LAMBDA(self, node):
args = []
annotations = []
if PY2:
def addArgs(arglist):
for arg in arglist:
if isinstance(arg, ast.Tuple):
addArgs(arg.elts)
else:
args.append(arg.id)
addArgs(node.args.args)
defaults = node.args.defaults
else:
for arg in node.args.args + node.args.kwonlyargs:
args.append(arg.arg)
annotations.append(arg.annotation)
defaults = node.args.defaults + node.args.kw_defaults
# Only for Python3 FunctionDefs
is_py3_func = hasattr(node, 'returns')
for arg_name in ('vararg', 'kwarg'):
wildcard = getattr(node.args, arg_name)
if not wildcard:
continue
args.append(wildcard if PY2 else wildcard.arg)
if is_py3_func:
if PY2: # Python 2.7
argannotation = arg_name + 'annotation'
annotations.append(getattr(node.args, argannotation))
else: # Python >= 3.4
annotations.append(wildcard.annotation)
if is_py3_func:
annotations.append(node.returns)
if len(set(args)) < len(args):
for (idx, arg) in enumerate(args):
if arg in args[:idx]:
self.report(messages.DuplicateArgument, node, arg)
for annotation in annotations:
self.handleAnnotation(annotation, node)
for default in defaults:
self.handleNode(default, node)
def runFunction():
self.pushScope()
self.handleChildren(node, omit='decorator_list')
def checkUnusedAssignments():
"""
Check to see if any assignments have not been used.
"""
for name, binding in self.scope.unusedAssignments():
self.report(messages.UnusedVariable, binding.source, name)
self.deferAssignment(checkUnusedAssignments)
if PY2:
def checkReturnWithArgumentInsideGenerator():
"""
Check to see if there is any return statement with
arguments but the function is a generator.
"""
if self.scope.isGenerator and self.scope.returnValue:
self.report(messages.ReturnWithArgsInsideGenerator,
self.scope.returnValue)
self.deferAssignment(checkReturnWithArgumentInsideGenerator)
self.popScope()
self.deferFunction(runFunction)
def ARGUMENTS(self, node):
self.handleChildren(node, omit=('defaults', 'kw_defaults'))
if PY2:
scope_node = self.getScopeNode(node)
if node.vararg:
self.addBinding(node, Argument(node.vararg, scope_node))
if node.kwarg:
self.addBinding(node, Argument(node.kwarg, scope_node))
def ARG(self, node):
self.addBinding(node, Argument(node.arg, self.getScopeNode(node)))
def CLASSDEF(self, node):
"""
Check names used in a class definition, including its decorators, base
classes, and the body of its definition. Additionally, add its name to
the current scope.
"""
for deco in node.decorator_list:
self.handleNode(deco, node)
for baseNode in node.bases:
self.handleNode(baseNode, node)
if not PY2:
for keywordNode in node.keywords:
self.handleNode(keywordNode, node)
self.pushScope(ClassScope)
# doctest does not process doctest within a doctest
# classes within classes are processed.
if (self.withDoctest and
not self._in_doctest() and
not isinstance(self.scope, FunctionScope)):
self.deferFunction(lambda: self.handleDoctests(node))
for stmt in node.body:
self.handleNode(stmt, node)
self.popScope()
self.addBinding(node, ClassDefinition(node.name, node))
def AUGASSIGN(self, node):
self.handleNodeLoad(node.target)
self.handleNode(node.value, node)
self.handleNode(node.target, node)
def TUPLE(self, node):
if not PY2 and isinstance(node.ctx, ast.Store):
# Python 3 advanced tuple unpacking: a, *b, c = d.
# Only one starred expression is allowed, and no more than 1<<8
# assignments are allowed before a stared expression. There is
# also a limit of 1<<24 expressions after the starred expression,
# which is impossible to test due to memory restrictions, but we
# add it here anyway
has_starred = False
star_loc = -1
for i, n in enumerate(node.elts):
if isinstance(n, ast.Starred):
if has_starred:
self.report(messages.TwoStarredExpressions, node)
# The SyntaxError doesn't distinguish two from more
# than two.
break
has_starred = True
star_loc = i
if star_loc >= 1 << 8 or len(node.elts) - star_loc - 1 >= 1 << 24:
self.report(messages.TooManyExpressionsInStarredAssignment, node)
self.handleChildren(node)
LIST = TUPLE
def IMPORT(self, node):
for alias in node.names:
if '.' in alias.name and not alias.asname:
importation = SubmoduleImportation(alias.name, node)
else:
name = alias.asname or alias.name
importation = Importation(name, node, alias.name)
self.addBinding(node, importation)
def IMPORTFROM(self, node):
if node.module == '__future__':
if not self.futuresAllowed:
self.report(messages.LateFutureImport,
node, [n.name for n in node.names])
else:
self.futuresAllowed = False
module = ('.' * node.level) + (node.module or '')
for alias in node.names:
name = alias.asname or alias.name
if node.module == '__future__':
importation = FutureImportation(name, node, self.scope)
if alias.name not in __future__.all_feature_names:
self.report(messages.FutureFeatureNotDefined,
node, alias.name)
if alias.name == 'annotations':
self.annotationsFutureEnabled = True
elif alias.name == '*':
# Only Python 2, local import * is a SyntaxWarning
if not PY2 and not isinstance(self.scope, ModuleScope):
self.report(messages.ImportStarNotPermitted,
node, module)
continue
self.scope.importStarred = True
self.report(messages.ImportStarUsed, node, module)
importation = StarImportation(module, node)
else:
importation = ImportationFrom(name, node,
module, alias.name)
self.addBinding(node, importation)
def TRY(self, node):
handler_names = []
# List the exception handlers
for i, handler in enumerate(node.handlers):
if isinstance(handler.type, ast.Tuple):
for exc_type in handler.type.elts:
handler_names.append(getNodeName(exc_type))
elif handler.type:
handler_names.append(getNodeName(handler.type))
if handler.type is None and i < len(node.handlers) - 1:
self.report(messages.DefaultExceptNotLast, handler)
# Memorize the except handlers and process the body
self.exceptHandlers.append(handler_names)
for child in node.body:
self.handleNode(child, node)
self.exceptHandlers.pop()
# Process the other nodes: "except:", "else:", "finally:"
self.handleChildren(node, omit='body')
TRYEXCEPT = TRY
def EXCEPTHANDLER(self, node):
if PY2 or node.name is None:
self.handleChildren(node)
return
# If the name already exists in the scope, modify state of existing
# binding.
if node.name in self.scope:
self.handleNodeStore(node)
# 3.x: the name of the exception, which is not a Name node, but a
# simple string, creates a local that is only bound within the scope of
# the except: block. As such, temporarily remove the existing binding
# to more accurately determine if the name is used in the except:
# block.
try:
prev_definition = self.scope.pop(node.name)
except KeyError:
prev_definition = None
self.handleNodeStore(node)
self.handleChildren(node)
# See discussion on https://github.com/PyCQA/pyflakes/pull/59
# We're removing the local name since it's being unbound after leaving
# the except: block and it's always unbound if the except: block is
# never entered. This will cause an "undefined name" error raised if
# the checked code tries to use the name afterwards.
#
# Unless it's been removed already. Then do nothing.
try:
binding = self.scope.pop(node.name)
except KeyError:
pass
else:
if not binding.used:
self.report(messages.UnusedVariable, node, node.name)
# Restore.
if prev_definition:
self.scope[node.name] = prev_definition
def ANNASSIGN(self, node):
if node.value:
# Only bind the *targets* if the assignment has a value.
# Otherwise it's not really ast.Store and shouldn't silence
# UndefinedLocal warnings.
self.handleNode(node.target, node)
self.handleAnnotation(node.annotation, node)
if node.value:
# If the assignment has value, handle the *value* now.
self.handleNode(node.value, node)
def COMPARE(self, node):
literals = (ast.Str, ast.Num)
if not PY2:
literals += (ast.Bytes,)
left = node.left
for op, right in zip(node.ops, node.comparators):
if (isinstance(op, (ast.Is, ast.IsNot)) and
(isinstance(left, literals) or isinstance(right, literals))):
self.report(messages.IsLiteral, node)
left = right
self.handleChildren(node)
|
PyCQA/pyflakes | pyflakes/checker.py | Importation.source_statement | python | def source_statement(self):
if self._has_alias():
return 'import %s as %s' % (self.fullName, self.name)
else:
return 'import %s' % self.fullName | Generate a source statement equivalent to the import. | train | https://github.com/PyCQA/pyflakes/blob/232cb1d27ee134bf96adc8f37e53589dc259b159/pyflakes/checker.py#L265-L270 | [
"def _has_alias(self):\n \"\"\"Return whether importation needs an as clause.\"\"\"\n return not self.fullName.split('.')[-1] == self.name\n"
] | class Importation(Definition):
"""
A binding created by an import statement.
@ivar fullName: The complete name given to the import statement,
possibly including multiple dotted components.
@type fullName: C{str}
"""
def __init__(self, name, source, full_name=None):
self.fullName = full_name or name
self.redefined = []
super(Importation, self).__init__(name, source)
def redefines(self, other):
if isinstance(other, SubmoduleImportation):
# See note in SubmoduleImportation about RedefinedWhileUnused
return self.fullName == other.fullName
return isinstance(other, Definition) and self.name == other.name
def _has_alias(self):
"""Return whether importation needs an as clause."""
return not self.fullName.split('.')[-1] == self.name
@property
def __str__(self):
"""Return import full name with alias."""
if self._has_alias():
return self.fullName + ' as ' + self.name
else:
return self.fullName
|
PyCQA/pyflakes | pyflakes/checker.py | Checker.deferFunction | python | def deferFunction(self, callable):
self._deferredFunctions.append((callable, self.scopeStack[:], self.offset)) | Schedule a function handler to be called just before completion.
This is used for handling function bodies, which must be deferred
because code later in the file might modify the global scope. When
`callable` is called, the scope at the time this is called will be
restored, however it will contain any new bindings added to it. | train | https://github.com/PyCQA/pyflakes/blob/232cb1d27ee134bf96adc8f37e53589dc259b159/pyflakes/checker.py#L694-L703 | null | class Checker(object):
"""
I check the cleanliness and sanity of Python code.
@ivar _deferredFunctions: Tracking list used by L{deferFunction}. Elements
of the list are two-tuples. The first element is the callable passed
to L{deferFunction}. The second element is a copy of the scope stack
at the time L{deferFunction} was called.
@ivar _deferredAssignments: Similar to C{_deferredFunctions}, but for
callables which are deferred assignment checks.
"""
_ast_node_scope = {
ast.Module: ModuleScope,
ast.ClassDef: ClassScope,
ast.FunctionDef: FunctionScope,
ast.Lambda: FunctionScope,
ast.ListComp: GeneratorScope,
ast.SetComp: GeneratorScope,
ast.GeneratorExp: GeneratorScope,
ast.DictComp: GeneratorScope,
}
if PY35_PLUS:
_ast_node_scope[ast.AsyncFunctionDef] = FunctionScope,
nodeDepth = 0
offset = None
traceTree = False
builtIns = set(builtin_vars).union(_MAGIC_GLOBALS)
_customBuiltIns = os.environ.get('PYFLAKES_BUILTINS')
if _customBuiltIns:
builtIns.update(_customBuiltIns.split(','))
del _customBuiltIns
# TODO: file_tokens= is required to perform checks on type comments,
# eventually make this a required positional argument. For now it
# is defaulted to `()` for api compatibility.
def __init__(self, tree, filename='(none)', builtins=None,
withDoctest='PYFLAKES_DOCTEST' in os.environ, file_tokens=()):
self._nodeHandlers = {}
self._deferredFunctions = []
self._deferredAssignments = []
self.deadScopes = []
self.messages = []
self.filename = filename
if builtins:
self.builtIns = self.builtIns.union(builtins)
self.withDoctest = withDoctest
try:
self.scopeStack = [Checker._ast_node_scope[type(tree)]()]
except KeyError:
raise RuntimeError('No scope implemented for the node %r' % tree)
self.exceptHandlers = [()]
self.root = tree
self._type_comments = _collect_type_comments(tree, file_tokens)
for builtin in self.builtIns:
self.addBinding(None, Builtin(builtin))
self.handleChildren(tree)
self.runDeferred(self._deferredFunctions)
# Set _deferredFunctions to None so that deferFunction will fail
# noisily if called after we've run through the deferred functions.
self._deferredFunctions = None
self.runDeferred(self._deferredAssignments)
# Set _deferredAssignments to None so that deferAssignment will fail
# noisily if called after we've run through the deferred assignments.
self._deferredAssignments = None
del self.scopeStack[1:]
self.popScope()
self.checkDeadScopes()
def deferAssignment(self, callable):
"""
Schedule an assignment handler to be called just after deferred
function handlers.
"""
self._deferredAssignments.append((callable, self.scopeStack[:], self.offset))
def runDeferred(self, deferred):
"""
Run the callables in C{deferred} using their associated scope stack.
"""
for handler, scope, offset in deferred:
self.scopeStack = scope
self.offset = offset
handler()
def _in_doctest(self):
return (len(self.scopeStack) >= 2 and
isinstance(self.scopeStack[1], DoctestScope))
@property
def futuresAllowed(self):
if not all(isinstance(scope, ModuleScope)
for scope in self.scopeStack):
return False
return self.scope._futures_allowed
@futuresAllowed.setter
def futuresAllowed(self, value):
assert value is False
if isinstance(self.scope, ModuleScope):
self.scope._futures_allowed = False
@property
def annotationsFutureEnabled(self):
scope = self.scopeStack[0]
if not isinstance(scope, ModuleScope):
return False
return scope._annotations_future_enabled
@annotationsFutureEnabled.setter
def annotationsFutureEnabled(self, value):
assert value is True
assert isinstance(self.scope, ModuleScope)
self.scope._annotations_future_enabled = True
@property
def scope(self):
return self.scopeStack[-1]
def popScope(self):
self.deadScopes.append(self.scopeStack.pop())
def checkDeadScopes(self):
"""
Look at scopes which have been fully examined and report names in them
which were imported but unused.
"""
for scope in self.deadScopes:
# imports in classes are public members
if isinstance(scope, ClassScope):
continue
all_binding = scope.get('__all__')
if all_binding and not isinstance(all_binding, ExportBinding):
all_binding = None
if all_binding:
all_names = set(all_binding.names)
undefined = all_names.difference(scope)
else:
all_names = undefined = []
if undefined:
if not scope.importStarred and \
os.path.basename(self.filename) != '__init__.py':
# Look for possible mistakes in the export list
for name in undefined:
self.report(messages.UndefinedExport,
scope['__all__'].source, name)
# mark all import '*' as used by the undefined in __all__
if scope.importStarred:
from_list = []
for binding in scope.values():
if isinstance(binding, StarImportation):
binding.used = all_binding
from_list.append(binding.fullName)
# report * usage, with a list of possible sources
from_list = ', '.join(sorted(from_list))
for name in undefined:
self.report(messages.ImportStarUsage,
scope['__all__'].source, name, from_list)
# Look for imported names that aren't used.
for value in scope.values():
if isinstance(value, Importation):
used = value.used or value.name in all_names
if not used:
messg = messages.UnusedImport
self.report(messg, value.source, str(value))
for node in value.redefined:
if isinstance(self.getParent(node), FOR_TYPES):
messg = messages.ImportShadowedByLoopVar
elif used:
continue
else:
messg = messages.RedefinedWhileUnused
self.report(messg, node, value.name, value.source)
def pushScope(self, scopeClass=FunctionScope):
self.scopeStack.append(scopeClass())
def report(self, messageClass, *args, **kwargs):
self.messages.append(messageClass(self.filename, *args, **kwargs))
def getParent(self, node):
# Lookup the first parent which is not Tuple, List or Starred
while True:
node = node.parent
if not hasattr(node, 'elts') and not hasattr(node, 'ctx'):
return node
def getCommonAncestor(self, lnode, rnode, stop):
if stop in (lnode, rnode) or not (hasattr(lnode, 'parent') and
hasattr(rnode, 'parent')):
return None
if lnode is rnode:
return lnode
if (lnode.depth > rnode.depth):
return self.getCommonAncestor(lnode.parent, rnode, stop)
if (lnode.depth < rnode.depth):
return self.getCommonAncestor(lnode, rnode.parent, stop)
return self.getCommonAncestor(lnode.parent, rnode.parent, stop)
def descendantOf(self, node, ancestors, stop):
for a in ancestors:
if self.getCommonAncestor(node, a, stop):
return True
return False
def _getAncestor(self, node, ancestor_type):
parent = node
while True:
if parent is self.root:
return None
parent = self.getParent(parent)
if isinstance(parent, ancestor_type):
return parent
def getScopeNode(self, node):
return self._getAncestor(node, tuple(Checker._ast_node_scope.keys()))
def differentForks(self, lnode, rnode):
"""True, if lnode and rnode are located on different forks of IF/TRY"""
ancestor = self.getCommonAncestor(lnode, rnode, self.root)
parts = getAlternatives(ancestor)
if parts:
for items in parts:
if self.descendantOf(lnode, items, ancestor) ^ \
self.descendantOf(rnode, items, ancestor):
return True
return False
def addBinding(self, node, value):
"""
Called when a binding is altered.
- `node` is the statement responsible for the change
- `value` is the new value, a Binding instance
"""
# assert value.source in (node, node.parent):
for scope in self.scopeStack[::-1]:
if value.name in scope:
break
existing = scope.get(value.name)
if (existing and not isinstance(existing, Builtin) and
not self.differentForks(node, existing.source)):
parent_stmt = self.getParent(value.source)
if isinstance(existing, Importation) and isinstance(parent_stmt, FOR_TYPES):
self.report(messages.ImportShadowedByLoopVar,
node, value.name, existing.source)
elif scope is self.scope:
if (isinstance(parent_stmt, ast.comprehension) and
not isinstance(self.getParent(existing.source),
(FOR_TYPES, ast.comprehension))):
self.report(messages.RedefinedInListComp,
node, value.name, existing.source)
elif not existing.used and value.redefines(existing):
if value.name != '_' or isinstance(existing, Importation):
if not is_typing_overload(existing, self.scopeStack):
self.report(messages.RedefinedWhileUnused,
node, value.name, existing.source)
elif isinstance(existing, Importation) and value.redefines(existing):
existing.redefined.append(node)
if value.name in self.scope:
# then assume the rebound name is used as a global or within a loop
value.used = self.scope[value.name].used
self.scope[value.name] = value
def getNodeHandler(self, node_class):
try:
return self._nodeHandlers[node_class]
except KeyError:
nodeType = getNodeType(node_class)
self._nodeHandlers[node_class] = handler = getattr(self, nodeType)
return handler
def handleNodeLoad(self, node):
name = getNodeName(node)
if not name:
return
in_generators = None
importStarred = None
# try enclosing function scopes and global scope
for scope in self.scopeStack[-1::-1]:
if isinstance(scope, ClassScope):
if not PY2 and name == '__class__':
return
elif in_generators is False:
# only generators used in a class scope can access the
# names of the class. this is skipped during the first
# iteration
continue
if (name == 'print' and
isinstance(scope.get(name, None), Builtin)):
parent = self.getParent(node)
if (isinstance(parent, ast.BinOp) and
isinstance(parent.op, ast.RShift)):
self.report(messages.InvalidPrintSyntax, node)
try:
scope[name].used = (self.scope, node)
# if the name of SubImportation is same as
# alias of other Importation and the alias
# is used, SubImportation also should be marked as used.
n = scope[name]
if isinstance(n, Importation) and n._has_alias():
try:
scope[n.fullName].used = (self.scope, node)
except KeyError:
pass
except KeyError:
pass
else:
return
importStarred = importStarred or scope.importStarred
if in_generators is not False:
in_generators = isinstance(scope, GeneratorScope)
if importStarred:
from_list = []
for scope in self.scopeStack[-1::-1]:
for binding in scope.values():
if isinstance(binding, StarImportation):
# mark '*' imports as used for each scope
binding.used = (self.scope, node)
from_list.append(binding.fullName)
# report * usage, with a list of possible sources
from_list = ', '.join(sorted(from_list))
self.report(messages.ImportStarUsage, node, name, from_list)
return
if name == '__path__' and os.path.basename(self.filename) == '__init__.py':
# the special name __path__ is valid only in packages
return
if name == '__module__' and isinstance(self.scope, ClassScope):
return
# protected with a NameError handler?
if 'NameError' not in self.exceptHandlers[-1]:
self.report(messages.UndefinedName, node, name)
def handleNodeStore(self, node):
name = getNodeName(node)
if not name:
return
# if the name hasn't already been defined in the current scope
if isinstance(self.scope, FunctionScope) and name not in self.scope:
# for each function or module scope above us
for scope in self.scopeStack[:-1]:
if not isinstance(scope, (FunctionScope, ModuleScope)):
continue
# if the name was defined in that scope, and the name has
# been accessed already in the current scope, and hasn't
# been declared global
used = name in scope and scope[name].used
if used and used[0] is self.scope and name not in self.scope.globals:
# then it's probably a mistake
self.report(messages.UndefinedLocal,
scope[name].used[1], name, scope[name].source)
break
parent_stmt = self.getParent(node)
if isinstance(parent_stmt, (FOR_TYPES, ast.comprehension)) or (
parent_stmt != node.parent and
not self.isLiteralTupleUnpacking(parent_stmt)):
binding = Binding(name, node)
elif name == '__all__' and isinstance(self.scope, ModuleScope):
binding = ExportBinding(name, node.parent, self.scope)
elif isinstance(getattr(node, 'ctx', None), ast.Param):
binding = Argument(name, self.getScopeNode(node))
else:
binding = Assignment(name, node)
self.addBinding(node, binding)
def handleNodeDelete(self, node):
def on_conditional_branch():
"""
Return `True` if node is part of a conditional body.
"""
current = getattr(node, 'parent', None)
while current:
if isinstance(current, (ast.If, ast.While, ast.IfExp)):
return True
current = getattr(current, 'parent', None)
return False
name = getNodeName(node)
if not name:
return
if on_conditional_branch():
# We cannot predict if this conditional branch is going to
# be executed.
return
if isinstance(self.scope, FunctionScope) and name in self.scope.globals:
self.scope.globals.remove(name)
else:
try:
del self.scope[name]
except KeyError:
self.report(messages.UndefinedName, node, name)
def _handle_type_comments(self, node):
for (lineno, col_offset), comment in self._type_comments.get(node, ()):
comment = comment.split(':', 1)[1].strip()
func_match = TYPE_FUNC_RE.match(comment)
if func_match:
parts = (
func_match.group(1).replace('*', ''),
func_match.group(2).strip(),
)
else:
parts = (comment,)
for part in parts:
if PY2:
part = part.replace('...', 'Ellipsis')
self.deferFunction(functools.partial(
self.handleStringAnnotation,
part, DummyNode(lineno, col_offset), lineno, col_offset,
messages.CommentAnnotationSyntaxError,
))
def handleChildren(self, tree, omit=None):
self._handle_type_comments(tree)
for node in iter_child_nodes(tree, omit=omit):
self.handleNode(node, tree)
def isLiteralTupleUnpacking(self, node):
if isinstance(node, ast.Assign):
for child in node.targets + [node.value]:
if not hasattr(child, 'elts'):
return False
return True
def isDocstring(self, node):
"""
Determine if the given node is a docstring, as long as it is at the
correct place in the node tree.
"""
return isinstance(node, ast.Str) or (isinstance(node, ast.Expr) and
isinstance(node.value, ast.Str))
def getDocstring(self, node):
if isinstance(node, ast.Expr):
node = node.value
if not isinstance(node, ast.Str):
return (None, None)
if PYPY or PY38_PLUS:
doctest_lineno = node.lineno - 1
else:
# Computed incorrectly if the docstring has backslash
doctest_lineno = node.lineno - node.s.count('\n') - 1
return (node.s, doctest_lineno)
def handleNode(self, node, parent):
if node is None:
return
if self.offset and getattr(node, 'lineno', None) is not None:
node.lineno += self.offset[0]
node.col_offset += self.offset[1]
if self.traceTree:
print(' ' * self.nodeDepth + node.__class__.__name__)
if self.futuresAllowed and not (isinstance(node, ast.ImportFrom) or
self.isDocstring(node)):
self.futuresAllowed = False
self.nodeDepth += 1
node.depth = self.nodeDepth
node.parent = parent
try:
handler = self.getNodeHandler(node.__class__)
handler(node)
finally:
self.nodeDepth -= 1
if self.traceTree:
print(' ' * self.nodeDepth + 'end ' + node.__class__.__name__)
_getDoctestExamples = doctest.DocTestParser().get_examples
def handleDoctests(self, node):
try:
if hasattr(node, 'docstring'):
docstring = node.docstring
# This is just a reasonable guess. In Python 3.7, docstrings no
# longer have line numbers associated with them. This will be
# incorrect if there are empty lines between the beginning
# of the function and the docstring.
node_lineno = node.lineno
if hasattr(node, 'args'):
node_lineno = max([node_lineno] +
[arg.lineno for arg in node.args.args])
else:
(docstring, node_lineno) = self.getDocstring(node.body[0])
examples = docstring and self._getDoctestExamples(docstring)
except (ValueError, IndexError):
# e.g. line 6 of the docstring for <string> has inconsistent
# leading whitespace: ...
return
if not examples:
return
# Place doctest in module scope
saved_stack = self.scopeStack
self.scopeStack = [self.scopeStack[0]]
node_offset = self.offset or (0, 0)
self.pushScope(DoctestScope)
self.addBinding(None, Builtin('_'))
for example in examples:
try:
tree = ast.parse(example.source, "<doctest>")
except SyntaxError:
e = sys.exc_info()[1]
if PYPY:
e.offset += 1
position = (node_lineno + example.lineno + e.lineno,
example.indent + 4 + (e.offset or 0))
self.report(messages.DoctestSyntaxError, node, position)
else:
self.offset = (node_offset[0] + node_lineno + example.lineno,
node_offset[1] + example.indent + 4)
self.handleChildren(tree)
self.offset = node_offset
self.popScope()
self.scopeStack = saved_stack
def handleStringAnnotation(self, s, node, ref_lineno, ref_col_offset, err):
try:
tree = ast.parse(s)
except SyntaxError:
self.report(err, node, s)
return
body = tree.body
if len(body) != 1 or not isinstance(body[0], ast.Expr):
self.report(err, node, s)
return
parsed_annotation = tree.body[0].value
for descendant in ast.walk(parsed_annotation):
if (
'lineno' in descendant._attributes and
'col_offset' in descendant._attributes
):
descendant.lineno = ref_lineno
descendant.col_offset = ref_col_offset
self.handleNode(parsed_annotation, node)
def handleAnnotation(self, annotation, node):
if isinstance(annotation, ast.Str):
# Defer handling forward annotation.
self.deferFunction(functools.partial(
self.handleStringAnnotation,
annotation.s,
node,
annotation.lineno,
annotation.col_offset,
messages.ForwardAnnotationSyntaxError,
))
elif self.annotationsFutureEnabled:
self.deferFunction(lambda: self.handleNode(annotation, node))
else:
self.handleNode(annotation, node)
def ignore(self, node):
pass
# "stmt" type nodes
DELETE = PRINT = FOR = ASYNCFOR = WHILE = IF = WITH = WITHITEM = \
ASYNCWITH = ASYNCWITHITEM = TRYFINALLY = EXEC = \
EXPR = ASSIGN = handleChildren
PASS = ignore
# "expr" type nodes
BOOLOP = BINOP = UNARYOP = IFEXP = SET = \
CALL = REPR = ATTRIBUTE = SUBSCRIPT = \
STARRED = NAMECONSTANT = handleChildren
NUM = STR = BYTES = ELLIPSIS = CONSTANT = ignore
# "slice" type nodes
SLICE = EXTSLICE = INDEX = handleChildren
# expression contexts are node instances too, though being constants
LOAD = STORE = DEL = AUGLOAD = AUGSTORE = PARAM = ignore
# same for operators
AND = OR = ADD = SUB = MULT = DIV = MOD = POW = LSHIFT = RSHIFT = \
BITOR = BITXOR = BITAND = FLOORDIV = INVERT = NOT = UADD = USUB = \
EQ = NOTEQ = LT = LTE = GT = GTE = IS = ISNOT = IN = NOTIN = \
MATMULT = ignore
def RAISE(self, node):
self.handleChildren(node)
arg = get_raise_argument(node)
if isinstance(arg, ast.Call):
if is_notimplemented_name_node(arg.func):
# Handle "raise NotImplemented(...)"
self.report(messages.RaiseNotImplemented, node)
elif is_notimplemented_name_node(arg):
# Handle "raise NotImplemented"
self.report(messages.RaiseNotImplemented, node)
# additional node types
COMPREHENSION = KEYWORD = FORMATTEDVALUE = JOINEDSTR = handleChildren
def DICT(self, node):
# Complain if there are duplicate keys with different values
# If they have the same value it's not going to cause potentially
# unexpected behaviour so we'll not complain.
keys = [
convert_to_value(key) for key in node.keys
]
key_counts = counter(keys)
duplicate_keys = [
key for key, count in key_counts.items()
if count > 1
]
for key in duplicate_keys:
key_indices = [i for i, i_key in enumerate(keys) if i_key == key]
values = counter(
convert_to_value(node.values[index])
for index in key_indices
)
if any(count == 1 for value, count in values.items()):
for key_index in key_indices:
key_node = node.keys[key_index]
if isinstance(key, VariableKey):
self.report(messages.MultiValueRepeatedKeyVariable,
key_node,
key.name)
else:
self.report(
messages.MultiValueRepeatedKeyLiteral,
key_node,
key,
)
self.handleChildren(node)
def ASSERT(self, node):
if isinstance(node.test, ast.Tuple) and node.test.elts != []:
self.report(messages.AssertTuple, node)
self.handleChildren(node)
def GLOBAL(self, node):
"""
Keep track of globals declarations.
"""
global_scope_index = 1 if self._in_doctest() else 0
global_scope = self.scopeStack[global_scope_index]
# Ignore 'global' statement in global scope.
if self.scope is not global_scope:
# One 'global' statement can bind multiple (comma-delimited) names.
for node_name in node.names:
node_value = Assignment(node_name, node)
# Remove UndefinedName messages already reported for this name.
# TODO: if the global is not used in this scope, it does not
# become a globally defined name. See test_unused_global.
self.messages = [
m for m in self.messages if not
isinstance(m, messages.UndefinedName) or
m.message_args[0] != node_name]
# Bind name to global scope if it doesn't exist already.
global_scope.setdefault(node_name, node_value)
# Bind name to non-global scopes, but as already "used".
node_value.used = (global_scope, node)
for scope in self.scopeStack[global_scope_index + 1:]:
scope[node_name] = node_value
NONLOCAL = GLOBAL
def GENERATOREXP(self, node):
self.pushScope(GeneratorScope)
self.handleChildren(node)
self.popScope()
LISTCOMP = handleChildren if PY2 else GENERATOREXP
DICTCOMP = SETCOMP = GENERATOREXP
def NAME(self, node):
"""
Handle occurrence of Name (which can be a load/store/delete access.)
"""
# Locate the name in locals / function / globals scopes.
if isinstance(node.ctx, (ast.Load, ast.AugLoad)):
self.handleNodeLoad(node)
if (node.id == 'locals' and isinstance(self.scope, FunctionScope) and
isinstance(node.parent, ast.Call)):
# we are doing locals() call in current scope
self.scope.usesLocals = True
elif isinstance(node.ctx, (ast.Store, ast.AugStore, ast.Param)):
self.handleNodeStore(node)
elif isinstance(node.ctx, ast.Del):
self.handleNodeDelete(node)
else:
# Unknown context
raise RuntimeError("Got impossible expression context: %r" % (node.ctx,))
def CONTINUE(self, node):
# Walk the tree up until we see a loop (OK), a function or class
# definition (not OK), for 'continue', a finally block (not OK), or
# the top module scope (not OK)
n = node
while hasattr(n, 'parent'):
n, n_child = n.parent, n
if isinstance(n, LOOP_TYPES):
# Doesn't apply unless it's in the loop itself
if n_child not in n.orelse:
return
if isinstance(n, (ast.FunctionDef, ast.ClassDef)):
break
# Handle Try/TryFinally difference in Python < and >= 3.3
if hasattr(n, 'finalbody') and isinstance(node, ast.Continue):
if n_child in n.finalbody:
self.report(messages.ContinueInFinally, node)
return
if isinstance(node, ast.Continue):
self.report(messages.ContinueOutsideLoop, node)
else: # ast.Break
self.report(messages.BreakOutsideLoop, node)
BREAK = CONTINUE
def RETURN(self, node):
if isinstance(self.scope, (ClassScope, ModuleScope)):
self.report(messages.ReturnOutsideFunction, node)
return
if (
node.value and
hasattr(self.scope, 'returnValue') and
not self.scope.returnValue
):
self.scope.returnValue = node.value
self.handleNode(node.value, node)
def YIELD(self, node):
if isinstance(self.scope, (ClassScope, ModuleScope)):
self.report(messages.YieldOutsideFunction, node)
return
self.scope.isGenerator = True
self.handleNode(node.value, node)
AWAIT = YIELDFROM = YIELD
def FUNCTIONDEF(self, node):
for deco in node.decorator_list:
self.handleNode(deco, node)
self.LAMBDA(node)
self.addBinding(node, FunctionDefinition(node.name, node))
# doctest does not process doctest within a doctest,
# or in nested functions.
if (self.withDoctest and
not self._in_doctest() and
not isinstance(self.scope, FunctionScope)):
self.deferFunction(lambda: self.handleDoctests(node))
ASYNCFUNCTIONDEF = FUNCTIONDEF
def LAMBDA(self, node):
args = []
annotations = []
if PY2:
def addArgs(arglist):
for arg in arglist:
if isinstance(arg, ast.Tuple):
addArgs(arg.elts)
else:
args.append(arg.id)
addArgs(node.args.args)
defaults = node.args.defaults
else:
for arg in node.args.args + node.args.kwonlyargs:
args.append(arg.arg)
annotations.append(arg.annotation)
defaults = node.args.defaults + node.args.kw_defaults
# Only for Python3 FunctionDefs
is_py3_func = hasattr(node, 'returns')
for arg_name in ('vararg', 'kwarg'):
wildcard = getattr(node.args, arg_name)
if not wildcard:
continue
args.append(wildcard if PY2 else wildcard.arg)
if is_py3_func:
if PY2: # Python 2.7
argannotation = arg_name + 'annotation'
annotations.append(getattr(node.args, argannotation))
else: # Python >= 3.4
annotations.append(wildcard.annotation)
if is_py3_func:
annotations.append(node.returns)
if len(set(args)) < len(args):
for (idx, arg) in enumerate(args):
if arg in args[:idx]:
self.report(messages.DuplicateArgument, node, arg)
for annotation in annotations:
self.handleAnnotation(annotation, node)
for default in defaults:
self.handleNode(default, node)
def runFunction():
self.pushScope()
self.handleChildren(node, omit='decorator_list')
def checkUnusedAssignments():
"""
Check to see if any assignments have not been used.
"""
for name, binding in self.scope.unusedAssignments():
self.report(messages.UnusedVariable, binding.source, name)
self.deferAssignment(checkUnusedAssignments)
if PY2:
def checkReturnWithArgumentInsideGenerator():
"""
Check to see if there is any return statement with
arguments but the function is a generator.
"""
if self.scope.isGenerator and self.scope.returnValue:
self.report(messages.ReturnWithArgsInsideGenerator,
self.scope.returnValue)
self.deferAssignment(checkReturnWithArgumentInsideGenerator)
self.popScope()
self.deferFunction(runFunction)
def ARGUMENTS(self, node):
self.handleChildren(node, omit=('defaults', 'kw_defaults'))
if PY2:
scope_node = self.getScopeNode(node)
if node.vararg:
self.addBinding(node, Argument(node.vararg, scope_node))
if node.kwarg:
self.addBinding(node, Argument(node.kwarg, scope_node))
def ARG(self, node):
self.addBinding(node, Argument(node.arg, self.getScopeNode(node)))
def CLASSDEF(self, node):
"""
Check names used in a class definition, including its decorators, base
classes, and the body of its definition. Additionally, add its name to
the current scope.
"""
for deco in node.decorator_list:
self.handleNode(deco, node)
for baseNode in node.bases:
self.handleNode(baseNode, node)
if not PY2:
for keywordNode in node.keywords:
self.handleNode(keywordNode, node)
self.pushScope(ClassScope)
# doctest does not process doctest within a doctest
# classes within classes are processed.
if (self.withDoctest and
not self._in_doctest() and
not isinstance(self.scope, FunctionScope)):
self.deferFunction(lambda: self.handleDoctests(node))
for stmt in node.body:
self.handleNode(stmt, node)
self.popScope()
self.addBinding(node, ClassDefinition(node.name, node))
def AUGASSIGN(self, node):
self.handleNodeLoad(node.target)
self.handleNode(node.value, node)
self.handleNode(node.target, node)
def TUPLE(self, node):
if not PY2 and isinstance(node.ctx, ast.Store):
# Python 3 advanced tuple unpacking: a, *b, c = d.
# Only one starred expression is allowed, and no more than 1<<8
# assignments are allowed before a stared expression. There is
# also a limit of 1<<24 expressions after the starred expression,
# which is impossible to test due to memory restrictions, but we
# add it here anyway
has_starred = False
star_loc = -1
for i, n in enumerate(node.elts):
if isinstance(n, ast.Starred):
if has_starred:
self.report(messages.TwoStarredExpressions, node)
# The SyntaxError doesn't distinguish two from more
# than two.
break
has_starred = True
star_loc = i
if star_loc >= 1 << 8 or len(node.elts) - star_loc - 1 >= 1 << 24:
self.report(messages.TooManyExpressionsInStarredAssignment, node)
self.handleChildren(node)
LIST = TUPLE
def IMPORT(self, node):
for alias in node.names:
if '.' in alias.name and not alias.asname:
importation = SubmoduleImportation(alias.name, node)
else:
name = alias.asname or alias.name
importation = Importation(name, node, alias.name)
self.addBinding(node, importation)
def IMPORTFROM(self, node):
if node.module == '__future__':
if not self.futuresAllowed:
self.report(messages.LateFutureImport,
node, [n.name for n in node.names])
else:
self.futuresAllowed = False
module = ('.' * node.level) + (node.module or '')
for alias in node.names:
name = alias.asname or alias.name
if node.module == '__future__':
importation = FutureImportation(name, node, self.scope)
if alias.name not in __future__.all_feature_names:
self.report(messages.FutureFeatureNotDefined,
node, alias.name)
if alias.name == 'annotations':
self.annotationsFutureEnabled = True
elif alias.name == '*':
# Only Python 2, local import * is a SyntaxWarning
if not PY2 and not isinstance(self.scope, ModuleScope):
self.report(messages.ImportStarNotPermitted,
node, module)
continue
self.scope.importStarred = True
self.report(messages.ImportStarUsed, node, module)
importation = StarImportation(module, node)
else:
importation = ImportationFrom(name, node,
module, alias.name)
self.addBinding(node, importation)
def TRY(self, node):
handler_names = []
# List the exception handlers
for i, handler in enumerate(node.handlers):
if isinstance(handler.type, ast.Tuple):
for exc_type in handler.type.elts:
handler_names.append(getNodeName(exc_type))
elif handler.type:
handler_names.append(getNodeName(handler.type))
if handler.type is None and i < len(node.handlers) - 1:
self.report(messages.DefaultExceptNotLast, handler)
# Memorize the except handlers and process the body
self.exceptHandlers.append(handler_names)
for child in node.body:
self.handleNode(child, node)
self.exceptHandlers.pop()
# Process the other nodes: "except:", "else:", "finally:"
self.handleChildren(node, omit='body')
TRYEXCEPT = TRY
def EXCEPTHANDLER(self, node):
if PY2 or node.name is None:
self.handleChildren(node)
return
# If the name already exists in the scope, modify state of existing
# binding.
if node.name in self.scope:
self.handleNodeStore(node)
# 3.x: the name of the exception, which is not a Name node, but a
# simple string, creates a local that is only bound within the scope of
# the except: block. As such, temporarily remove the existing binding
# to more accurately determine if the name is used in the except:
# block.
try:
prev_definition = self.scope.pop(node.name)
except KeyError:
prev_definition = None
self.handleNodeStore(node)
self.handleChildren(node)
# See discussion on https://github.com/PyCQA/pyflakes/pull/59
# We're removing the local name since it's being unbound after leaving
# the except: block and it's always unbound if the except: block is
# never entered. This will cause an "undefined name" error raised if
# the checked code tries to use the name afterwards.
#
# Unless it's been removed already. Then do nothing.
try:
binding = self.scope.pop(node.name)
except KeyError:
pass
else:
if not binding.used:
self.report(messages.UnusedVariable, node, node.name)
# Restore.
if prev_definition:
self.scope[node.name] = prev_definition
def ANNASSIGN(self, node):
if node.value:
# Only bind the *targets* if the assignment has a value.
# Otherwise it's not really ast.Store and shouldn't silence
# UndefinedLocal warnings.
self.handleNode(node.target, node)
self.handleAnnotation(node.annotation, node)
if node.value:
# If the assignment has value, handle the *value* now.
self.handleNode(node.value, node)
def COMPARE(self, node):
literals = (ast.Str, ast.Num)
if not PY2:
literals += (ast.Bytes,)
left = node.left
for op, right in zip(node.ops, node.comparators):
if (isinstance(op, (ast.Is, ast.IsNot)) and
(isinstance(left, literals) or isinstance(right, literals))):
self.report(messages.IsLiteral, node)
left = right
self.handleChildren(node)
|
PyCQA/pyflakes | pyflakes/checker.py | Checker.deferAssignment | python | def deferAssignment(self, callable):
self._deferredAssignments.append((callable, self.scopeStack[:], self.offset)) | Schedule an assignment handler to be called just after deferred
function handlers. | train | https://github.com/PyCQA/pyflakes/blob/232cb1d27ee134bf96adc8f37e53589dc259b159/pyflakes/checker.py#L705-L710 | null | class Checker(object):
"""
I check the cleanliness and sanity of Python code.
@ivar _deferredFunctions: Tracking list used by L{deferFunction}. Elements
of the list are two-tuples. The first element is the callable passed
to L{deferFunction}. The second element is a copy of the scope stack
at the time L{deferFunction} was called.
@ivar _deferredAssignments: Similar to C{_deferredFunctions}, but for
callables which are deferred assignment checks.
"""
_ast_node_scope = {
ast.Module: ModuleScope,
ast.ClassDef: ClassScope,
ast.FunctionDef: FunctionScope,
ast.Lambda: FunctionScope,
ast.ListComp: GeneratorScope,
ast.SetComp: GeneratorScope,
ast.GeneratorExp: GeneratorScope,
ast.DictComp: GeneratorScope,
}
if PY35_PLUS:
_ast_node_scope[ast.AsyncFunctionDef] = FunctionScope,
nodeDepth = 0
offset = None
traceTree = False
builtIns = set(builtin_vars).union(_MAGIC_GLOBALS)
_customBuiltIns = os.environ.get('PYFLAKES_BUILTINS')
if _customBuiltIns:
builtIns.update(_customBuiltIns.split(','))
del _customBuiltIns
# TODO: file_tokens= is required to perform checks on type comments,
# eventually make this a required positional argument. For now it
# is defaulted to `()` for api compatibility.
def __init__(self, tree, filename='(none)', builtins=None,
withDoctest='PYFLAKES_DOCTEST' in os.environ, file_tokens=()):
self._nodeHandlers = {}
self._deferredFunctions = []
self._deferredAssignments = []
self.deadScopes = []
self.messages = []
self.filename = filename
if builtins:
self.builtIns = self.builtIns.union(builtins)
self.withDoctest = withDoctest
try:
self.scopeStack = [Checker._ast_node_scope[type(tree)]()]
except KeyError:
raise RuntimeError('No scope implemented for the node %r' % tree)
self.exceptHandlers = [()]
self.root = tree
self._type_comments = _collect_type_comments(tree, file_tokens)
for builtin in self.builtIns:
self.addBinding(None, Builtin(builtin))
self.handleChildren(tree)
self.runDeferred(self._deferredFunctions)
# Set _deferredFunctions to None so that deferFunction will fail
# noisily if called after we've run through the deferred functions.
self._deferredFunctions = None
self.runDeferred(self._deferredAssignments)
# Set _deferredAssignments to None so that deferAssignment will fail
# noisily if called after we've run through the deferred assignments.
self._deferredAssignments = None
del self.scopeStack[1:]
self.popScope()
self.checkDeadScopes()
def deferFunction(self, callable):
"""
Schedule a function handler to be called just before completion.
This is used for handling function bodies, which must be deferred
because code later in the file might modify the global scope. When
`callable` is called, the scope at the time this is called will be
restored, however it will contain any new bindings added to it.
"""
self._deferredFunctions.append((callable, self.scopeStack[:], self.offset))
def runDeferred(self, deferred):
"""
Run the callables in C{deferred} using their associated scope stack.
"""
for handler, scope, offset in deferred:
self.scopeStack = scope
self.offset = offset
handler()
def _in_doctest(self):
return (len(self.scopeStack) >= 2 and
isinstance(self.scopeStack[1], DoctestScope))
@property
def futuresAllowed(self):
if not all(isinstance(scope, ModuleScope)
for scope in self.scopeStack):
return False
return self.scope._futures_allowed
@futuresAllowed.setter
def futuresAllowed(self, value):
assert value is False
if isinstance(self.scope, ModuleScope):
self.scope._futures_allowed = False
@property
def annotationsFutureEnabled(self):
scope = self.scopeStack[0]
if not isinstance(scope, ModuleScope):
return False
return scope._annotations_future_enabled
@annotationsFutureEnabled.setter
def annotationsFutureEnabled(self, value):
assert value is True
assert isinstance(self.scope, ModuleScope)
self.scope._annotations_future_enabled = True
@property
def scope(self):
return self.scopeStack[-1]
def popScope(self):
self.deadScopes.append(self.scopeStack.pop())
def checkDeadScopes(self):
"""
Look at scopes which have been fully examined and report names in them
which were imported but unused.
"""
for scope in self.deadScopes:
# imports in classes are public members
if isinstance(scope, ClassScope):
continue
all_binding = scope.get('__all__')
if all_binding and not isinstance(all_binding, ExportBinding):
all_binding = None
if all_binding:
all_names = set(all_binding.names)
undefined = all_names.difference(scope)
else:
all_names = undefined = []
if undefined:
if not scope.importStarred and \
os.path.basename(self.filename) != '__init__.py':
# Look for possible mistakes in the export list
for name in undefined:
self.report(messages.UndefinedExport,
scope['__all__'].source, name)
# mark all import '*' as used by the undefined in __all__
if scope.importStarred:
from_list = []
for binding in scope.values():
if isinstance(binding, StarImportation):
binding.used = all_binding
from_list.append(binding.fullName)
# report * usage, with a list of possible sources
from_list = ', '.join(sorted(from_list))
for name in undefined:
self.report(messages.ImportStarUsage,
scope['__all__'].source, name, from_list)
# Look for imported names that aren't used.
for value in scope.values():
if isinstance(value, Importation):
used = value.used or value.name in all_names
if not used:
messg = messages.UnusedImport
self.report(messg, value.source, str(value))
for node in value.redefined:
if isinstance(self.getParent(node), FOR_TYPES):
messg = messages.ImportShadowedByLoopVar
elif used:
continue
else:
messg = messages.RedefinedWhileUnused
self.report(messg, node, value.name, value.source)
def pushScope(self, scopeClass=FunctionScope):
self.scopeStack.append(scopeClass())
def report(self, messageClass, *args, **kwargs):
self.messages.append(messageClass(self.filename, *args, **kwargs))
def getParent(self, node):
# Lookup the first parent which is not Tuple, List or Starred
while True:
node = node.parent
if not hasattr(node, 'elts') and not hasattr(node, 'ctx'):
return node
def getCommonAncestor(self, lnode, rnode, stop):
if stop in (lnode, rnode) or not (hasattr(lnode, 'parent') and
hasattr(rnode, 'parent')):
return None
if lnode is rnode:
return lnode
if (lnode.depth > rnode.depth):
return self.getCommonAncestor(lnode.parent, rnode, stop)
if (lnode.depth < rnode.depth):
return self.getCommonAncestor(lnode, rnode.parent, stop)
return self.getCommonAncestor(lnode.parent, rnode.parent, stop)
def descendantOf(self, node, ancestors, stop):
for a in ancestors:
if self.getCommonAncestor(node, a, stop):
return True
return False
def _getAncestor(self, node, ancestor_type):
parent = node
while True:
if parent is self.root:
return None
parent = self.getParent(parent)
if isinstance(parent, ancestor_type):
return parent
def getScopeNode(self, node):
return self._getAncestor(node, tuple(Checker._ast_node_scope.keys()))
def differentForks(self, lnode, rnode):
"""True, if lnode and rnode are located on different forks of IF/TRY"""
ancestor = self.getCommonAncestor(lnode, rnode, self.root)
parts = getAlternatives(ancestor)
if parts:
for items in parts:
if self.descendantOf(lnode, items, ancestor) ^ \
self.descendantOf(rnode, items, ancestor):
return True
return False
def addBinding(self, node, value):
"""
Called when a binding is altered.
- `node` is the statement responsible for the change
- `value` is the new value, a Binding instance
"""
# assert value.source in (node, node.parent):
for scope in self.scopeStack[::-1]:
if value.name in scope:
break
existing = scope.get(value.name)
if (existing and not isinstance(existing, Builtin) and
not self.differentForks(node, existing.source)):
parent_stmt = self.getParent(value.source)
if isinstance(existing, Importation) and isinstance(parent_stmt, FOR_TYPES):
self.report(messages.ImportShadowedByLoopVar,
node, value.name, existing.source)
elif scope is self.scope:
if (isinstance(parent_stmt, ast.comprehension) and
not isinstance(self.getParent(existing.source),
(FOR_TYPES, ast.comprehension))):
self.report(messages.RedefinedInListComp,
node, value.name, existing.source)
elif not existing.used and value.redefines(existing):
if value.name != '_' or isinstance(existing, Importation):
if not is_typing_overload(existing, self.scopeStack):
self.report(messages.RedefinedWhileUnused,
node, value.name, existing.source)
elif isinstance(existing, Importation) and value.redefines(existing):
existing.redefined.append(node)
if value.name in self.scope:
# then assume the rebound name is used as a global or within a loop
value.used = self.scope[value.name].used
self.scope[value.name] = value
def getNodeHandler(self, node_class):
try:
return self._nodeHandlers[node_class]
except KeyError:
nodeType = getNodeType(node_class)
self._nodeHandlers[node_class] = handler = getattr(self, nodeType)
return handler
def handleNodeLoad(self, node):
name = getNodeName(node)
if not name:
return
in_generators = None
importStarred = None
# try enclosing function scopes and global scope
for scope in self.scopeStack[-1::-1]:
if isinstance(scope, ClassScope):
if not PY2 and name == '__class__':
return
elif in_generators is False:
# only generators used in a class scope can access the
# names of the class. this is skipped during the first
# iteration
continue
if (name == 'print' and
isinstance(scope.get(name, None), Builtin)):
parent = self.getParent(node)
if (isinstance(parent, ast.BinOp) and
isinstance(parent.op, ast.RShift)):
self.report(messages.InvalidPrintSyntax, node)
try:
scope[name].used = (self.scope, node)
# if the name of SubImportation is same as
# alias of other Importation and the alias
# is used, SubImportation also should be marked as used.
n = scope[name]
if isinstance(n, Importation) and n._has_alias():
try:
scope[n.fullName].used = (self.scope, node)
except KeyError:
pass
except KeyError:
pass
else:
return
importStarred = importStarred or scope.importStarred
if in_generators is not False:
in_generators = isinstance(scope, GeneratorScope)
if importStarred:
from_list = []
for scope in self.scopeStack[-1::-1]:
for binding in scope.values():
if isinstance(binding, StarImportation):
# mark '*' imports as used for each scope
binding.used = (self.scope, node)
from_list.append(binding.fullName)
# report * usage, with a list of possible sources
from_list = ', '.join(sorted(from_list))
self.report(messages.ImportStarUsage, node, name, from_list)
return
if name == '__path__' and os.path.basename(self.filename) == '__init__.py':
# the special name __path__ is valid only in packages
return
if name == '__module__' and isinstance(self.scope, ClassScope):
return
# protected with a NameError handler?
if 'NameError' not in self.exceptHandlers[-1]:
self.report(messages.UndefinedName, node, name)
def handleNodeStore(self, node):
name = getNodeName(node)
if not name:
return
# if the name hasn't already been defined in the current scope
if isinstance(self.scope, FunctionScope) and name not in self.scope:
# for each function or module scope above us
for scope in self.scopeStack[:-1]:
if not isinstance(scope, (FunctionScope, ModuleScope)):
continue
# if the name was defined in that scope, and the name has
# been accessed already in the current scope, and hasn't
# been declared global
used = name in scope and scope[name].used
if used and used[0] is self.scope and name not in self.scope.globals:
# then it's probably a mistake
self.report(messages.UndefinedLocal,
scope[name].used[1], name, scope[name].source)
break
parent_stmt = self.getParent(node)
if isinstance(parent_stmt, (FOR_TYPES, ast.comprehension)) or (
parent_stmt != node.parent and
not self.isLiteralTupleUnpacking(parent_stmt)):
binding = Binding(name, node)
elif name == '__all__' and isinstance(self.scope, ModuleScope):
binding = ExportBinding(name, node.parent, self.scope)
elif isinstance(getattr(node, 'ctx', None), ast.Param):
binding = Argument(name, self.getScopeNode(node))
else:
binding = Assignment(name, node)
self.addBinding(node, binding)
def handleNodeDelete(self, node):
def on_conditional_branch():
"""
Return `True` if node is part of a conditional body.
"""
current = getattr(node, 'parent', None)
while current:
if isinstance(current, (ast.If, ast.While, ast.IfExp)):
return True
current = getattr(current, 'parent', None)
return False
name = getNodeName(node)
if not name:
return
if on_conditional_branch():
# We cannot predict if this conditional branch is going to
# be executed.
return
if isinstance(self.scope, FunctionScope) and name in self.scope.globals:
self.scope.globals.remove(name)
else:
try:
del self.scope[name]
except KeyError:
self.report(messages.UndefinedName, node, name)
def _handle_type_comments(self, node):
for (lineno, col_offset), comment in self._type_comments.get(node, ()):
comment = comment.split(':', 1)[1].strip()
func_match = TYPE_FUNC_RE.match(comment)
if func_match:
parts = (
func_match.group(1).replace('*', ''),
func_match.group(2).strip(),
)
else:
parts = (comment,)
for part in parts:
if PY2:
part = part.replace('...', 'Ellipsis')
self.deferFunction(functools.partial(
self.handleStringAnnotation,
part, DummyNode(lineno, col_offset), lineno, col_offset,
messages.CommentAnnotationSyntaxError,
))
def handleChildren(self, tree, omit=None):
self._handle_type_comments(tree)
for node in iter_child_nodes(tree, omit=omit):
self.handleNode(node, tree)
def isLiteralTupleUnpacking(self, node):
if isinstance(node, ast.Assign):
for child in node.targets + [node.value]:
if not hasattr(child, 'elts'):
return False
return True
def isDocstring(self, node):
"""
Determine if the given node is a docstring, as long as it is at the
correct place in the node tree.
"""
return isinstance(node, ast.Str) or (isinstance(node, ast.Expr) and
isinstance(node.value, ast.Str))
def getDocstring(self, node):
if isinstance(node, ast.Expr):
node = node.value
if not isinstance(node, ast.Str):
return (None, None)
if PYPY or PY38_PLUS:
doctest_lineno = node.lineno - 1
else:
# Computed incorrectly if the docstring has backslash
doctest_lineno = node.lineno - node.s.count('\n') - 1
return (node.s, doctest_lineno)
def handleNode(self, node, parent):
if node is None:
return
if self.offset and getattr(node, 'lineno', None) is not None:
node.lineno += self.offset[0]
node.col_offset += self.offset[1]
if self.traceTree:
print(' ' * self.nodeDepth + node.__class__.__name__)
if self.futuresAllowed and not (isinstance(node, ast.ImportFrom) or
self.isDocstring(node)):
self.futuresAllowed = False
self.nodeDepth += 1
node.depth = self.nodeDepth
node.parent = parent
try:
handler = self.getNodeHandler(node.__class__)
handler(node)
finally:
self.nodeDepth -= 1
if self.traceTree:
print(' ' * self.nodeDepth + 'end ' + node.__class__.__name__)
_getDoctestExamples = doctest.DocTestParser().get_examples
def handleDoctests(self, node):
try:
if hasattr(node, 'docstring'):
docstring = node.docstring
# This is just a reasonable guess. In Python 3.7, docstrings no
# longer have line numbers associated with them. This will be
# incorrect if there are empty lines between the beginning
# of the function and the docstring.
node_lineno = node.lineno
if hasattr(node, 'args'):
node_lineno = max([node_lineno] +
[arg.lineno for arg in node.args.args])
else:
(docstring, node_lineno) = self.getDocstring(node.body[0])
examples = docstring and self._getDoctestExamples(docstring)
except (ValueError, IndexError):
# e.g. line 6 of the docstring for <string> has inconsistent
# leading whitespace: ...
return
if not examples:
return
# Place doctest in module scope
saved_stack = self.scopeStack
self.scopeStack = [self.scopeStack[0]]
node_offset = self.offset or (0, 0)
self.pushScope(DoctestScope)
self.addBinding(None, Builtin('_'))
for example in examples:
try:
tree = ast.parse(example.source, "<doctest>")
except SyntaxError:
e = sys.exc_info()[1]
if PYPY:
e.offset += 1
position = (node_lineno + example.lineno + e.lineno,
example.indent + 4 + (e.offset or 0))
self.report(messages.DoctestSyntaxError, node, position)
else:
self.offset = (node_offset[0] + node_lineno + example.lineno,
node_offset[1] + example.indent + 4)
self.handleChildren(tree)
self.offset = node_offset
self.popScope()
self.scopeStack = saved_stack
def handleStringAnnotation(self, s, node, ref_lineno, ref_col_offset, err):
try:
tree = ast.parse(s)
except SyntaxError:
self.report(err, node, s)
return
body = tree.body
if len(body) != 1 or not isinstance(body[0], ast.Expr):
self.report(err, node, s)
return
parsed_annotation = tree.body[0].value
for descendant in ast.walk(parsed_annotation):
if (
'lineno' in descendant._attributes and
'col_offset' in descendant._attributes
):
descendant.lineno = ref_lineno
descendant.col_offset = ref_col_offset
self.handleNode(parsed_annotation, node)
def handleAnnotation(self, annotation, node):
if isinstance(annotation, ast.Str):
# Defer handling forward annotation.
self.deferFunction(functools.partial(
self.handleStringAnnotation,
annotation.s,
node,
annotation.lineno,
annotation.col_offset,
messages.ForwardAnnotationSyntaxError,
))
elif self.annotationsFutureEnabled:
self.deferFunction(lambda: self.handleNode(annotation, node))
else:
self.handleNode(annotation, node)
def ignore(self, node):
pass
# "stmt" type nodes
DELETE = PRINT = FOR = ASYNCFOR = WHILE = IF = WITH = WITHITEM = \
ASYNCWITH = ASYNCWITHITEM = TRYFINALLY = EXEC = \
EXPR = ASSIGN = handleChildren
PASS = ignore
# "expr" type nodes
BOOLOP = BINOP = UNARYOP = IFEXP = SET = \
CALL = REPR = ATTRIBUTE = SUBSCRIPT = \
STARRED = NAMECONSTANT = handleChildren
NUM = STR = BYTES = ELLIPSIS = CONSTANT = ignore
# "slice" type nodes
SLICE = EXTSLICE = INDEX = handleChildren
# expression contexts are node instances too, though being constants
LOAD = STORE = DEL = AUGLOAD = AUGSTORE = PARAM = ignore
# same for operators
AND = OR = ADD = SUB = MULT = DIV = MOD = POW = LSHIFT = RSHIFT = \
BITOR = BITXOR = BITAND = FLOORDIV = INVERT = NOT = UADD = USUB = \
EQ = NOTEQ = LT = LTE = GT = GTE = IS = ISNOT = IN = NOTIN = \
MATMULT = ignore
def RAISE(self, node):
self.handleChildren(node)
arg = get_raise_argument(node)
if isinstance(arg, ast.Call):
if is_notimplemented_name_node(arg.func):
# Handle "raise NotImplemented(...)"
self.report(messages.RaiseNotImplemented, node)
elif is_notimplemented_name_node(arg):
# Handle "raise NotImplemented"
self.report(messages.RaiseNotImplemented, node)
# additional node types
COMPREHENSION = KEYWORD = FORMATTEDVALUE = JOINEDSTR = handleChildren
def DICT(self, node):
# Complain if there are duplicate keys with different values
# If they have the same value it's not going to cause potentially
# unexpected behaviour so we'll not complain.
keys = [
convert_to_value(key) for key in node.keys
]
key_counts = counter(keys)
duplicate_keys = [
key for key, count in key_counts.items()
if count > 1
]
for key in duplicate_keys:
key_indices = [i for i, i_key in enumerate(keys) if i_key == key]
values = counter(
convert_to_value(node.values[index])
for index in key_indices
)
if any(count == 1 for value, count in values.items()):
for key_index in key_indices:
key_node = node.keys[key_index]
if isinstance(key, VariableKey):
self.report(messages.MultiValueRepeatedKeyVariable,
key_node,
key.name)
else:
self.report(
messages.MultiValueRepeatedKeyLiteral,
key_node,
key,
)
self.handleChildren(node)
def ASSERT(self, node):
if isinstance(node.test, ast.Tuple) and node.test.elts != []:
self.report(messages.AssertTuple, node)
self.handleChildren(node)
def GLOBAL(self, node):
"""
Keep track of globals declarations.
"""
global_scope_index = 1 if self._in_doctest() else 0
global_scope = self.scopeStack[global_scope_index]
# Ignore 'global' statement in global scope.
if self.scope is not global_scope:
# One 'global' statement can bind multiple (comma-delimited) names.
for node_name in node.names:
node_value = Assignment(node_name, node)
# Remove UndefinedName messages already reported for this name.
# TODO: if the global is not used in this scope, it does not
# become a globally defined name. See test_unused_global.
self.messages = [
m for m in self.messages if not
isinstance(m, messages.UndefinedName) or
m.message_args[0] != node_name]
# Bind name to global scope if it doesn't exist already.
global_scope.setdefault(node_name, node_value)
# Bind name to non-global scopes, but as already "used".
node_value.used = (global_scope, node)
for scope in self.scopeStack[global_scope_index + 1:]:
scope[node_name] = node_value
NONLOCAL = GLOBAL
def GENERATOREXP(self, node):
self.pushScope(GeneratorScope)
self.handleChildren(node)
self.popScope()
LISTCOMP = handleChildren if PY2 else GENERATOREXP
DICTCOMP = SETCOMP = GENERATOREXP
def NAME(self, node):
"""
Handle occurrence of Name (which can be a load/store/delete access.)
"""
# Locate the name in locals / function / globals scopes.
if isinstance(node.ctx, (ast.Load, ast.AugLoad)):
self.handleNodeLoad(node)
if (node.id == 'locals' and isinstance(self.scope, FunctionScope) and
isinstance(node.parent, ast.Call)):
# we are doing locals() call in current scope
self.scope.usesLocals = True
elif isinstance(node.ctx, (ast.Store, ast.AugStore, ast.Param)):
self.handleNodeStore(node)
elif isinstance(node.ctx, ast.Del):
self.handleNodeDelete(node)
else:
# Unknown context
raise RuntimeError("Got impossible expression context: %r" % (node.ctx,))
def CONTINUE(self, node):
# Walk the tree up until we see a loop (OK), a function or class
# definition (not OK), for 'continue', a finally block (not OK), or
# the top module scope (not OK)
n = node
while hasattr(n, 'parent'):
n, n_child = n.parent, n
if isinstance(n, LOOP_TYPES):
# Doesn't apply unless it's in the loop itself
if n_child not in n.orelse:
return
if isinstance(n, (ast.FunctionDef, ast.ClassDef)):
break
# Handle Try/TryFinally difference in Python < and >= 3.3
if hasattr(n, 'finalbody') and isinstance(node, ast.Continue):
if n_child in n.finalbody:
self.report(messages.ContinueInFinally, node)
return
if isinstance(node, ast.Continue):
self.report(messages.ContinueOutsideLoop, node)
else: # ast.Break
self.report(messages.BreakOutsideLoop, node)
BREAK = CONTINUE
def RETURN(self, node):
if isinstance(self.scope, (ClassScope, ModuleScope)):
self.report(messages.ReturnOutsideFunction, node)
return
if (
node.value and
hasattr(self.scope, 'returnValue') and
not self.scope.returnValue
):
self.scope.returnValue = node.value
self.handleNode(node.value, node)
def YIELD(self, node):
if isinstance(self.scope, (ClassScope, ModuleScope)):
self.report(messages.YieldOutsideFunction, node)
return
self.scope.isGenerator = True
self.handleNode(node.value, node)
AWAIT = YIELDFROM = YIELD
def FUNCTIONDEF(self, node):
for deco in node.decorator_list:
self.handleNode(deco, node)
self.LAMBDA(node)
self.addBinding(node, FunctionDefinition(node.name, node))
# doctest does not process doctest within a doctest,
# or in nested functions.
if (self.withDoctest and
not self._in_doctest() and
not isinstance(self.scope, FunctionScope)):
self.deferFunction(lambda: self.handleDoctests(node))
ASYNCFUNCTIONDEF = FUNCTIONDEF
def LAMBDA(self, node):
args = []
annotations = []
if PY2:
def addArgs(arglist):
for arg in arglist:
if isinstance(arg, ast.Tuple):
addArgs(arg.elts)
else:
args.append(arg.id)
addArgs(node.args.args)
defaults = node.args.defaults
else:
for arg in node.args.args + node.args.kwonlyargs:
args.append(arg.arg)
annotations.append(arg.annotation)
defaults = node.args.defaults + node.args.kw_defaults
# Only for Python3 FunctionDefs
is_py3_func = hasattr(node, 'returns')
for arg_name in ('vararg', 'kwarg'):
wildcard = getattr(node.args, arg_name)
if not wildcard:
continue
args.append(wildcard if PY2 else wildcard.arg)
if is_py3_func:
if PY2: # Python 2.7
argannotation = arg_name + 'annotation'
annotations.append(getattr(node.args, argannotation))
else: # Python >= 3.4
annotations.append(wildcard.annotation)
if is_py3_func:
annotations.append(node.returns)
if len(set(args)) < len(args):
for (idx, arg) in enumerate(args):
if arg in args[:idx]:
self.report(messages.DuplicateArgument, node, arg)
for annotation in annotations:
self.handleAnnotation(annotation, node)
for default in defaults:
self.handleNode(default, node)
def runFunction():
self.pushScope()
self.handleChildren(node, omit='decorator_list')
def checkUnusedAssignments():
"""
Check to see if any assignments have not been used.
"""
for name, binding in self.scope.unusedAssignments():
self.report(messages.UnusedVariable, binding.source, name)
self.deferAssignment(checkUnusedAssignments)
if PY2:
def checkReturnWithArgumentInsideGenerator():
"""
Check to see if there is any return statement with
arguments but the function is a generator.
"""
if self.scope.isGenerator and self.scope.returnValue:
self.report(messages.ReturnWithArgsInsideGenerator,
self.scope.returnValue)
self.deferAssignment(checkReturnWithArgumentInsideGenerator)
self.popScope()
self.deferFunction(runFunction)
def ARGUMENTS(self, node):
self.handleChildren(node, omit=('defaults', 'kw_defaults'))
if PY2:
scope_node = self.getScopeNode(node)
if node.vararg:
self.addBinding(node, Argument(node.vararg, scope_node))
if node.kwarg:
self.addBinding(node, Argument(node.kwarg, scope_node))
def ARG(self, node):
self.addBinding(node, Argument(node.arg, self.getScopeNode(node)))
def CLASSDEF(self, node):
"""
Check names used in a class definition, including its decorators, base
classes, and the body of its definition. Additionally, add its name to
the current scope.
"""
for deco in node.decorator_list:
self.handleNode(deco, node)
for baseNode in node.bases:
self.handleNode(baseNode, node)
if not PY2:
for keywordNode in node.keywords:
self.handleNode(keywordNode, node)
self.pushScope(ClassScope)
# doctest does not process doctest within a doctest
# classes within classes are processed.
if (self.withDoctest and
not self._in_doctest() and
not isinstance(self.scope, FunctionScope)):
self.deferFunction(lambda: self.handleDoctests(node))
for stmt in node.body:
self.handleNode(stmt, node)
self.popScope()
self.addBinding(node, ClassDefinition(node.name, node))
def AUGASSIGN(self, node):
self.handleNodeLoad(node.target)
self.handleNode(node.value, node)
self.handleNode(node.target, node)
def TUPLE(self, node):
if not PY2 and isinstance(node.ctx, ast.Store):
# Python 3 advanced tuple unpacking: a, *b, c = d.
# Only one starred expression is allowed, and no more than 1<<8
# assignments are allowed before a stared expression. There is
# also a limit of 1<<24 expressions after the starred expression,
# which is impossible to test due to memory restrictions, but we
# add it here anyway
has_starred = False
star_loc = -1
for i, n in enumerate(node.elts):
if isinstance(n, ast.Starred):
if has_starred:
self.report(messages.TwoStarredExpressions, node)
# The SyntaxError doesn't distinguish two from more
# than two.
break
has_starred = True
star_loc = i
if star_loc >= 1 << 8 or len(node.elts) - star_loc - 1 >= 1 << 24:
self.report(messages.TooManyExpressionsInStarredAssignment, node)
self.handleChildren(node)
LIST = TUPLE
def IMPORT(self, node):
for alias in node.names:
if '.' in alias.name and not alias.asname:
importation = SubmoduleImportation(alias.name, node)
else:
name = alias.asname or alias.name
importation = Importation(name, node, alias.name)
self.addBinding(node, importation)
def IMPORTFROM(self, node):
if node.module == '__future__':
if not self.futuresAllowed:
self.report(messages.LateFutureImport,
node, [n.name for n in node.names])
else:
self.futuresAllowed = False
module = ('.' * node.level) + (node.module or '')
for alias in node.names:
name = alias.asname or alias.name
if node.module == '__future__':
importation = FutureImportation(name, node, self.scope)
if alias.name not in __future__.all_feature_names:
self.report(messages.FutureFeatureNotDefined,
node, alias.name)
if alias.name == 'annotations':
self.annotationsFutureEnabled = True
elif alias.name == '*':
# Only Python 2, local import * is a SyntaxWarning
if not PY2 and not isinstance(self.scope, ModuleScope):
self.report(messages.ImportStarNotPermitted,
node, module)
continue
self.scope.importStarred = True
self.report(messages.ImportStarUsed, node, module)
importation = StarImportation(module, node)
else:
importation = ImportationFrom(name, node,
module, alias.name)
self.addBinding(node, importation)
def TRY(self, node):
handler_names = []
# List the exception handlers
for i, handler in enumerate(node.handlers):
if isinstance(handler.type, ast.Tuple):
for exc_type in handler.type.elts:
handler_names.append(getNodeName(exc_type))
elif handler.type:
handler_names.append(getNodeName(handler.type))
if handler.type is None and i < len(node.handlers) - 1:
self.report(messages.DefaultExceptNotLast, handler)
# Memorize the except handlers and process the body
self.exceptHandlers.append(handler_names)
for child in node.body:
self.handleNode(child, node)
self.exceptHandlers.pop()
# Process the other nodes: "except:", "else:", "finally:"
self.handleChildren(node, omit='body')
TRYEXCEPT = TRY
def EXCEPTHANDLER(self, node):
if PY2 or node.name is None:
self.handleChildren(node)
return
# If the name already exists in the scope, modify state of existing
# binding.
if node.name in self.scope:
self.handleNodeStore(node)
# 3.x: the name of the exception, which is not a Name node, but a
# simple string, creates a local that is only bound within the scope of
# the except: block. As such, temporarily remove the existing binding
# to more accurately determine if the name is used in the except:
# block.
try:
prev_definition = self.scope.pop(node.name)
except KeyError:
prev_definition = None
self.handleNodeStore(node)
self.handleChildren(node)
# See discussion on https://github.com/PyCQA/pyflakes/pull/59
# We're removing the local name since it's being unbound after leaving
# the except: block and it's always unbound if the except: block is
# never entered. This will cause an "undefined name" error raised if
# the checked code tries to use the name afterwards.
#
# Unless it's been removed already. Then do nothing.
try:
binding = self.scope.pop(node.name)
except KeyError:
pass
else:
if not binding.used:
self.report(messages.UnusedVariable, node, node.name)
# Restore.
if prev_definition:
self.scope[node.name] = prev_definition
def ANNASSIGN(self, node):
if node.value:
# Only bind the *targets* if the assignment has a value.
# Otherwise it's not really ast.Store and shouldn't silence
# UndefinedLocal warnings.
self.handleNode(node.target, node)
self.handleAnnotation(node.annotation, node)
if node.value:
# If the assignment has value, handle the *value* now.
self.handleNode(node.value, node)
def COMPARE(self, node):
literals = (ast.Str, ast.Num)
if not PY2:
literals += (ast.Bytes,)
left = node.left
for op, right in zip(node.ops, node.comparators):
if (isinstance(op, (ast.Is, ast.IsNot)) and
(isinstance(left, literals) or isinstance(right, literals))):
self.report(messages.IsLiteral, node)
left = right
self.handleChildren(node)
|
PyCQA/pyflakes | pyflakes/checker.py | Checker.runDeferred | python | def runDeferred(self, deferred):
for handler, scope, offset in deferred:
self.scopeStack = scope
self.offset = offset
handler() | Run the callables in C{deferred} using their associated scope stack. | train | https://github.com/PyCQA/pyflakes/blob/232cb1d27ee134bf96adc8f37e53589dc259b159/pyflakes/checker.py#L712-L719 | null | class Checker(object):
"""
I check the cleanliness and sanity of Python code.
@ivar _deferredFunctions: Tracking list used by L{deferFunction}. Elements
of the list are two-tuples. The first element is the callable passed
to L{deferFunction}. The second element is a copy of the scope stack
at the time L{deferFunction} was called.
@ivar _deferredAssignments: Similar to C{_deferredFunctions}, but for
callables which are deferred assignment checks.
"""
_ast_node_scope = {
ast.Module: ModuleScope,
ast.ClassDef: ClassScope,
ast.FunctionDef: FunctionScope,
ast.Lambda: FunctionScope,
ast.ListComp: GeneratorScope,
ast.SetComp: GeneratorScope,
ast.GeneratorExp: GeneratorScope,
ast.DictComp: GeneratorScope,
}
if PY35_PLUS:
_ast_node_scope[ast.AsyncFunctionDef] = FunctionScope,
nodeDepth = 0
offset = None
traceTree = False
builtIns = set(builtin_vars).union(_MAGIC_GLOBALS)
_customBuiltIns = os.environ.get('PYFLAKES_BUILTINS')
if _customBuiltIns:
builtIns.update(_customBuiltIns.split(','))
del _customBuiltIns
# TODO: file_tokens= is required to perform checks on type comments,
# eventually make this a required positional argument. For now it
# is defaulted to `()` for api compatibility.
def __init__(self, tree, filename='(none)', builtins=None,
withDoctest='PYFLAKES_DOCTEST' in os.environ, file_tokens=()):
self._nodeHandlers = {}
self._deferredFunctions = []
self._deferredAssignments = []
self.deadScopes = []
self.messages = []
self.filename = filename
if builtins:
self.builtIns = self.builtIns.union(builtins)
self.withDoctest = withDoctest
try:
self.scopeStack = [Checker._ast_node_scope[type(tree)]()]
except KeyError:
raise RuntimeError('No scope implemented for the node %r' % tree)
self.exceptHandlers = [()]
self.root = tree
self._type_comments = _collect_type_comments(tree, file_tokens)
for builtin in self.builtIns:
self.addBinding(None, Builtin(builtin))
self.handleChildren(tree)
self.runDeferred(self._deferredFunctions)
# Set _deferredFunctions to None so that deferFunction will fail
# noisily if called after we've run through the deferred functions.
self._deferredFunctions = None
self.runDeferred(self._deferredAssignments)
# Set _deferredAssignments to None so that deferAssignment will fail
# noisily if called after we've run through the deferred assignments.
self._deferredAssignments = None
del self.scopeStack[1:]
self.popScope()
self.checkDeadScopes()
def deferFunction(self, callable):
"""
Schedule a function handler to be called just before completion.
This is used for handling function bodies, which must be deferred
because code later in the file might modify the global scope. When
`callable` is called, the scope at the time this is called will be
restored, however it will contain any new bindings added to it.
"""
self._deferredFunctions.append((callable, self.scopeStack[:], self.offset))
def deferAssignment(self, callable):
"""
Schedule an assignment handler to be called just after deferred
function handlers.
"""
self._deferredAssignments.append((callable, self.scopeStack[:], self.offset))
def _in_doctest(self):
return (len(self.scopeStack) >= 2 and
isinstance(self.scopeStack[1], DoctestScope))
@property
def futuresAllowed(self):
if not all(isinstance(scope, ModuleScope)
for scope in self.scopeStack):
return False
return self.scope._futures_allowed
@futuresAllowed.setter
def futuresAllowed(self, value):
assert value is False
if isinstance(self.scope, ModuleScope):
self.scope._futures_allowed = False
@property
def annotationsFutureEnabled(self):
scope = self.scopeStack[0]
if not isinstance(scope, ModuleScope):
return False
return scope._annotations_future_enabled
@annotationsFutureEnabled.setter
def annotationsFutureEnabled(self, value):
assert value is True
assert isinstance(self.scope, ModuleScope)
self.scope._annotations_future_enabled = True
@property
def scope(self):
return self.scopeStack[-1]
def popScope(self):
self.deadScopes.append(self.scopeStack.pop())
def checkDeadScopes(self):
"""
Look at scopes which have been fully examined and report names in them
which were imported but unused.
"""
for scope in self.deadScopes:
# imports in classes are public members
if isinstance(scope, ClassScope):
continue
all_binding = scope.get('__all__')
if all_binding and not isinstance(all_binding, ExportBinding):
all_binding = None
if all_binding:
all_names = set(all_binding.names)
undefined = all_names.difference(scope)
else:
all_names = undefined = []
if undefined:
if not scope.importStarred and \
os.path.basename(self.filename) != '__init__.py':
# Look for possible mistakes in the export list
for name in undefined:
self.report(messages.UndefinedExport,
scope['__all__'].source, name)
# mark all import '*' as used by the undefined in __all__
if scope.importStarred:
from_list = []
for binding in scope.values():
if isinstance(binding, StarImportation):
binding.used = all_binding
from_list.append(binding.fullName)
# report * usage, with a list of possible sources
from_list = ', '.join(sorted(from_list))
for name in undefined:
self.report(messages.ImportStarUsage,
scope['__all__'].source, name, from_list)
# Look for imported names that aren't used.
for value in scope.values():
if isinstance(value, Importation):
used = value.used or value.name in all_names
if not used:
messg = messages.UnusedImport
self.report(messg, value.source, str(value))
for node in value.redefined:
if isinstance(self.getParent(node), FOR_TYPES):
messg = messages.ImportShadowedByLoopVar
elif used:
continue
else:
messg = messages.RedefinedWhileUnused
self.report(messg, node, value.name, value.source)
def pushScope(self, scopeClass=FunctionScope):
self.scopeStack.append(scopeClass())
def report(self, messageClass, *args, **kwargs):
self.messages.append(messageClass(self.filename, *args, **kwargs))
def getParent(self, node):
# Lookup the first parent which is not Tuple, List or Starred
while True:
node = node.parent
if not hasattr(node, 'elts') and not hasattr(node, 'ctx'):
return node
def getCommonAncestor(self, lnode, rnode, stop):
if stop in (lnode, rnode) or not (hasattr(lnode, 'parent') and
hasattr(rnode, 'parent')):
return None
if lnode is rnode:
return lnode
if (lnode.depth > rnode.depth):
return self.getCommonAncestor(lnode.parent, rnode, stop)
if (lnode.depth < rnode.depth):
return self.getCommonAncestor(lnode, rnode.parent, stop)
return self.getCommonAncestor(lnode.parent, rnode.parent, stop)
def descendantOf(self, node, ancestors, stop):
for a in ancestors:
if self.getCommonAncestor(node, a, stop):
return True
return False
def _getAncestor(self, node, ancestor_type):
parent = node
while True:
if parent is self.root:
return None
parent = self.getParent(parent)
if isinstance(parent, ancestor_type):
return parent
def getScopeNode(self, node):
return self._getAncestor(node, tuple(Checker._ast_node_scope.keys()))
def differentForks(self, lnode, rnode):
"""True, if lnode and rnode are located on different forks of IF/TRY"""
ancestor = self.getCommonAncestor(lnode, rnode, self.root)
parts = getAlternatives(ancestor)
if parts:
for items in parts:
if self.descendantOf(lnode, items, ancestor) ^ \
self.descendantOf(rnode, items, ancestor):
return True
return False
def addBinding(self, node, value):
"""
Called when a binding is altered.
- `node` is the statement responsible for the change
- `value` is the new value, a Binding instance
"""
# assert value.source in (node, node.parent):
for scope in self.scopeStack[::-1]:
if value.name in scope:
break
existing = scope.get(value.name)
if (existing and not isinstance(existing, Builtin) and
not self.differentForks(node, existing.source)):
parent_stmt = self.getParent(value.source)
if isinstance(existing, Importation) and isinstance(parent_stmt, FOR_TYPES):
self.report(messages.ImportShadowedByLoopVar,
node, value.name, existing.source)
elif scope is self.scope:
if (isinstance(parent_stmt, ast.comprehension) and
not isinstance(self.getParent(existing.source),
(FOR_TYPES, ast.comprehension))):
self.report(messages.RedefinedInListComp,
node, value.name, existing.source)
elif not existing.used and value.redefines(existing):
if value.name != '_' or isinstance(existing, Importation):
if not is_typing_overload(existing, self.scopeStack):
self.report(messages.RedefinedWhileUnused,
node, value.name, existing.source)
elif isinstance(existing, Importation) and value.redefines(existing):
existing.redefined.append(node)
if value.name in self.scope:
# then assume the rebound name is used as a global or within a loop
value.used = self.scope[value.name].used
self.scope[value.name] = value
def getNodeHandler(self, node_class):
try:
return self._nodeHandlers[node_class]
except KeyError:
nodeType = getNodeType(node_class)
self._nodeHandlers[node_class] = handler = getattr(self, nodeType)
return handler
def handleNodeLoad(self, node):
name = getNodeName(node)
if not name:
return
in_generators = None
importStarred = None
# try enclosing function scopes and global scope
for scope in self.scopeStack[-1::-1]:
if isinstance(scope, ClassScope):
if not PY2 and name == '__class__':
return
elif in_generators is False:
# only generators used in a class scope can access the
# names of the class. this is skipped during the first
# iteration
continue
if (name == 'print' and
isinstance(scope.get(name, None), Builtin)):
parent = self.getParent(node)
if (isinstance(parent, ast.BinOp) and
isinstance(parent.op, ast.RShift)):
self.report(messages.InvalidPrintSyntax, node)
try:
scope[name].used = (self.scope, node)
# if the name of SubImportation is same as
# alias of other Importation and the alias
# is used, SubImportation also should be marked as used.
n = scope[name]
if isinstance(n, Importation) and n._has_alias():
try:
scope[n.fullName].used = (self.scope, node)
except KeyError:
pass
except KeyError:
pass
else:
return
importStarred = importStarred or scope.importStarred
if in_generators is not False:
in_generators = isinstance(scope, GeneratorScope)
if importStarred:
from_list = []
for scope in self.scopeStack[-1::-1]:
for binding in scope.values():
if isinstance(binding, StarImportation):
# mark '*' imports as used for each scope
binding.used = (self.scope, node)
from_list.append(binding.fullName)
# report * usage, with a list of possible sources
from_list = ', '.join(sorted(from_list))
self.report(messages.ImportStarUsage, node, name, from_list)
return
if name == '__path__' and os.path.basename(self.filename) == '__init__.py':
# the special name __path__ is valid only in packages
return
if name == '__module__' and isinstance(self.scope, ClassScope):
return
# protected with a NameError handler?
if 'NameError' not in self.exceptHandlers[-1]:
self.report(messages.UndefinedName, node, name)
def handleNodeStore(self, node):
name = getNodeName(node)
if not name:
return
# if the name hasn't already been defined in the current scope
if isinstance(self.scope, FunctionScope) and name not in self.scope:
# for each function or module scope above us
for scope in self.scopeStack[:-1]:
if not isinstance(scope, (FunctionScope, ModuleScope)):
continue
# if the name was defined in that scope, and the name has
# been accessed already in the current scope, and hasn't
# been declared global
used = name in scope and scope[name].used
if used and used[0] is self.scope and name not in self.scope.globals:
# then it's probably a mistake
self.report(messages.UndefinedLocal,
scope[name].used[1], name, scope[name].source)
break
parent_stmt = self.getParent(node)
if isinstance(parent_stmt, (FOR_TYPES, ast.comprehension)) or (
parent_stmt != node.parent and
not self.isLiteralTupleUnpacking(parent_stmt)):
binding = Binding(name, node)
elif name == '__all__' and isinstance(self.scope, ModuleScope):
binding = ExportBinding(name, node.parent, self.scope)
elif isinstance(getattr(node, 'ctx', None), ast.Param):
binding = Argument(name, self.getScopeNode(node))
else:
binding = Assignment(name, node)
self.addBinding(node, binding)
def handleNodeDelete(self, node):
def on_conditional_branch():
"""
Return `True` if node is part of a conditional body.
"""
current = getattr(node, 'parent', None)
while current:
if isinstance(current, (ast.If, ast.While, ast.IfExp)):
return True
current = getattr(current, 'parent', None)
return False
name = getNodeName(node)
if not name:
return
if on_conditional_branch():
# We cannot predict if this conditional branch is going to
# be executed.
return
if isinstance(self.scope, FunctionScope) and name in self.scope.globals:
self.scope.globals.remove(name)
else:
try:
del self.scope[name]
except KeyError:
self.report(messages.UndefinedName, node, name)
def _handle_type_comments(self, node):
for (lineno, col_offset), comment in self._type_comments.get(node, ()):
comment = comment.split(':', 1)[1].strip()
func_match = TYPE_FUNC_RE.match(comment)
if func_match:
parts = (
func_match.group(1).replace('*', ''),
func_match.group(2).strip(),
)
else:
parts = (comment,)
for part in parts:
if PY2:
part = part.replace('...', 'Ellipsis')
self.deferFunction(functools.partial(
self.handleStringAnnotation,
part, DummyNode(lineno, col_offset), lineno, col_offset,
messages.CommentAnnotationSyntaxError,
))
def handleChildren(self, tree, omit=None):
self._handle_type_comments(tree)
for node in iter_child_nodes(tree, omit=omit):
self.handleNode(node, tree)
def isLiteralTupleUnpacking(self, node):
if isinstance(node, ast.Assign):
for child in node.targets + [node.value]:
if not hasattr(child, 'elts'):
return False
return True
def isDocstring(self, node):
"""
Determine if the given node is a docstring, as long as it is at the
correct place in the node tree.
"""
return isinstance(node, ast.Str) or (isinstance(node, ast.Expr) and
isinstance(node.value, ast.Str))
def getDocstring(self, node):
if isinstance(node, ast.Expr):
node = node.value
if not isinstance(node, ast.Str):
return (None, None)
if PYPY or PY38_PLUS:
doctest_lineno = node.lineno - 1
else:
# Computed incorrectly if the docstring has backslash
doctest_lineno = node.lineno - node.s.count('\n') - 1
return (node.s, doctest_lineno)
def handleNode(self, node, parent):
if node is None:
return
if self.offset and getattr(node, 'lineno', None) is not None:
node.lineno += self.offset[0]
node.col_offset += self.offset[1]
if self.traceTree:
print(' ' * self.nodeDepth + node.__class__.__name__)
if self.futuresAllowed and not (isinstance(node, ast.ImportFrom) or
self.isDocstring(node)):
self.futuresAllowed = False
self.nodeDepth += 1
node.depth = self.nodeDepth
node.parent = parent
try:
handler = self.getNodeHandler(node.__class__)
handler(node)
finally:
self.nodeDepth -= 1
if self.traceTree:
print(' ' * self.nodeDepth + 'end ' + node.__class__.__name__)
_getDoctestExamples = doctest.DocTestParser().get_examples
def handleDoctests(self, node):
try:
if hasattr(node, 'docstring'):
docstring = node.docstring
# This is just a reasonable guess. In Python 3.7, docstrings no
# longer have line numbers associated with them. This will be
# incorrect if there are empty lines between the beginning
# of the function and the docstring.
node_lineno = node.lineno
if hasattr(node, 'args'):
node_lineno = max([node_lineno] +
[arg.lineno for arg in node.args.args])
else:
(docstring, node_lineno) = self.getDocstring(node.body[0])
examples = docstring and self._getDoctestExamples(docstring)
except (ValueError, IndexError):
# e.g. line 6 of the docstring for <string> has inconsistent
# leading whitespace: ...
return
if not examples:
return
# Place doctest in module scope
saved_stack = self.scopeStack
self.scopeStack = [self.scopeStack[0]]
node_offset = self.offset or (0, 0)
self.pushScope(DoctestScope)
self.addBinding(None, Builtin('_'))
for example in examples:
try:
tree = ast.parse(example.source, "<doctest>")
except SyntaxError:
e = sys.exc_info()[1]
if PYPY:
e.offset += 1
position = (node_lineno + example.lineno + e.lineno,
example.indent + 4 + (e.offset or 0))
self.report(messages.DoctestSyntaxError, node, position)
else:
self.offset = (node_offset[0] + node_lineno + example.lineno,
node_offset[1] + example.indent + 4)
self.handleChildren(tree)
self.offset = node_offset
self.popScope()
self.scopeStack = saved_stack
def handleStringAnnotation(self, s, node, ref_lineno, ref_col_offset, err):
try:
tree = ast.parse(s)
except SyntaxError:
self.report(err, node, s)
return
body = tree.body
if len(body) != 1 or not isinstance(body[0], ast.Expr):
self.report(err, node, s)
return
parsed_annotation = tree.body[0].value
for descendant in ast.walk(parsed_annotation):
if (
'lineno' in descendant._attributes and
'col_offset' in descendant._attributes
):
descendant.lineno = ref_lineno
descendant.col_offset = ref_col_offset
self.handleNode(parsed_annotation, node)
def handleAnnotation(self, annotation, node):
if isinstance(annotation, ast.Str):
# Defer handling forward annotation.
self.deferFunction(functools.partial(
self.handleStringAnnotation,
annotation.s,
node,
annotation.lineno,
annotation.col_offset,
messages.ForwardAnnotationSyntaxError,
))
elif self.annotationsFutureEnabled:
self.deferFunction(lambda: self.handleNode(annotation, node))
else:
self.handleNode(annotation, node)
def ignore(self, node):
pass
# "stmt" type nodes
DELETE = PRINT = FOR = ASYNCFOR = WHILE = IF = WITH = WITHITEM = \
ASYNCWITH = ASYNCWITHITEM = TRYFINALLY = EXEC = \
EXPR = ASSIGN = handleChildren
PASS = ignore
# "expr" type nodes
BOOLOP = BINOP = UNARYOP = IFEXP = SET = \
CALL = REPR = ATTRIBUTE = SUBSCRIPT = \
STARRED = NAMECONSTANT = handleChildren
NUM = STR = BYTES = ELLIPSIS = CONSTANT = ignore
# "slice" type nodes
SLICE = EXTSLICE = INDEX = handleChildren
# expression contexts are node instances too, though being constants
LOAD = STORE = DEL = AUGLOAD = AUGSTORE = PARAM = ignore
# same for operators
AND = OR = ADD = SUB = MULT = DIV = MOD = POW = LSHIFT = RSHIFT = \
BITOR = BITXOR = BITAND = FLOORDIV = INVERT = NOT = UADD = USUB = \
EQ = NOTEQ = LT = LTE = GT = GTE = IS = ISNOT = IN = NOTIN = \
MATMULT = ignore
def RAISE(self, node):
self.handleChildren(node)
arg = get_raise_argument(node)
if isinstance(arg, ast.Call):
if is_notimplemented_name_node(arg.func):
# Handle "raise NotImplemented(...)"
self.report(messages.RaiseNotImplemented, node)
elif is_notimplemented_name_node(arg):
# Handle "raise NotImplemented"
self.report(messages.RaiseNotImplemented, node)
# additional node types
COMPREHENSION = KEYWORD = FORMATTEDVALUE = JOINEDSTR = handleChildren
def DICT(self, node):
# Complain if there are duplicate keys with different values
# If they have the same value it's not going to cause potentially
# unexpected behaviour so we'll not complain.
keys = [
convert_to_value(key) for key in node.keys
]
key_counts = counter(keys)
duplicate_keys = [
key for key, count in key_counts.items()
if count > 1
]
for key in duplicate_keys:
key_indices = [i for i, i_key in enumerate(keys) if i_key == key]
values = counter(
convert_to_value(node.values[index])
for index in key_indices
)
if any(count == 1 for value, count in values.items()):
for key_index in key_indices:
key_node = node.keys[key_index]
if isinstance(key, VariableKey):
self.report(messages.MultiValueRepeatedKeyVariable,
key_node,
key.name)
else:
self.report(
messages.MultiValueRepeatedKeyLiteral,
key_node,
key,
)
self.handleChildren(node)
def ASSERT(self, node):
if isinstance(node.test, ast.Tuple) and node.test.elts != []:
self.report(messages.AssertTuple, node)
self.handleChildren(node)
def GLOBAL(self, node):
"""
Keep track of globals declarations.
"""
global_scope_index = 1 if self._in_doctest() else 0
global_scope = self.scopeStack[global_scope_index]
# Ignore 'global' statement in global scope.
if self.scope is not global_scope:
# One 'global' statement can bind multiple (comma-delimited) names.
for node_name in node.names:
node_value = Assignment(node_name, node)
# Remove UndefinedName messages already reported for this name.
# TODO: if the global is not used in this scope, it does not
# become a globally defined name. See test_unused_global.
self.messages = [
m for m in self.messages if not
isinstance(m, messages.UndefinedName) or
m.message_args[0] != node_name]
# Bind name to global scope if it doesn't exist already.
global_scope.setdefault(node_name, node_value)
# Bind name to non-global scopes, but as already "used".
node_value.used = (global_scope, node)
for scope in self.scopeStack[global_scope_index + 1:]:
scope[node_name] = node_value
NONLOCAL = GLOBAL
def GENERATOREXP(self, node):
self.pushScope(GeneratorScope)
self.handleChildren(node)
self.popScope()
LISTCOMP = handleChildren if PY2 else GENERATOREXP
DICTCOMP = SETCOMP = GENERATOREXP
def NAME(self, node):
"""
Handle occurrence of Name (which can be a load/store/delete access.)
"""
# Locate the name in locals / function / globals scopes.
if isinstance(node.ctx, (ast.Load, ast.AugLoad)):
self.handleNodeLoad(node)
if (node.id == 'locals' and isinstance(self.scope, FunctionScope) and
isinstance(node.parent, ast.Call)):
# we are doing locals() call in current scope
self.scope.usesLocals = True
elif isinstance(node.ctx, (ast.Store, ast.AugStore, ast.Param)):
self.handleNodeStore(node)
elif isinstance(node.ctx, ast.Del):
self.handleNodeDelete(node)
else:
# Unknown context
raise RuntimeError("Got impossible expression context: %r" % (node.ctx,))
def CONTINUE(self, node):
# Walk the tree up until we see a loop (OK), a function or class
# definition (not OK), for 'continue', a finally block (not OK), or
# the top module scope (not OK)
n = node
while hasattr(n, 'parent'):
n, n_child = n.parent, n
if isinstance(n, LOOP_TYPES):
# Doesn't apply unless it's in the loop itself
if n_child not in n.orelse:
return
if isinstance(n, (ast.FunctionDef, ast.ClassDef)):
break
# Handle Try/TryFinally difference in Python < and >= 3.3
if hasattr(n, 'finalbody') and isinstance(node, ast.Continue):
if n_child in n.finalbody:
self.report(messages.ContinueInFinally, node)
return
if isinstance(node, ast.Continue):
self.report(messages.ContinueOutsideLoop, node)
else: # ast.Break
self.report(messages.BreakOutsideLoop, node)
BREAK = CONTINUE
def RETURN(self, node):
if isinstance(self.scope, (ClassScope, ModuleScope)):
self.report(messages.ReturnOutsideFunction, node)
return
if (
node.value and
hasattr(self.scope, 'returnValue') and
not self.scope.returnValue
):
self.scope.returnValue = node.value
self.handleNode(node.value, node)
def YIELD(self, node):
if isinstance(self.scope, (ClassScope, ModuleScope)):
self.report(messages.YieldOutsideFunction, node)
return
self.scope.isGenerator = True
self.handleNode(node.value, node)
AWAIT = YIELDFROM = YIELD
def FUNCTIONDEF(self, node):
for deco in node.decorator_list:
self.handleNode(deco, node)
self.LAMBDA(node)
self.addBinding(node, FunctionDefinition(node.name, node))
# doctest does not process doctest within a doctest,
# or in nested functions.
if (self.withDoctest and
not self._in_doctest() and
not isinstance(self.scope, FunctionScope)):
self.deferFunction(lambda: self.handleDoctests(node))
ASYNCFUNCTIONDEF = FUNCTIONDEF
def LAMBDA(self, node):
args = []
annotations = []
if PY2:
def addArgs(arglist):
for arg in arglist:
if isinstance(arg, ast.Tuple):
addArgs(arg.elts)
else:
args.append(arg.id)
addArgs(node.args.args)
defaults = node.args.defaults
else:
for arg in node.args.args + node.args.kwonlyargs:
args.append(arg.arg)
annotations.append(arg.annotation)
defaults = node.args.defaults + node.args.kw_defaults
# Only for Python3 FunctionDefs
is_py3_func = hasattr(node, 'returns')
for arg_name in ('vararg', 'kwarg'):
wildcard = getattr(node.args, arg_name)
if not wildcard:
continue
args.append(wildcard if PY2 else wildcard.arg)
if is_py3_func:
if PY2: # Python 2.7
argannotation = arg_name + 'annotation'
annotations.append(getattr(node.args, argannotation))
else: # Python >= 3.4
annotations.append(wildcard.annotation)
if is_py3_func:
annotations.append(node.returns)
if len(set(args)) < len(args):
for (idx, arg) in enumerate(args):
if arg in args[:idx]:
self.report(messages.DuplicateArgument, node, arg)
for annotation in annotations:
self.handleAnnotation(annotation, node)
for default in defaults:
self.handleNode(default, node)
def runFunction():
self.pushScope()
self.handleChildren(node, omit='decorator_list')
def checkUnusedAssignments():
"""
Check to see if any assignments have not been used.
"""
for name, binding in self.scope.unusedAssignments():
self.report(messages.UnusedVariable, binding.source, name)
self.deferAssignment(checkUnusedAssignments)
if PY2:
def checkReturnWithArgumentInsideGenerator():
"""
Check to see if there is any return statement with
arguments but the function is a generator.
"""
if self.scope.isGenerator and self.scope.returnValue:
self.report(messages.ReturnWithArgsInsideGenerator,
self.scope.returnValue)
self.deferAssignment(checkReturnWithArgumentInsideGenerator)
self.popScope()
self.deferFunction(runFunction)
def ARGUMENTS(self, node):
self.handleChildren(node, omit=('defaults', 'kw_defaults'))
if PY2:
scope_node = self.getScopeNode(node)
if node.vararg:
self.addBinding(node, Argument(node.vararg, scope_node))
if node.kwarg:
self.addBinding(node, Argument(node.kwarg, scope_node))
def ARG(self, node):
self.addBinding(node, Argument(node.arg, self.getScopeNode(node)))
def CLASSDEF(self, node):
"""
Check names used in a class definition, including its decorators, base
classes, and the body of its definition. Additionally, add its name to
the current scope.
"""
for deco in node.decorator_list:
self.handleNode(deco, node)
for baseNode in node.bases:
self.handleNode(baseNode, node)
if not PY2:
for keywordNode in node.keywords:
self.handleNode(keywordNode, node)
self.pushScope(ClassScope)
# doctest does not process doctest within a doctest
# classes within classes are processed.
if (self.withDoctest and
not self._in_doctest() and
not isinstance(self.scope, FunctionScope)):
self.deferFunction(lambda: self.handleDoctests(node))
for stmt in node.body:
self.handleNode(stmt, node)
self.popScope()
self.addBinding(node, ClassDefinition(node.name, node))
def AUGASSIGN(self, node):
self.handleNodeLoad(node.target)
self.handleNode(node.value, node)
self.handleNode(node.target, node)
def TUPLE(self, node):
if not PY2 and isinstance(node.ctx, ast.Store):
# Python 3 advanced tuple unpacking: a, *b, c = d.
# Only one starred expression is allowed, and no more than 1<<8
# assignments are allowed before a stared expression. There is
# also a limit of 1<<24 expressions after the starred expression,
# which is impossible to test due to memory restrictions, but we
# add it here anyway
has_starred = False
star_loc = -1
for i, n in enumerate(node.elts):
if isinstance(n, ast.Starred):
if has_starred:
self.report(messages.TwoStarredExpressions, node)
# The SyntaxError doesn't distinguish two from more
# than two.
break
has_starred = True
star_loc = i
if star_loc >= 1 << 8 or len(node.elts) - star_loc - 1 >= 1 << 24:
self.report(messages.TooManyExpressionsInStarredAssignment, node)
self.handleChildren(node)
LIST = TUPLE
def IMPORT(self, node):
for alias in node.names:
if '.' in alias.name and not alias.asname:
importation = SubmoduleImportation(alias.name, node)
else:
name = alias.asname or alias.name
importation = Importation(name, node, alias.name)
self.addBinding(node, importation)
def IMPORTFROM(self, node):
if node.module == '__future__':
if not self.futuresAllowed:
self.report(messages.LateFutureImport,
node, [n.name for n in node.names])
else:
self.futuresAllowed = False
module = ('.' * node.level) + (node.module or '')
for alias in node.names:
name = alias.asname or alias.name
if node.module == '__future__':
importation = FutureImportation(name, node, self.scope)
if alias.name not in __future__.all_feature_names:
self.report(messages.FutureFeatureNotDefined,
node, alias.name)
if alias.name == 'annotations':
self.annotationsFutureEnabled = True
elif alias.name == '*':
# Only Python 2, local import * is a SyntaxWarning
if not PY2 and not isinstance(self.scope, ModuleScope):
self.report(messages.ImportStarNotPermitted,
node, module)
continue
self.scope.importStarred = True
self.report(messages.ImportStarUsed, node, module)
importation = StarImportation(module, node)
else:
importation = ImportationFrom(name, node,
module, alias.name)
self.addBinding(node, importation)
def TRY(self, node):
handler_names = []
# List the exception handlers
for i, handler in enumerate(node.handlers):
if isinstance(handler.type, ast.Tuple):
for exc_type in handler.type.elts:
handler_names.append(getNodeName(exc_type))
elif handler.type:
handler_names.append(getNodeName(handler.type))
if handler.type is None and i < len(node.handlers) - 1:
self.report(messages.DefaultExceptNotLast, handler)
# Memorize the except handlers and process the body
self.exceptHandlers.append(handler_names)
for child in node.body:
self.handleNode(child, node)
self.exceptHandlers.pop()
# Process the other nodes: "except:", "else:", "finally:"
self.handleChildren(node, omit='body')
TRYEXCEPT = TRY
def EXCEPTHANDLER(self, node):
if PY2 or node.name is None:
self.handleChildren(node)
return
# If the name already exists in the scope, modify state of existing
# binding.
if node.name in self.scope:
self.handleNodeStore(node)
# 3.x: the name of the exception, which is not a Name node, but a
# simple string, creates a local that is only bound within the scope of
# the except: block. As such, temporarily remove the existing binding
# to more accurately determine if the name is used in the except:
# block.
try:
prev_definition = self.scope.pop(node.name)
except KeyError:
prev_definition = None
self.handleNodeStore(node)
self.handleChildren(node)
# See discussion on https://github.com/PyCQA/pyflakes/pull/59
# We're removing the local name since it's being unbound after leaving
# the except: block and it's always unbound if the except: block is
# never entered. This will cause an "undefined name" error raised if
# the checked code tries to use the name afterwards.
#
# Unless it's been removed already. Then do nothing.
try:
binding = self.scope.pop(node.name)
except KeyError:
pass
else:
if not binding.used:
self.report(messages.UnusedVariable, node, node.name)
# Restore.
if prev_definition:
self.scope[node.name] = prev_definition
def ANNASSIGN(self, node):
if node.value:
# Only bind the *targets* if the assignment has a value.
# Otherwise it's not really ast.Store and shouldn't silence
# UndefinedLocal warnings.
self.handleNode(node.target, node)
self.handleAnnotation(node.annotation, node)
if node.value:
# If the assignment has value, handle the *value* now.
self.handleNode(node.value, node)
def COMPARE(self, node):
literals = (ast.Str, ast.Num)
if not PY2:
literals += (ast.Bytes,)
left = node.left
for op, right in zip(node.ops, node.comparators):
if (isinstance(op, (ast.Is, ast.IsNot)) and
(isinstance(left, literals) or isinstance(right, literals))):
self.report(messages.IsLiteral, node)
left = right
self.handleChildren(node)
|
PyCQA/pyflakes | pyflakes/checker.py | Checker.checkDeadScopes | python | def checkDeadScopes(self):
for scope in self.deadScopes:
# imports in classes are public members
if isinstance(scope, ClassScope):
continue
all_binding = scope.get('__all__')
if all_binding and not isinstance(all_binding, ExportBinding):
all_binding = None
if all_binding:
all_names = set(all_binding.names)
undefined = all_names.difference(scope)
else:
all_names = undefined = []
if undefined:
if not scope.importStarred and \
os.path.basename(self.filename) != '__init__.py':
# Look for possible mistakes in the export list
for name in undefined:
self.report(messages.UndefinedExport,
scope['__all__'].source, name)
# mark all import '*' as used by the undefined in __all__
if scope.importStarred:
from_list = []
for binding in scope.values():
if isinstance(binding, StarImportation):
binding.used = all_binding
from_list.append(binding.fullName)
# report * usage, with a list of possible sources
from_list = ', '.join(sorted(from_list))
for name in undefined:
self.report(messages.ImportStarUsage,
scope['__all__'].source, name, from_list)
# Look for imported names that aren't used.
for value in scope.values():
if isinstance(value, Importation):
used = value.used or value.name in all_names
if not used:
messg = messages.UnusedImport
self.report(messg, value.source, str(value))
for node in value.redefined:
if isinstance(self.getParent(node), FOR_TYPES):
messg = messages.ImportShadowedByLoopVar
elif used:
continue
else:
messg = messages.RedefinedWhileUnused
self.report(messg, node, value.name, value.source) | Look at scopes which have been fully examined and report names in them
which were imported but unused. | train | https://github.com/PyCQA/pyflakes/blob/232cb1d27ee134bf96adc8f37e53589dc259b159/pyflakes/checker.py#L759-L814 | [
"def report(self, messageClass, *args, **kwargs):\n self.messages.append(messageClass(self.filename, *args, **kwargs))\n"
] | class Checker(object):
"""
I check the cleanliness and sanity of Python code.
@ivar _deferredFunctions: Tracking list used by L{deferFunction}. Elements
of the list are two-tuples. The first element is the callable passed
to L{deferFunction}. The second element is a copy of the scope stack
at the time L{deferFunction} was called.
@ivar _deferredAssignments: Similar to C{_deferredFunctions}, but for
callables which are deferred assignment checks.
"""
_ast_node_scope = {
ast.Module: ModuleScope,
ast.ClassDef: ClassScope,
ast.FunctionDef: FunctionScope,
ast.Lambda: FunctionScope,
ast.ListComp: GeneratorScope,
ast.SetComp: GeneratorScope,
ast.GeneratorExp: GeneratorScope,
ast.DictComp: GeneratorScope,
}
if PY35_PLUS:
_ast_node_scope[ast.AsyncFunctionDef] = FunctionScope,
nodeDepth = 0
offset = None
traceTree = False
builtIns = set(builtin_vars).union(_MAGIC_GLOBALS)
_customBuiltIns = os.environ.get('PYFLAKES_BUILTINS')
if _customBuiltIns:
builtIns.update(_customBuiltIns.split(','))
del _customBuiltIns
# TODO: file_tokens= is required to perform checks on type comments,
# eventually make this a required positional argument. For now it
# is defaulted to `()` for api compatibility.
def __init__(self, tree, filename='(none)', builtins=None,
withDoctest='PYFLAKES_DOCTEST' in os.environ, file_tokens=()):
self._nodeHandlers = {}
self._deferredFunctions = []
self._deferredAssignments = []
self.deadScopes = []
self.messages = []
self.filename = filename
if builtins:
self.builtIns = self.builtIns.union(builtins)
self.withDoctest = withDoctest
try:
self.scopeStack = [Checker._ast_node_scope[type(tree)]()]
except KeyError:
raise RuntimeError('No scope implemented for the node %r' % tree)
self.exceptHandlers = [()]
self.root = tree
self._type_comments = _collect_type_comments(tree, file_tokens)
for builtin in self.builtIns:
self.addBinding(None, Builtin(builtin))
self.handleChildren(tree)
self.runDeferred(self._deferredFunctions)
# Set _deferredFunctions to None so that deferFunction will fail
# noisily if called after we've run through the deferred functions.
self._deferredFunctions = None
self.runDeferred(self._deferredAssignments)
# Set _deferredAssignments to None so that deferAssignment will fail
# noisily if called after we've run through the deferred assignments.
self._deferredAssignments = None
del self.scopeStack[1:]
self.popScope()
self.checkDeadScopes()
def deferFunction(self, callable):
"""
Schedule a function handler to be called just before completion.
This is used for handling function bodies, which must be deferred
because code later in the file might modify the global scope. When
`callable` is called, the scope at the time this is called will be
restored, however it will contain any new bindings added to it.
"""
self._deferredFunctions.append((callable, self.scopeStack[:], self.offset))
def deferAssignment(self, callable):
"""
Schedule an assignment handler to be called just after deferred
function handlers.
"""
self._deferredAssignments.append((callable, self.scopeStack[:], self.offset))
def runDeferred(self, deferred):
"""
Run the callables in C{deferred} using their associated scope stack.
"""
for handler, scope, offset in deferred:
self.scopeStack = scope
self.offset = offset
handler()
def _in_doctest(self):
return (len(self.scopeStack) >= 2 and
isinstance(self.scopeStack[1], DoctestScope))
@property
def futuresAllowed(self):
if not all(isinstance(scope, ModuleScope)
for scope in self.scopeStack):
return False
return self.scope._futures_allowed
@futuresAllowed.setter
def futuresAllowed(self, value):
assert value is False
if isinstance(self.scope, ModuleScope):
self.scope._futures_allowed = False
@property
def annotationsFutureEnabled(self):
scope = self.scopeStack[0]
if not isinstance(scope, ModuleScope):
return False
return scope._annotations_future_enabled
@annotationsFutureEnabled.setter
def annotationsFutureEnabled(self, value):
assert value is True
assert isinstance(self.scope, ModuleScope)
self.scope._annotations_future_enabled = True
@property
def scope(self):
return self.scopeStack[-1]
def popScope(self):
self.deadScopes.append(self.scopeStack.pop())
def pushScope(self, scopeClass=FunctionScope):
self.scopeStack.append(scopeClass())
def report(self, messageClass, *args, **kwargs):
self.messages.append(messageClass(self.filename, *args, **kwargs))
def getParent(self, node):
# Lookup the first parent which is not Tuple, List or Starred
while True:
node = node.parent
if not hasattr(node, 'elts') and not hasattr(node, 'ctx'):
return node
def getCommonAncestor(self, lnode, rnode, stop):
if stop in (lnode, rnode) or not (hasattr(lnode, 'parent') and
hasattr(rnode, 'parent')):
return None
if lnode is rnode:
return lnode
if (lnode.depth > rnode.depth):
return self.getCommonAncestor(lnode.parent, rnode, stop)
if (lnode.depth < rnode.depth):
return self.getCommonAncestor(lnode, rnode.parent, stop)
return self.getCommonAncestor(lnode.parent, rnode.parent, stop)
def descendantOf(self, node, ancestors, stop):
for a in ancestors:
if self.getCommonAncestor(node, a, stop):
return True
return False
def _getAncestor(self, node, ancestor_type):
parent = node
while True:
if parent is self.root:
return None
parent = self.getParent(parent)
if isinstance(parent, ancestor_type):
return parent
def getScopeNode(self, node):
return self._getAncestor(node, tuple(Checker._ast_node_scope.keys()))
def differentForks(self, lnode, rnode):
"""True, if lnode and rnode are located on different forks of IF/TRY"""
ancestor = self.getCommonAncestor(lnode, rnode, self.root)
parts = getAlternatives(ancestor)
if parts:
for items in parts:
if self.descendantOf(lnode, items, ancestor) ^ \
self.descendantOf(rnode, items, ancestor):
return True
return False
def addBinding(self, node, value):
"""
Called when a binding is altered.
- `node` is the statement responsible for the change
- `value` is the new value, a Binding instance
"""
# assert value.source in (node, node.parent):
for scope in self.scopeStack[::-1]:
if value.name in scope:
break
existing = scope.get(value.name)
if (existing and not isinstance(existing, Builtin) and
not self.differentForks(node, existing.source)):
parent_stmt = self.getParent(value.source)
if isinstance(existing, Importation) and isinstance(parent_stmt, FOR_TYPES):
self.report(messages.ImportShadowedByLoopVar,
node, value.name, existing.source)
elif scope is self.scope:
if (isinstance(parent_stmt, ast.comprehension) and
not isinstance(self.getParent(existing.source),
(FOR_TYPES, ast.comprehension))):
self.report(messages.RedefinedInListComp,
node, value.name, existing.source)
elif not existing.used and value.redefines(existing):
if value.name != '_' or isinstance(existing, Importation):
if not is_typing_overload(existing, self.scopeStack):
self.report(messages.RedefinedWhileUnused,
node, value.name, existing.source)
elif isinstance(existing, Importation) and value.redefines(existing):
existing.redefined.append(node)
if value.name in self.scope:
# then assume the rebound name is used as a global or within a loop
value.used = self.scope[value.name].used
self.scope[value.name] = value
def getNodeHandler(self, node_class):
try:
return self._nodeHandlers[node_class]
except KeyError:
nodeType = getNodeType(node_class)
self._nodeHandlers[node_class] = handler = getattr(self, nodeType)
return handler
def handleNodeLoad(self, node):
name = getNodeName(node)
if not name:
return
in_generators = None
importStarred = None
# try enclosing function scopes and global scope
for scope in self.scopeStack[-1::-1]:
if isinstance(scope, ClassScope):
if not PY2 and name == '__class__':
return
elif in_generators is False:
# only generators used in a class scope can access the
# names of the class. this is skipped during the first
# iteration
continue
if (name == 'print' and
isinstance(scope.get(name, None), Builtin)):
parent = self.getParent(node)
if (isinstance(parent, ast.BinOp) and
isinstance(parent.op, ast.RShift)):
self.report(messages.InvalidPrintSyntax, node)
try:
scope[name].used = (self.scope, node)
# if the name of SubImportation is same as
# alias of other Importation and the alias
# is used, SubImportation also should be marked as used.
n = scope[name]
if isinstance(n, Importation) and n._has_alias():
try:
scope[n.fullName].used = (self.scope, node)
except KeyError:
pass
except KeyError:
pass
else:
return
importStarred = importStarred or scope.importStarred
if in_generators is not False:
in_generators = isinstance(scope, GeneratorScope)
if importStarred:
from_list = []
for scope in self.scopeStack[-1::-1]:
for binding in scope.values():
if isinstance(binding, StarImportation):
# mark '*' imports as used for each scope
binding.used = (self.scope, node)
from_list.append(binding.fullName)
# report * usage, with a list of possible sources
from_list = ', '.join(sorted(from_list))
self.report(messages.ImportStarUsage, node, name, from_list)
return
if name == '__path__' and os.path.basename(self.filename) == '__init__.py':
# the special name __path__ is valid only in packages
return
if name == '__module__' and isinstance(self.scope, ClassScope):
return
# protected with a NameError handler?
if 'NameError' not in self.exceptHandlers[-1]:
self.report(messages.UndefinedName, node, name)
def handleNodeStore(self, node):
name = getNodeName(node)
if not name:
return
# if the name hasn't already been defined in the current scope
if isinstance(self.scope, FunctionScope) and name not in self.scope:
# for each function or module scope above us
for scope in self.scopeStack[:-1]:
if not isinstance(scope, (FunctionScope, ModuleScope)):
continue
# if the name was defined in that scope, and the name has
# been accessed already in the current scope, and hasn't
# been declared global
used = name in scope and scope[name].used
if used and used[0] is self.scope and name not in self.scope.globals:
# then it's probably a mistake
self.report(messages.UndefinedLocal,
scope[name].used[1], name, scope[name].source)
break
parent_stmt = self.getParent(node)
if isinstance(parent_stmt, (FOR_TYPES, ast.comprehension)) or (
parent_stmt != node.parent and
not self.isLiteralTupleUnpacking(parent_stmt)):
binding = Binding(name, node)
elif name == '__all__' and isinstance(self.scope, ModuleScope):
binding = ExportBinding(name, node.parent, self.scope)
elif isinstance(getattr(node, 'ctx', None), ast.Param):
binding = Argument(name, self.getScopeNode(node))
else:
binding = Assignment(name, node)
self.addBinding(node, binding)
def handleNodeDelete(self, node):
def on_conditional_branch():
"""
Return `True` if node is part of a conditional body.
"""
current = getattr(node, 'parent', None)
while current:
if isinstance(current, (ast.If, ast.While, ast.IfExp)):
return True
current = getattr(current, 'parent', None)
return False
name = getNodeName(node)
if not name:
return
if on_conditional_branch():
# We cannot predict if this conditional branch is going to
# be executed.
return
if isinstance(self.scope, FunctionScope) and name in self.scope.globals:
self.scope.globals.remove(name)
else:
try:
del self.scope[name]
except KeyError:
self.report(messages.UndefinedName, node, name)
def _handle_type_comments(self, node):
for (lineno, col_offset), comment in self._type_comments.get(node, ()):
comment = comment.split(':', 1)[1].strip()
func_match = TYPE_FUNC_RE.match(comment)
if func_match:
parts = (
func_match.group(1).replace('*', ''),
func_match.group(2).strip(),
)
else:
parts = (comment,)
for part in parts:
if PY2:
part = part.replace('...', 'Ellipsis')
self.deferFunction(functools.partial(
self.handleStringAnnotation,
part, DummyNode(lineno, col_offset), lineno, col_offset,
messages.CommentAnnotationSyntaxError,
))
def handleChildren(self, tree, omit=None):
self._handle_type_comments(tree)
for node in iter_child_nodes(tree, omit=omit):
self.handleNode(node, tree)
def isLiteralTupleUnpacking(self, node):
if isinstance(node, ast.Assign):
for child in node.targets + [node.value]:
if not hasattr(child, 'elts'):
return False
return True
def isDocstring(self, node):
"""
Determine if the given node is a docstring, as long as it is at the
correct place in the node tree.
"""
return isinstance(node, ast.Str) or (isinstance(node, ast.Expr) and
isinstance(node.value, ast.Str))
def getDocstring(self, node):
if isinstance(node, ast.Expr):
node = node.value
if not isinstance(node, ast.Str):
return (None, None)
if PYPY or PY38_PLUS:
doctest_lineno = node.lineno - 1
else:
# Computed incorrectly if the docstring has backslash
doctest_lineno = node.lineno - node.s.count('\n') - 1
return (node.s, doctest_lineno)
def handleNode(self, node, parent):
if node is None:
return
if self.offset and getattr(node, 'lineno', None) is not None:
node.lineno += self.offset[0]
node.col_offset += self.offset[1]
if self.traceTree:
print(' ' * self.nodeDepth + node.__class__.__name__)
if self.futuresAllowed and not (isinstance(node, ast.ImportFrom) or
self.isDocstring(node)):
self.futuresAllowed = False
self.nodeDepth += 1
node.depth = self.nodeDepth
node.parent = parent
try:
handler = self.getNodeHandler(node.__class__)
handler(node)
finally:
self.nodeDepth -= 1
if self.traceTree:
print(' ' * self.nodeDepth + 'end ' + node.__class__.__name__)
_getDoctestExamples = doctest.DocTestParser().get_examples
def handleDoctests(self, node):
try:
if hasattr(node, 'docstring'):
docstring = node.docstring
# This is just a reasonable guess. In Python 3.7, docstrings no
# longer have line numbers associated with them. This will be
# incorrect if there are empty lines between the beginning
# of the function and the docstring.
node_lineno = node.lineno
if hasattr(node, 'args'):
node_lineno = max([node_lineno] +
[arg.lineno for arg in node.args.args])
else:
(docstring, node_lineno) = self.getDocstring(node.body[0])
examples = docstring and self._getDoctestExamples(docstring)
except (ValueError, IndexError):
# e.g. line 6 of the docstring for <string> has inconsistent
# leading whitespace: ...
return
if not examples:
return
# Place doctest in module scope
saved_stack = self.scopeStack
self.scopeStack = [self.scopeStack[0]]
node_offset = self.offset or (0, 0)
self.pushScope(DoctestScope)
self.addBinding(None, Builtin('_'))
for example in examples:
try:
tree = ast.parse(example.source, "<doctest>")
except SyntaxError:
e = sys.exc_info()[1]
if PYPY:
e.offset += 1
position = (node_lineno + example.lineno + e.lineno,
example.indent + 4 + (e.offset or 0))
self.report(messages.DoctestSyntaxError, node, position)
else:
self.offset = (node_offset[0] + node_lineno + example.lineno,
node_offset[1] + example.indent + 4)
self.handleChildren(tree)
self.offset = node_offset
self.popScope()
self.scopeStack = saved_stack
def handleStringAnnotation(self, s, node, ref_lineno, ref_col_offset, err):
try:
tree = ast.parse(s)
except SyntaxError:
self.report(err, node, s)
return
body = tree.body
if len(body) != 1 or not isinstance(body[0], ast.Expr):
self.report(err, node, s)
return
parsed_annotation = tree.body[0].value
for descendant in ast.walk(parsed_annotation):
if (
'lineno' in descendant._attributes and
'col_offset' in descendant._attributes
):
descendant.lineno = ref_lineno
descendant.col_offset = ref_col_offset
self.handleNode(parsed_annotation, node)
def handleAnnotation(self, annotation, node):
if isinstance(annotation, ast.Str):
# Defer handling forward annotation.
self.deferFunction(functools.partial(
self.handleStringAnnotation,
annotation.s,
node,
annotation.lineno,
annotation.col_offset,
messages.ForwardAnnotationSyntaxError,
))
elif self.annotationsFutureEnabled:
self.deferFunction(lambda: self.handleNode(annotation, node))
else:
self.handleNode(annotation, node)
def ignore(self, node):
pass
# "stmt" type nodes
DELETE = PRINT = FOR = ASYNCFOR = WHILE = IF = WITH = WITHITEM = \
ASYNCWITH = ASYNCWITHITEM = TRYFINALLY = EXEC = \
EXPR = ASSIGN = handleChildren
PASS = ignore
# "expr" type nodes
BOOLOP = BINOP = UNARYOP = IFEXP = SET = \
CALL = REPR = ATTRIBUTE = SUBSCRIPT = \
STARRED = NAMECONSTANT = handleChildren
NUM = STR = BYTES = ELLIPSIS = CONSTANT = ignore
# "slice" type nodes
SLICE = EXTSLICE = INDEX = handleChildren
# expression contexts are node instances too, though being constants
LOAD = STORE = DEL = AUGLOAD = AUGSTORE = PARAM = ignore
# same for operators
AND = OR = ADD = SUB = MULT = DIV = MOD = POW = LSHIFT = RSHIFT = \
BITOR = BITXOR = BITAND = FLOORDIV = INVERT = NOT = UADD = USUB = \
EQ = NOTEQ = LT = LTE = GT = GTE = IS = ISNOT = IN = NOTIN = \
MATMULT = ignore
def RAISE(self, node):
self.handleChildren(node)
arg = get_raise_argument(node)
if isinstance(arg, ast.Call):
if is_notimplemented_name_node(arg.func):
# Handle "raise NotImplemented(...)"
self.report(messages.RaiseNotImplemented, node)
elif is_notimplemented_name_node(arg):
# Handle "raise NotImplemented"
self.report(messages.RaiseNotImplemented, node)
# additional node types
COMPREHENSION = KEYWORD = FORMATTEDVALUE = JOINEDSTR = handleChildren
def DICT(self, node):
# Complain if there are duplicate keys with different values
# If they have the same value it's not going to cause potentially
# unexpected behaviour so we'll not complain.
keys = [
convert_to_value(key) for key in node.keys
]
key_counts = counter(keys)
duplicate_keys = [
key for key, count in key_counts.items()
if count > 1
]
for key in duplicate_keys:
key_indices = [i for i, i_key in enumerate(keys) if i_key == key]
values = counter(
convert_to_value(node.values[index])
for index in key_indices
)
if any(count == 1 for value, count in values.items()):
for key_index in key_indices:
key_node = node.keys[key_index]
if isinstance(key, VariableKey):
self.report(messages.MultiValueRepeatedKeyVariable,
key_node,
key.name)
else:
self.report(
messages.MultiValueRepeatedKeyLiteral,
key_node,
key,
)
self.handleChildren(node)
def ASSERT(self, node):
if isinstance(node.test, ast.Tuple) and node.test.elts != []:
self.report(messages.AssertTuple, node)
self.handleChildren(node)
def GLOBAL(self, node):
"""
Keep track of globals declarations.
"""
global_scope_index = 1 if self._in_doctest() else 0
global_scope = self.scopeStack[global_scope_index]
# Ignore 'global' statement in global scope.
if self.scope is not global_scope:
# One 'global' statement can bind multiple (comma-delimited) names.
for node_name in node.names:
node_value = Assignment(node_name, node)
# Remove UndefinedName messages already reported for this name.
# TODO: if the global is not used in this scope, it does not
# become a globally defined name. See test_unused_global.
self.messages = [
m for m in self.messages if not
isinstance(m, messages.UndefinedName) or
m.message_args[0] != node_name]
# Bind name to global scope if it doesn't exist already.
global_scope.setdefault(node_name, node_value)
# Bind name to non-global scopes, but as already "used".
node_value.used = (global_scope, node)
for scope in self.scopeStack[global_scope_index + 1:]:
scope[node_name] = node_value
NONLOCAL = GLOBAL
def GENERATOREXP(self, node):
self.pushScope(GeneratorScope)
self.handleChildren(node)
self.popScope()
LISTCOMP = handleChildren if PY2 else GENERATOREXP
DICTCOMP = SETCOMP = GENERATOREXP
def NAME(self, node):
"""
Handle occurrence of Name (which can be a load/store/delete access.)
"""
# Locate the name in locals / function / globals scopes.
if isinstance(node.ctx, (ast.Load, ast.AugLoad)):
self.handleNodeLoad(node)
if (node.id == 'locals' and isinstance(self.scope, FunctionScope) and
isinstance(node.parent, ast.Call)):
# we are doing locals() call in current scope
self.scope.usesLocals = True
elif isinstance(node.ctx, (ast.Store, ast.AugStore, ast.Param)):
self.handleNodeStore(node)
elif isinstance(node.ctx, ast.Del):
self.handleNodeDelete(node)
else:
# Unknown context
raise RuntimeError("Got impossible expression context: %r" % (node.ctx,))
def CONTINUE(self, node):
# Walk the tree up until we see a loop (OK), a function or class
# definition (not OK), for 'continue', a finally block (not OK), or
# the top module scope (not OK)
n = node
while hasattr(n, 'parent'):
n, n_child = n.parent, n
if isinstance(n, LOOP_TYPES):
# Doesn't apply unless it's in the loop itself
if n_child not in n.orelse:
return
if isinstance(n, (ast.FunctionDef, ast.ClassDef)):
break
# Handle Try/TryFinally difference in Python < and >= 3.3
if hasattr(n, 'finalbody') and isinstance(node, ast.Continue):
if n_child in n.finalbody:
self.report(messages.ContinueInFinally, node)
return
if isinstance(node, ast.Continue):
self.report(messages.ContinueOutsideLoop, node)
else: # ast.Break
self.report(messages.BreakOutsideLoop, node)
BREAK = CONTINUE
def RETURN(self, node):
if isinstance(self.scope, (ClassScope, ModuleScope)):
self.report(messages.ReturnOutsideFunction, node)
return
if (
node.value and
hasattr(self.scope, 'returnValue') and
not self.scope.returnValue
):
self.scope.returnValue = node.value
self.handleNode(node.value, node)
def YIELD(self, node):
if isinstance(self.scope, (ClassScope, ModuleScope)):
self.report(messages.YieldOutsideFunction, node)
return
self.scope.isGenerator = True
self.handleNode(node.value, node)
AWAIT = YIELDFROM = YIELD
def FUNCTIONDEF(self, node):
for deco in node.decorator_list:
self.handleNode(deco, node)
self.LAMBDA(node)
self.addBinding(node, FunctionDefinition(node.name, node))
# doctest does not process doctest within a doctest,
# or in nested functions.
if (self.withDoctest and
not self._in_doctest() and
not isinstance(self.scope, FunctionScope)):
self.deferFunction(lambda: self.handleDoctests(node))
ASYNCFUNCTIONDEF = FUNCTIONDEF
def LAMBDA(self, node):
args = []
annotations = []
if PY2:
def addArgs(arglist):
for arg in arglist:
if isinstance(arg, ast.Tuple):
addArgs(arg.elts)
else:
args.append(arg.id)
addArgs(node.args.args)
defaults = node.args.defaults
else:
for arg in node.args.args + node.args.kwonlyargs:
args.append(arg.arg)
annotations.append(arg.annotation)
defaults = node.args.defaults + node.args.kw_defaults
# Only for Python3 FunctionDefs
is_py3_func = hasattr(node, 'returns')
for arg_name in ('vararg', 'kwarg'):
wildcard = getattr(node.args, arg_name)
if not wildcard:
continue
args.append(wildcard if PY2 else wildcard.arg)
if is_py3_func:
if PY2: # Python 2.7
argannotation = arg_name + 'annotation'
annotations.append(getattr(node.args, argannotation))
else: # Python >= 3.4
annotations.append(wildcard.annotation)
if is_py3_func:
annotations.append(node.returns)
if len(set(args)) < len(args):
for (idx, arg) in enumerate(args):
if arg in args[:idx]:
self.report(messages.DuplicateArgument, node, arg)
for annotation in annotations:
self.handleAnnotation(annotation, node)
for default in defaults:
self.handleNode(default, node)
def runFunction():
self.pushScope()
self.handleChildren(node, omit='decorator_list')
def checkUnusedAssignments():
"""
Check to see if any assignments have not been used.
"""
for name, binding in self.scope.unusedAssignments():
self.report(messages.UnusedVariable, binding.source, name)
self.deferAssignment(checkUnusedAssignments)
if PY2:
def checkReturnWithArgumentInsideGenerator():
"""
Check to see if there is any return statement with
arguments but the function is a generator.
"""
if self.scope.isGenerator and self.scope.returnValue:
self.report(messages.ReturnWithArgsInsideGenerator,
self.scope.returnValue)
self.deferAssignment(checkReturnWithArgumentInsideGenerator)
self.popScope()
self.deferFunction(runFunction)
def ARGUMENTS(self, node):
self.handleChildren(node, omit=('defaults', 'kw_defaults'))
if PY2:
scope_node = self.getScopeNode(node)
if node.vararg:
self.addBinding(node, Argument(node.vararg, scope_node))
if node.kwarg:
self.addBinding(node, Argument(node.kwarg, scope_node))
def ARG(self, node):
self.addBinding(node, Argument(node.arg, self.getScopeNode(node)))
def CLASSDEF(self, node):
"""
Check names used in a class definition, including its decorators, base
classes, and the body of its definition. Additionally, add its name to
the current scope.
"""
for deco in node.decorator_list:
self.handleNode(deco, node)
for baseNode in node.bases:
self.handleNode(baseNode, node)
if not PY2:
for keywordNode in node.keywords:
self.handleNode(keywordNode, node)
self.pushScope(ClassScope)
# doctest does not process doctest within a doctest
# classes within classes are processed.
if (self.withDoctest and
not self._in_doctest() and
not isinstance(self.scope, FunctionScope)):
self.deferFunction(lambda: self.handleDoctests(node))
for stmt in node.body:
self.handleNode(stmt, node)
self.popScope()
self.addBinding(node, ClassDefinition(node.name, node))
def AUGASSIGN(self, node):
self.handleNodeLoad(node.target)
self.handleNode(node.value, node)
self.handleNode(node.target, node)
def TUPLE(self, node):
if not PY2 and isinstance(node.ctx, ast.Store):
# Python 3 advanced tuple unpacking: a, *b, c = d.
# Only one starred expression is allowed, and no more than 1<<8
# assignments are allowed before a stared expression. There is
# also a limit of 1<<24 expressions after the starred expression,
# which is impossible to test due to memory restrictions, but we
# add it here anyway
has_starred = False
star_loc = -1
for i, n in enumerate(node.elts):
if isinstance(n, ast.Starred):
if has_starred:
self.report(messages.TwoStarredExpressions, node)
# The SyntaxError doesn't distinguish two from more
# than two.
break
has_starred = True
star_loc = i
if star_loc >= 1 << 8 or len(node.elts) - star_loc - 1 >= 1 << 24:
self.report(messages.TooManyExpressionsInStarredAssignment, node)
self.handleChildren(node)
LIST = TUPLE
def IMPORT(self, node):
for alias in node.names:
if '.' in alias.name and not alias.asname:
importation = SubmoduleImportation(alias.name, node)
else:
name = alias.asname or alias.name
importation = Importation(name, node, alias.name)
self.addBinding(node, importation)
def IMPORTFROM(self, node):
if node.module == '__future__':
if not self.futuresAllowed:
self.report(messages.LateFutureImport,
node, [n.name for n in node.names])
else:
self.futuresAllowed = False
module = ('.' * node.level) + (node.module or '')
for alias in node.names:
name = alias.asname or alias.name
if node.module == '__future__':
importation = FutureImportation(name, node, self.scope)
if alias.name not in __future__.all_feature_names:
self.report(messages.FutureFeatureNotDefined,
node, alias.name)
if alias.name == 'annotations':
self.annotationsFutureEnabled = True
elif alias.name == '*':
# Only Python 2, local import * is a SyntaxWarning
if not PY2 and not isinstance(self.scope, ModuleScope):
self.report(messages.ImportStarNotPermitted,
node, module)
continue
self.scope.importStarred = True
self.report(messages.ImportStarUsed, node, module)
importation = StarImportation(module, node)
else:
importation = ImportationFrom(name, node,
module, alias.name)
self.addBinding(node, importation)
def TRY(self, node):
handler_names = []
# List the exception handlers
for i, handler in enumerate(node.handlers):
if isinstance(handler.type, ast.Tuple):
for exc_type in handler.type.elts:
handler_names.append(getNodeName(exc_type))
elif handler.type:
handler_names.append(getNodeName(handler.type))
if handler.type is None and i < len(node.handlers) - 1:
self.report(messages.DefaultExceptNotLast, handler)
# Memorize the except handlers and process the body
self.exceptHandlers.append(handler_names)
for child in node.body:
self.handleNode(child, node)
self.exceptHandlers.pop()
# Process the other nodes: "except:", "else:", "finally:"
self.handleChildren(node, omit='body')
TRYEXCEPT = TRY
def EXCEPTHANDLER(self, node):
if PY2 or node.name is None:
self.handleChildren(node)
return
# If the name already exists in the scope, modify state of existing
# binding.
if node.name in self.scope:
self.handleNodeStore(node)
# 3.x: the name of the exception, which is not a Name node, but a
# simple string, creates a local that is only bound within the scope of
# the except: block. As such, temporarily remove the existing binding
# to more accurately determine if the name is used in the except:
# block.
try:
prev_definition = self.scope.pop(node.name)
except KeyError:
prev_definition = None
self.handleNodeStore(node)
self.handleChildren(node)
# See discussion on https://github.com/PyCQA/pyflakes/pull/59
# We're removing the local name since it's being unbound after leaving
# the except: block and it's always unbound if the except: block is
# never entered. This will cause an "undefined name" error raised if
# the checked code tries to use the name afterwards.
#
# Unless it's been removed already. Then do nothing.
try:
binding = self.scope.pop(node.name)
except KeyError:
pass
else:
if not binding.used:
self.report(messages.UnusedVariable, node, node.name)
# Restore.
if prev_definition:
self.scope[node.name] = prev_definition
def ANNASSIGN(self, node):
if node.value:
# Only bind the *targets* if the assignment has a value.
# Otherwise it's not really ast.Store and shouldn't silence
# UndefinedLocal warnings.
self.handleNode(node.target, node)
self.handleAnnotation(node.annotation, node)
if node.value:
# If the assignment has value, handle the *value* now.
self.handleNode(node.value, node)
def COMPARE(self, node):
literals = (ast.Str, ast.Num)
if not PY2:
literals += (ast.Bytes,)
left = node.left
for op, right in zip(node.ops, node.comparators):
if (isinstance(op, (ast.Is, ast.IsNot)) and
(isinstance(left, literals) or isinstance(right, literals))):
self.report(messages.IsLiteral, node)
left = right
self.handleChildren(node)
|
PyCQA/pyflakes | pyflakes/checker.py | Checker.differentForks | python | def differentForks(self, lnode, rnode):
ancestor = self.getCommonAncestor(lnode, rnode, self.root)
parts = getAlternatives(ancestor)
if parts:
for items in parts:
if self.descendantOf(lnode, items, ancestor) ^ \
self.descendantOf(rnode, items, ancestor):
return True
return False | True, if lnode and rnode are located on different forks of IF/TRY | train | https://github.com/PyCQA/pyflakes/blob/232cb1d27ee134bf96adc8f37e53589dc259b159/pyflakes/checker.py#L860-L869 | [
"def getAlternatives(n):\n if isinstance(n, ast.If):\n return [n.body]\n if isinstance(n, ast.Try):\n return [n.body + n.orelse] + [[hdl] for hdl in n.handlers]\n",
"def getCommonAncestor(self, lnode, rnode, stop):\n if stop in (lnode, rnode) or not (hasattr(lnode, 'parent') and\n hasattr(rnode, 'parent')):\n return None\n if lnode is rnode:\n return lnode\n\n if (lnode.depth > rnode.depth):\n return self.getCommonAncestor(lnode.parent, rnode, stop)\n if (lnode.depth < rnode.depth):\n return self.getCommonAncestor(lnode, rnode.parent, stop)\n return self.getCommonAncestor(lnode.parent, rnode.parent, stop)\n",
"def descendantOf(self, node, ancestors, stop):\n for a in ancestors:\n if self.getCommonAncestor(node, a, stop):\n return True\n return False\n"
] | class Checker(object):
"""
I check the cleanliness and sanity of Python code.
@ivar _deferredFunctions: Tracking list used by L{deferFunction}. Elements
of the list are two-tuples. The first element is the callable passed
to L{deferFunction}. The second element is a copy of the scope stack
at the time L{deferFunction} was called.
@ivar _deferredAssignments: Similar to C{_deferredFunctions}, but for
callables which are deferred assignment checks.
"""
_ast_node_scope = {
ast.Module: ModuleScope,
ast.ClassDef: ClassScope,
ast.FunctionDef: FunctionScope,
ast.Lambda: FunctionScope,
ast.ListComp: GeneratorScope,
ast.SetComp: GeneratorScope,
ast.GeneratorExp: GeneratorScope,
ast.DictComp: GeneratorScope,
}
if PY35_PLUS:
_ast_node_scope[ast.AsyncFunctionDef] = FunctionScope,
nodeDepth = 0
offset = None
traceTree = False
builtIns = set(builtin_vars).union(_MAGIC_GLOBALS)
_customBuiltIns = os.environ.get('PYFLAKES_BUILTINS')
if _customBuiltIns:
builtIns.update(_customBuiltIns.split(','))
del _customBuiltIns
# TODO: file_tokens= is required to perform checks on type comments,
# eventually make this a required positional argument. For now it
# is defaulted to `()` for api compatibility.
def __init__(self, tree, filename='(none)', builtins=None,
withDoctest='PYFLAKES_DOCTEST' in os.environ, file_tokens=()):
self._nodeHandlers = {}
self._deferredFunctions = []
self._deferredAssignments = []
self.deadScopes = []
self.messages = []
self.filename = filename
if builtins:
self.builtIns = self.builtIns.union(builtins)
self.withDoctest = withDoctest
try:
self.scopeStack = [Checker._ast_node_scope[type(tree)]()]
except KeyError:
raise RuntimeError('No scope implemented for the node %r' % tree)
self.exceptHandlers = [()]
self.root = tree
self._type_comments = _collect_type_comments(tree, file_tokens)
for builtin in self.builtIns:
self.addBinding(None, Builtin(builtin))
self.handleChildren(tree)
self.runDeferred(self._deferredFunctions)
# Set _deferredFunctions to None so that deferFunction will fail
# noisily if called after we've run through the deferred functions.
self._deferredFunctions = None
self.runDeferred(self._deferredAssignments)
# Set _deferredAssignments to None so that deferAssignment will fail
# noisily if called after we've run through the deferred assignments.
self._deferredAssignments = None
del self.scopeStack[1:]
self.popScope()
self.checkDeadScopes()
def deferFunction(self, callable):
"""
Schedule a function handler to be called just before completion.
This is used for handling function bodies, which must be deferred
because code later in the file might modify the global scope. When
`callable` is called, the scope at the time this is called will be
restored, however it will contain any new bindings added to it.
"""
self._deferredFunctions.append((callable, self.scopeStack[:], self.offset))
def deferAssignment(self, callable):
"""
Schedule an assignment handler to be called just after deferred
function handlers.
"""
self._deferredAssignments.append((callable, self.scopeStack[:], self.offset))
def runDeferred(self, deferred):
"""
Run the callables in C{deferred} using their associated scope stack.
"""
for handler, scope, offset in deferred:
self.scopeStack = scope
self.offset = offset
handler()
def _in_doctest(self):
return (len(self.scopeStack) >= 2 and
isinstance(self.scopeStack[1], DoctestScope))
@property
def futuresAllowed(self):
if not all(isinstance(scope, ModuleScope)
for scope in self.scopeStack):
return False
return self.scope._futures_allowed
@futuresAllowed.setter
def futuresAllowed(self, value):
assert value is False
if isinstance(self.scope, ModuleScope):
self.scope._futures_allowed = False
@property
def annotationsFutureEnabled(self):
scope = self.scopeStack[0]
if not isinstance(scope, ModuleScope):
return False
return scope._annotations_future_enabled
@annotationsFutureEnabled.setter
def annotationsFutureEnabled(self, value):
assert value is True
assert isinstance(self.scope, ModuleScope)
self.scope._annotations_future_enabled = True
@property
def scope(self):
return self.scopeStack[-1]
def popScope(self):
self.deadScopes.append(self.scopeStack.pop())
def checkDeadScopes(self):
"""
Look at scopes which have been fully examined and report names in them
which were imported but unused.
"""
for scope in self.deadScopes:
# imports in classes are public members
if isinstance(scope, ClassScope):
continue
all_binding = scope.get('__all__')
if all_binding and not isinstance(all_binding, ExportBinding):
all_binding = None
if all_binding:
all_names = set(all_binding.names)
undefined = all_names.difference(scope)
else:
all_names = undefined = []
if undefined:
if not scope.importStarred and \
os.path.basename(self.filename) != '__init__.py':
# Look for possible mistakes in the export list
for name in undefined:
self.report(messages.UndefinedExport,
scope['__all__'].source, name)
# mark all import '*' as used by the undefined in __all__
if scope.importStarred:
from_list = []
for binding in scope.values():
if isinstance(binding, StarImportation):
binding.used = all_binding
from_list.append(binding.fullName)
# report * usage, with a list of possible sources
from_list = ', '.join(sorted(from_list))
for name in undefined:
self.report(messages.ImportStarUsage,
scope['__all__'].source, name, from_list)
# Look for imported names that aren't used.
for value in scope.values():
if isinstance(value, Importation):
used = value.used or value.name in all_names
if not used:
messg = messages.UnusedImport
self.report(messg, value.source, str(value))
for node in value.redefined:
if isinstance(self.getParent(node), FOR_TYPES):
messg = messages.ImportShadowedByLoopVar
elif used:
continue
else:
messg = messages.RedefinedWhileUnused
self.report(messg, node, value.name, value.source)
def pushScope(self, scopeClass=FunctionScope):
self.scopeStack.append(scopeClass())
def report(self, messageClass, *args, **kwargs):
self.messages.append(messageClass(self.filename, *args, **kwargs))
def getParent(self, node):
# Lookup the first parent which is not Tuple, List or Starred
while True:
node = node.parent
if not hasattr(node, 'elts') and not hasattr(node, 'ctx'):
return node
def getCommonAncestor(self, lnode, rnode, stop):
if stop in (lnode, rnode) or not (hasattr(lnode, 'parent') and
hasattr(rnode, 'parent')):
return None
if lnode is rnode:
return lnode
if (lnode.depth > rnode.depth):
return self.getCommonAncestor(lnode.parent, rnode, stop)
if (lnode.depth < rnode.depth):
return self.getCommonAncestor(lnode, rnode.parent, stop)
return self.getCommonAncestor(lnode.parent, rnode.parent, stop)
def descendantOf(self, node, ancestors, stop):
for a in ancestors:
if self.getCommonAncestor(node, a, stop):
return True
return False
def _getAncestor(self, node, ancestor_type):
parent = node
while True:
if parent is self.root:
return None
parent = self.getParent(parent)
if isinstance(parent, ancestor_type):
return parent
def getScopeNode(self, node):
return self._getAncestor(node, tuple(Checker._ast_node_scope.keys()))
def addBinding(self, node, value):
"""
Called when a binding is altered.
- `node` is the statement responsible for the change
- `value` is the new value, a Binding instance
"""
# assert value.source in (node, node.parent):
for scope in self.scopeStack[::-1]:
if value.name in scope:
break
existing = scope.get(value.name)
if (existing and not isinstance(existing, Builtin) and
not self.differentForks(node, existing.source)):
parent_stmt = self.getParent(value.source)
if isinstance(existing, Importation) and isinstance(parent_stmt, FOR_TYPES):
self.report(messages.ImportShadowedByLoopVar,
node, value.name, existing.source)
elif scope is self.scope:
if (isinstance(parent_stmt, ast.comprehension) and
not isinstance(self.getParent(existing.source),
(FOR_TYPES, ast.comprehension))):
self.report(messages.RedefinedInListComp,
node, value.name, existing.source)
elif not existing.used and value.redefines(existing):
if value.name != '_' or isinstance(existing, Importation):
if not is_typing_overload(existing, self.scopeStack):
self.report(messages.RedefinedWhileUnused,
node, value.name, existing.source)
elif isinstance(existing, Importation) and value.redefines(existing):
existing.redefined.append(node)
if value.name in self.scope:
# then assume the rebound name is used as a global or within a loop
value.used = self.scope[value.name].used
self.scope[value.name] = value
def getNodeHandler(self, node_class):
try:
return self._nodeHandlers[node_class]
except KeyError:
nodeType = getNodeType(node_class)
self._nodeHandlers[node_class] = handler = getattr(self, nodeType)
return handler
def handleNodeLoad(self, node):
name = getNodeName(node)
if not name:
return
in_generators = None
importStarred = None
# try enclosing function scopes and global scope
for scope in self.scopeStack[-1::-1]:
if isinstance(scope, ClassScope):
if not PY2 and name == '__class__':
return
elif in_generators is False:
# only generators used in a class scope can access the
# names of the class. this is skipped during the first
# iteration
continue
if (name == 'print' and
isinstance(scope.get(name, None), Builtin)):
parent = self.getParent(node)
if (isinstance(parent, ast.BinOp) and
isinstance(parent.op, ast.RShift)):
self.report(messages.InvalidPrintSyntax, node)
try:
scope[name].used = (self.scope, node)
# if the name of SubImportation is same as
# alias of other Importation and the alias
# is used, SubImportation also should be marked as used.
n = scope[name]
if isinstance(n, Importation) and n._has_alias():
try:
scope[n.fullName].used = (self.scope, node)
except KeyError:
pass
except KeyError:
pass
else:
return
importStarred = importStarred or scope.importStarred
if in_generators is not False:
in_generators = isinstance(scope, GeneratorScope)
if importStarred:
from_list = []
for scope in self.scopeStack[-1::-1]:
for binding in scope.values():
if isinstance(binding, StarImportation):
# mark '*' imports as used for each scope
binding.used = (self.scope, node)
from_list.append(binding.fullName)
# report * usage, with a list of possible sources
from_list = ', '.join(sorted(from_list))
self.report(messages.ImportStarUsage, node, name, from_list)
return
if name == '__path__' and os.path.basename(self.filename) == '__init__.py':
# the special name __path__ is valid only in packages
return
if name == '__module__' and isinstance(self.scope, ClassScope):
return
# protected with a NameError handler?
if 'NameError' not in self.exceptHandlers[-1]:
self.report(messages.UndefinedName, node, name)
def handleNodeStore(self, node):
name = getNodeName(node)
if not name:
return
# if the name hasn't already been defined in the current scope
if isinstance(self.scope, FunctionScope) and name not in self.scope:
# for each function or module scope above us
for scope in self.scopeStack[:-1]:
if not isinstance(scope, (FunctionScope, ModuleScope)):
continue
# if the name was defined in that scope, and the name has
# been accessed already in the current scope, and hasn't
# been declared global
used = name in scope and scope[name].used
if used and used[0] is self.scope and name not in self.scope.globals:
# then it's probably a mistake
self.report(messages.UndefinedLocal,
scope[name].used[1], name, scope[name].source)
break
parent_stmt = self.getParent(node)
if isinstance(parent_stmt, (FOR_TYPES, ast.comprehension)) or (
parent_stmt != node.parent and
not self.isLiteralTupleUnpacking(parent_stmt)):
binding = Binding(name, node)
elif name == '__all__' and isinstance(self.scope, ModuleScope):
binding = ExportBinding(name, node.parent, self.scope)
elif isinstance(getattr(node, 'ctx', None), ast.Param):
binding = Argument(name, self.getScopeNode(node))
else:
binding = Assignment(name, node)
self.addBinding(node, binding)
def handleNodeDelete(self, node):
def on_conditional_branch():
"""
Return `True` if node is part of a conditional body.
"""
current = getattr(node, 'parent', None)
while current:
if isinstance(current, (ast.If, ast.While, ast.IfExp)):
return True
current = getattr(current, 'parent', None)
return False
name = getNodeName(node)
if not name:
return
if on_conditional_branch():
# We cannot predict if this conditional branch is going to
# be executed.
return
if isinstance(self.scope, FunctionScope) and name in self.scope.globals:
self.scope.globals.remove(name)
else:
try:
del self.scope[name]
except KeyError:
self.report(messages.UndefinedName, node, name)
def _handle_type_comments(self, node):
for (lineno, col_offset), comment in self._type_comments.get(node, ()):
comment = comment.split(':', 1)[1].strip()
func_match = TYPE_FUNC_RE.match(comment)
if func_match:
parts = (
func_match.group(1).replace('*', ''),
func_match.group(2).strip(),
)
else:
parts = (comment,)
for part in parts:
if PY2:
part = part.replace('...', 'Ellipsis')
self.deferFunction(functools.partial(
self.handleStringAnnotation,
part, DummyNode(lineno, col_offset), lineno, col_offset,
messages.CommentAnnotationSyntaxError,
))
def handleChildren(self, tree, omit=None):
self._handle_type_comments(tree)
for node in iter_child_nodes(tree, omit=omit):
self.handleNode(node, tree)
def isLiteralTupleUnpacking(self, node):
if isinstance(node, ast.Assign):
for child in node.targets + [node.value]:
if not hasattr(child, 'elts'):
return False
return True
def isDocstring(self, node):
"""
Determine if the given node is a docstring, as long as it is at the
correct place in the node tree.
"""
return isinstance(node, ast.Str) or (isinstance(node, ast.Expr) and
isinstance(node.value, ast.Str))
def getDocstring(self, node):
if isinstance(node, ast.Expr):
node = node.value
if not isinstance(node, ast.Str):
return (None, None)
if PYPY or PY38_PLUS:
doctest_lineno = node.lineno - 1
else:
# Computed incorrectly if the docstring has backslash
doctest_lineno = node.lineno - node.s.count('\n') - 1
return (node.s, doctest_lineno)
def handleNode(self, node, parent):
if node is None:
return
if self.offset and getattr(node, 'lineno', None) is not None:
node.lineno += self.offset[0]
node.col_offset += self.offset[1]
if self.traceTree:
print(' ' * self.nodeDepth + node.__class__.__name__)
if self.futuresAllowed and not (isinstance(node, ast.ImportFrom) or
self.isDocstring(node)):
self.futuresAllowed = False
self.nodeDepth += 1
node.depth = self.nodeDepth
node.parent = parent
try:
handler = self.getNodeHandler(node.__class__)
handler(node)
finally:
self.nodeDepth -= 1
if self.traceTree:
print(' ' * self.nodeDepth + 'end ' + node.__class__.__name__)
_getDoctestExamples = doctest.DocTestParser().get_examples
def handleDoctests(self, node):
try:
if hasattr(node, 'docstring'):
docstring = node.docstring
# This is just a reasonable guess. In Python 3.7, docstrings no
# longer have line numbers associated with them. This will be
# incorrect if there are empty lines between the beginning
# of the function and the docstring.
node_lineno = node.lineno
if hasattr(node, 'args'):
node_lineno = max([node_lineno] +
[arg.lineno for arg in node.args.args])
else:
(docstring, node_lineno) = self.getDocstring(node.body[0])
examples = docstring and self._getDoctestExamples(docstring)
except (ValueError, IndexError):
# e.g. line 6 of the docstring for <string> has inconsistent
# leading whitespace: ...
return
if not examples:
return
# Place doctest in module scope
saved_stack = self.scopeStack
self.scopeStack = [self.scopeStack[0]]
node_offset = self.offset or (0, 0)
self.pushScope(DoctestScope)
self.addBinding(None, Builtin('_'))
for example in examples:
try:
tree = ast.parse(example.source, "<doctest>")
except SyntaxError:
e = sys.exc_info()[1]
if PYPY:
e.offset += 1
position = (node_lineno + example.lineno + e.lineno,
example.indent + 4 + (e.offset or 0))
self.report(messages.DoctestSyntaxError, node, position)
else:
self.offset = (node_offset[0] + node_lineno + example.lineno,
node_offset[1] + example.indent + 4)
self.handleChildren(tree)
self.offset = node_offset
self.popScope()
self.scopeStack = saved_stack
def handleStringAnnotation(self, s, node, ref_lineno, ref_col_offset, err):
try:
tree = ast.parse(s)
except SyntaxError:
self.report(err, node, s)
return
body = tree.body
if len(body) != 1 or not isinstance(body[0], ast.Expr):
self.report(err, node, s)
return
parsed_annotation = tree.body[0].value
for descendant in ast.walk(parsed_annotation):
if (
'lineno' in descendant._attributes and
'col_offset' in descendant._attributes
):
descendant.lineno = ref_lineno
descendant.col_offset = ref_col_offset
self.handleNode(parsed_annotation, node)
def handleAnnotation(self, annotation, node):
if isinstance(annotation, ast.Str):
# Defer handling forward annotation.
self.deferFunction(functools.partial(
self.handleStringAnnotation,
annotation.s,
node,
annotation.lineno,
annotation.col_offset,
messages.ForwardAnnotationSyntaxError,
))
elif self.annotationsFutureEnabled:
self.deferFunction(lambda: self.handleNode(annotation, node))
else:
self.handleNode(annotation, node)
def ignore(self, node):
pass
# "stmt" type nodes
DELETE = PRINT = FOR = ASYNCFOR = WHILE = IF = WITH = WITHITEM = \
ASYNCWITH = ASYNCWITHITEM = TRYFINALLY = EXEC = \
EXPR = ASSIGN = handleChildren
PASS = ignore
# "expr" type nodes
BOOLOP = BINOP = UNARYOP = IFEXP = SET = \
CALL = REPR = ATTRIBUTE = SUBSCRIPT = \
STARRED = NAMECONSTANT = handleChildren
NUM = STR = BYTES = ELLIPSIS = CONSTANT = ignore
# "slice" type nodes
SLICE = EXTSLICE = INDEX = handleChildren
# expression contexts are node instances too, though being constants
LOAD = STORE = DEL = AUGLOAD = AUGSTORE = PARAM = ignore
# same for operators
AND = OR = ADD = SUB = MULT = DIV = MOD = POW = LSHIFT = RSHIFT = \
BITOR = BITXOR = BITAND = FLOORDIV = INVERT = NOT = UADD = USUB = \
EQ = NOTEQ = LT = LTE = GT = GTE = IS = ISNOT = IN = NOTIN = \
MATMULT = ignore
def RAISE(self, node):
self.handleChildren(node)
arg = get_raise_argument(node)
if isinstance(arg, ast.Call):
if is_notimplemented_name_node(arg.func):
# Handle "raise NotImplemented(...)"
self.report(messages.RaiseNotImplemented, node)
elif is_notimplemented_name_node(arg):
# Handle "raise NotImplemented"
self.report(messages.RaiseNotImplemented, node)
# additional node types
COMPREHENSION = KEYWORD = FORMATTEDVALUE = JOINEDSTR = handleChildren
def DICT(self, node):
# Complain if there are duplicate keys with different values
# If they have the same value it's not going to cause potentially
# unexpected behaviour so we'll not complain.
keys = [
convert_to_value(key) for key in node.keys
]
key_counts = counter(keys)
duplicate_keys = [
key for key, count in key_counts.items()
if count > 1
]
for key in duplicate_keys:
key_indices = [i for i, i_key in enumerate(keys) if i_key == key]
values = counter(
convert_to_value(node.values[index])
for index in key_indices
)
if any(count == 1 for value, count in values.items()):
for key_index in key_indices:
key_node = node.keys[key_index]
if isinstance(key, VariableKey):
self.report(messages.MultiValueRepeatedKeyVariable,
key_node,
key.name)
else:
self.report(
messages.MultiValueRepeatedKeyLiteral,
key_node,
key,
)
self.handleChildren(node)
def ASSERT(self, node):
if isinstance(node.test, ast.Tuple) and node.test.elts != []:
self.report(messages.AssertTuple, node)
self.handleChildren(node)
def GLOBAL(self, node):
"""
Keep track of globals declarations.
"""
global_scope_index = 1 if self._in_doctest() else 0
global_scope = self.scopeStack[global_scope_index]
# Ignore 'global' statement in global scope.
if self.scope is not global_scope:
# One 'global' statement can bind multiple (comma-delimited) names.
for node_name in node.names:
node_value = Assignment(node_name, node)
# Remove UndefinedName messages already reported for this name.
# TODO: if the global is not used in this scope, it does not
# become a globally defined name. See test_unused_global.
self.messages = [
m for m in self.messages if not
isinstance(m, messages.UndefinedName) or
m.message_args[0] != node_name]
# Bind name to global scope if it doesn't exist already.
global_scope.setdefault(node_name, node_value)
# Bind name to non-global scopes, but as already "used".
node_value.used = (global_scope, node)
for scope in self.scopeStack[global_scope_index + 1:]:
scope[node_name] = node_value
NONLOCAL = GLOBAL
def GENERATOREXP(self, node):
self.pushScope(GeneratorScope)
self.handleChildren(node)
self.popScope()
LISTCOMP = handleChildren if PY2 else GENERATOREXP
DICTCOMP = SETCOMP = GENERATOREXP
def NAME(self, node):
"""
Handle occurrence of Name (which can be a load/store/delete access.)
"""
# Locate the name in locals / function / globals scopes.
if isinstance(node.ctx, (ast.Load, ast.AugLoad)):
self.handleNodeLoad(node)
if (node.id == 'locals' and isinstance(self.scope, FunctionScope) and
isinstance(node.parent, ast.Call)):
# we are doing locals() call in current scope
self.scope.usesLocals = True
elif isinstance(node.ctx, (ast.Store, ast.AugStore, ast.Param)):
self.handleNodeStore(node)
elif isinstance(node.ctx, ast.Del):
self.handleNodeDelete(node)
else:
# Unknown context
raise RuntimeError("Got impossible expression context: %r" % (node.ctx,))
def CONTINUE(self, node):
# Walk the tree up until we see a loop (OK), a function or class
# definition (not OK), for 'continue', a finally block (not OK), or
# the top module scope (not OK)
n = node
while hasattr(n, 'parent'):
n, n_child = n.parent, n
if isinstance(n, LOOP_TYPES):
# Doesn't apply unless it's in the loop itself
if n_child not in n.orelse:
return
if isinstance(n, (ast.FunctionDef, ast.ClassDef)):
break
# Handle Try/TryFinally difference in Python < and >= 3.3
if hasattr(n, 'finalbody') and isinstance(node, ast.Continue):
if n_child in n.finalbody:
self.report(messages.ContinueInFinally, node)
return
if isinstance(node, ast.Continue):
self.report(messages.ContinueOutsideLoop, node)
else: # ast.Break
self.report(messages.BreakOutsideLoop, node)
BREAK = CONTINUE
def RETURN(self, node):
if isinstance(self.scope, (ClassScope, ModuleScope)):
self.report(messages.ReturnOutsideFunction, node)
return
if (
node.value and
hasattr(self.scope, 'returnValue') and
not self.scope.returnValue
):
self.scope.returnValue = node.value
self.handleNode(node.value, node)
def YIELD(self, node):
if isinstance(self.scope, (ClassScope, ModuleScope)):
self.report(messages.YieldOutsideFunction, node)
return
self.scope.isGenerator = True
self.handleNode(node.value, node)
AWAIT = YIELDFROM = YIELD
def FUNCTIONDEF(self, node):
for deco in node.decorator_list:
self.handleNode(deco, node)
self.LAMBDA(node)
self.addBinding(node, FunctionDefinition(node.name, node))
# doctest does not process doctest within a doctest,
# or in nested functions.
if (self.withDoctest and
not self._in_doctest() and
not isinstance(self.scope, FunctionScope)):
self.deferFunction(lambda: self.handleDoctests(node))
ASYNCFUNCTIONDEF = FUNCTIONDEF
def LAMBDA(self, node):
args = []
annotations = []
if PY2:
def addArgs(arglist):
for arg in arglist:
if isinstance(arg, ast.Tuple):
addArgs(arg.elts)
else:
args.append(arg.id)
addArgs(node.args.args)
defaults = node.args.defaults
else:
for arg in node.args.args + node.args.kwonlyargs:
args.append(arg.arg)
annotations.append(arg.annotation)
defaults = node.args.defaults + node.args.kw_defaults
# Only for Python3 FunctionDefs
is_py3_func = hasattr(node, 'returns')
for arg_name in ('vararg', 'kwarg'):
wildcard = getattr(node.args, arg_name)
if not wildcard:
continue
args.append(wildcard if PY2 else wildcard.arg)
if is_py3_func:
if PY2: # Python 2.7
argannotation = arg_name + 'annotation'
annotations.append(getattr(node.args, argannotation))
else: # Python >= 3.4
annotations.append(wildcard.annotation)
if is_py3_func:
annotations.append(node.returns)
if len(set(args)) < len(args):
for (idx, arg) in enumerate(args):
if arg in args[:idx]:
self.report(messages.DuplicateArgument, node, arg)
for annotation in annotations:
self.handleAnnotation(annotation, node)
for default in defaults:
self.handleNode(default, node)
def runFunction():
self.pushScope()
self.handleChildren(node, omit='decorator_list')
def checkUnusedAssignments():
"""
Check to see if any assignments have not been used.
"""
for name, binding in self.scope.unusedAssignments():
self.report(messages.UnusedVariable, binding.source, name)
self.deferAssignment(checkUnusedAssignments)
if PY2:
def checkReturnWithArgumentInsideGenerator():
"""
Check to see if there is any return statement with
arguments but the function is a generator.
"""
if self.scope.isGenerator and self.scope.returnValue:
self.report(messages.ReturnWithArgsInsideGenerator,
self.scope.returnValue)
self.deferAssignment(checkReturnWithArgumentInsideGenerator)
self.popScope()
self.deferFunction(runFunction)
def ARGUMENTS(self, node):
self.handleChildren(node, omit=('defaults', 'kw_defaults'))
if PY2:
scope_node = self.getScopeNode(node)
if node.vararg:
self.addBinding(node, Argument(node.vararg, scope_node))
if node.kwarg:
self.addBinding(node, Argument(node.kwarg, scope_node))
def ARG(self, node):
self.addBinding(node, Argument(node.arg, self.getScopeNode(node)))
def CLASSDEF(self, node):
"""
Check names used in a class definition, including its decorators, base
classes, and the body of its definition. Additionally, add its name to
the current scope.
"""
for deco in node.decorator_list:
self.handleNode(deco, node)
for baseNode in node.bases:
self.handleNode(baseNode, node)
if not PY2:
for keywordNode in node.keywords:
self.handleNode(keywordNode, node)
self.pushScope(ClassScope)
# doctest does not process doctest within a doctest
# classes within classes are processed.
if (self.withDoctest and
not self._in_doctest() and
not isinstance(self.scope, FunctionScope)):
self.deferFunction(lambda: self.handleDoctests(node))
for stmt in node.body:
self.handleNode(stmt, node)
self.popScope()
self.addBinding(node, ClassDefinition(node.name, node))
def AUGASSIGN(self, node):
self.handleNodeLoad(node.target)
self.handleNode(node.value, node)
self.handleNode(node.target, node)
def TUPLE(self, node):
if not PY2 and isinstance(node.ctx, ast.Store):
# Python 3 advanced tuple unpacking: a, *b, c = d.
# Only one starred expression is allowed, and no more than 1<<8
# assignments are allowed before a stared expression. There is
# also a limit of 1<<24 expressions after the starred expression,
# which is impossible to test due to memory restrictions, but we
# add it here anyway
has_starred = False
star_loc = -1
for i, n in enumerate(node.elts):
if isinstance(n, ast.Starred):
if has_starred:
self.report(messages.TwoStarredExpressions, node)
# The SyntaxError doesn't distinguish two from more
# than two.
break
has_starred = True
star_loc = i
if star_loc >= 1 << 8 or len(node.elts) - star_loc - 1 >= 1 << 24:
self.report(messages.TooManyExpressionsInStarredAssignment, node)
self.handleChildren(node)
LIST = TUPLE
def IMPORT(self, node):
for alias in node.names:
if '.' in alias.name and not alias.asname:
importation = SubmoduleImportation(alias.name, node)
else:
name = alias.asname or alias.name
importation = Importation(name, node, alias.name)
self.addBinding(node, importation)
def IMPORTFROM(self, node):
if node.module == '__future__':
if not self.futuresAllowed:
self.report(messages.LateFutureImport,
node, [n.name for n in node.names])
else:
self.futuresAllowed = False
module = ('.' * node.level) + (node.module or '')
for alias in node.names:
name = alias.asname or alias.name
if node.module == '__future__':
importation = FutureImportation(name, node, self.scope)
if alias.name not in __future__.all_feature_names:
self.report(messages.FutureFeatureNotDefined,
node, alias.name)
if alias.name == 'annotations':
self.annotationsFutureEnabled = True
elif alias.name == '*':
# Only Python 2, local import * is a SyntaxWarning
if not PY2 and not isinstance(self.scope, ModuleScope):
self.report(messages.ImportStarNotPermitted,
node, module)
continue
self.scope.importStarred = True
self.report(messages.ImportStarUsed, node, module)
importation = StarImportation(module, node)
else:
importation = ImportationFrom(name, node,
module, alias.name)
self.addBinding(node, importation)
def TRY(self, node):
handler_names = []
# List the exception handlers
for i, handler in enumerate(node.handlers):
if isinstance(handler.type, ast.Tuple):
for exc_type in handler.type.elts:
handler_names.append(getNodeName(exc_type))
elif handler.type:
handler_names.append(getNodeName(handler.type))
if handler.type is None and i < len(node.handlers) - 1:
self.report(messages.DefaultExceptNotLast, handler)
# Memorize the except handlers and process the body
self.exceptHandlers.append(handler_names)
for child in node.body:
self.handleNode(child, node)
self.exceptHandlers.pop()
# Process the other nodes: "except:", "else:", "finally:"
self.handleChildren(node, omit='body')
TRYEXCEPT = TRY
def EXCEPTHANDLER(self, node):
if PY2 or node.name is None:
self.handleChildren(node)
return
# If the name already exists in the scope, modify state of existing
# binding.
if node.name in self.scope:
self.handleNodeStore(node)
# 3.x: the name of the exception, which is not a Name node, but a
# simple string, creates a local that is only bound within the scope of
# the except: block. As such, temporarily remove the existing binding
# to more accurately determine if the name is used in the except:
# block.
try:
prev_definition = self.scope.pop(node.name)
except KeyError:
prev_definition = None
self.handleNodeStore(node)
self.handleChildren(node)
# See discussion on https://github.com/PyCQA/pyflakes/pull/59
# We're removing the local name since it's being unbound after leaving
# the except: block and it's always unbound if the except: block is
# never entered. This will cause an "undefined name" error raised if
# the checked code tries to use the name afterwards.
#
# Unless it's been removed already. Then do nothing.
try:
binding = self.scope.pop(node.name)
except KeyError:
pass
else:
if not binding.used:
self.report(messages.UnusedVariable, node, node.name)
# Restore.
if prev_definition:
self.scope[node.name] = prev_definition
def ANNASSIGN(self, node):
if node.value:
# Only bind the *targets* if the assignment has a value.
# Otherwise it's not really ast.Store and shouldn't silence
# UndefinedLocal warnings.
self.handleNode(node.target, node)
self.handleAnnotation(node.annotation, node)
if node.value:
# If the assignment has value, handle the *value* now.
self.handleNode(node.value, node)
def COMPARE(self, node):
literals = (ast.Str, ast.Num)
if not PY2:
literals += (ast.Bytes,)
left = node.left
for op, right in zip(node.ops, node.comparators):
if (isinstance(op, (ast.Is, ast.IsNot)) and
(isinstance(left, literals) or isinstance(right, literals))):
self.report(messages.IsLiteral, node)
left = right
self.handleChildren(node)
|
PyCQA/pyflakes | pyflakes/checker.py | Checker.addBinding | python | def addBinding(self, node, value):
# assert value.source in (node, node.parent):
for scope in self.scopeStack[::-1]:
if value.name in scope:
break
existing = scope.get(value.name)
if (existing and not isinstance(existing, Builtin) and
not self.differentForks(node, existing.source)):
parent_stmt = self.getParent(value.source)
if isinstance(existing, Importation) and isinstance(parent_stmt, FOR_TYPES):
self.report(messages.ImportShadowedByLoopVar,
node, value.name, existing.source)
elif scope is self.scope:
if (isinstance(parent_stmt, ast.comprehension) and
not isinstance(self.getParent(existing.source),
(FOR_TYPES, ast.comprehension))):
self.report(messages.RedefinedInListComp,
node, value.name, existing.source)
elif not existing.used and value.redefines(existing):
if value.name != '_' or isinstance(existing, Importation):
if not is_typing_overload(existing, self.scopeStack):
self.report(messages.RedefinedWhileUnused,
node, value.name, existing.source)
elif isinstance(existing, Importation) and value.redefines(existing):
existing.redefined.append(node)
if value.name in self.scope:
# then assume the rebound name is used as a global or within a loop
value.used = self.scope[value.name].used
self.scope[value.name] = value | Called when a binding is altered.
- `node` is the statement responsible for the change
- `value` is the new value, a Binding instance | train | https://github.com/PyCQA/pyflakes/blob/232cb1d27ee134bf96adc8f37e53589dc259b159/pyflakes/checker.py#L871-L911 | [
"def differentForks(self, lnode, rnode):\n \"\"\"True, if lnode and rnode are located on different forks of IF/TRY\"\"\"\n ancestor = self.getCommonAncestor(lnode, rnode, self.root)\n parts = getAlternatives(ancestor)\n if parts:\n for items in parts:\n if self.descendantOf(lnode, items, ancestor) ^ \\\n self.descendantOf(rnode, items, ancestor):\n return True\n return False\n"
] | class Checker(object):
"""
I check the cleanliness and sanity of Python code.
@ivar _deferredFunctions: Tracking list used by L{deferFunction}. Elements
of the list are two-tuples. The first element is the callable passed
to L{deferFunction}. The second element is a copy of the scope stack
at the time L{deferFunction} was called.
@ivar _deferredAssignments: Similar to C{_deferredFunctions}, but for
callables which are deferred assignment checks.
"""
_ast_node_scope = {
ast.Module: ModuleScope,
ast.ClassDef: ClassScope,
ast.FunctionDef: FunctionScope,
ast.Lambda: FunctionScope,
ast.ListComp: GeneratorScope,
ast.SetComp: GeneratorScope,
ast.GeneratorExp: GeneratorScope,
ast.DictComp: GeneratorScope,
}
if PY35_PLUS:
_ast_node_scope[ast.AsyncFunctionDef] = FunctionScope,
nodeDepth = 0
offset = None
traceTree = False
builtIns = set(builtin_vars).union(_MAGIC_GLOBALS)
_customBuiltIns = os.environ.get('PYFLAKES_BUILTINS')
if _customBuiltIns:
builtIns.update(_customBuiltIns.split(','))
del _customBuiltIns
# TODO: file_tokens= is required to perform checks on type comments,
# eventually make this a required positional argument. For now it
# is defaulted to `()` for api compatibility.
def __init__(self, tree, filename='(none)', builtins=None,
withDoctest='PYFLAKES_DOCTEST' in os.environ, file_tokens=()):
self._nodeHandlers = {}
self._deferredFunctions = []
self._deferredAssignments = []
self.deadScopes = []
self.messages = []
self.filename = filename
if builtins:
self.builtIns = self.builtIns.union(builtins)
self.withDoctest = withDoctest
try:
self.scopeStack = [Checker._ast_node_scope[type(tree)]()]
except KeyError:
raise RuntimeError('No scope implemented for the node %r' % tree)
self.exceptHandlers = [()]
self.root = tree
self._type_comments = _collect_type_comments(tree, file_tokens)
for builtin in self.builtIns:
self.addBinding(None, Builtin(builtin))
self.handleChildren(tree)
self.runDeferred(self._deferredFunctions)
# Set _deferredFunctions to None so that deferFunction will fail
# noisily if called after we've run through the deferred functions.
self._deferredFunctions = None
self.runDeferred(self._deferredAssignments)
# Set _deferredAssignments to None so that deferAssignment will fail
# noisily if called after we've run through the deferred assignments.
self._deferredAssignments = None
del self.scopeStack[1:]
self.popScope()
self.checkDeadScopes()
def deferFunction(self, callable):
"""
Schedule a function handler to be called just before completion.
This is used for handling function bodies, which must be deferred
because code later in the file might modify the global scope. When
`callable` is called, the scope at the time this is called will be
restored, however it will contain any new bindings added to it.
"""
self._deferredFunctions.append((callable, self.scopeStack[:], self.offset))
def deferAssignment(self, callable):
"""
Schedule an assignment handler to be called just after deferred
function handlers.
"""
self._deferredAssignments.append((callable, self.scopeStack[:], self.offset))
def runDeferred(self, deferred):
"""
Run the callables in C{deferred} using their associated scope stack.
"""
for handler, scope, offset in deferred:
self.scopeStack = scope
self.offset = offset
handler()
def _in_doctest(self):
return (len(self.scopeStack) >= 2 and
isinstance(self.scopeStack[1], DoctestScope))
@property
def futuresAllowed(self):
if not all(isinstance(scope, ModuleScope)
for scope in self.scopeStack):
return False
return self.scope._futures_allowed
@futuresAllowed.setter
def futuresAllowed(self, value):
assert value is False
if isinstance(self.scope, ModuleScope):
self.scope._futures_allowed = False
@property
def annotationsFutureEnabled(self):
scope = self.scopeStack[0]
if not isinstance(scope, ModuleScope):
return False
return scope._annotations_future_enabled
@annotationsFutureEnabled.setter
def annotationsFutureEnabled(self, value):
assert value is True
assert isinstance(self.scope, ModuleScope)
self.scope._annotations_future_enabled = True
@property
def scope(self):
return self.scopeStack[-1]
def popScope(self):
self.deadScopes.append(self.scopeStack.pop())
def checkDeadScopes(self):
"""
Look at scopes which have been fully examined and report names in them
which were imported but unused.
"""
for scope in self.deadScopes:
# imports in classes are public members
if isinstance(scope, ClassScope):
continue
all_binding = scope.get('__all__')
if all_binding and not isinstance(all_binding, ExportBinding):
all_binding = None
if all_binding:
all_names = set(all_binding.names)
undefined = all_names.difference(scope)
else:
all_names = undefined = []
if undefined:
if not scope.importStarred and \
os.path.basename(self.filename) != '__init__.py':
# Look for possible mistakes in the export list
for name in undefined:
self.report(messages.UndefinedExport,
scope['__all__'].source, name)
# mark all import '*' as used by the undefined in __all__
if scope.importStarred:
from_list = []
for binding in scope.values():
if isinstance(binding, StarImportation):
binding.used = all_binding
from_list.append(binding.fullName)
# report * usage, with a list of possible sources
from_list = ', '.join(sorted(from_list))
for name in undefined:
self.report(messages.ImportStarUsage,
scope['__all__'].source, name, from_list)
# Look for imported names that aren't used.
for value in scope.values():
if isinstance(value, Importation):
used = value.used or value.name in all_names
if not used:
messg = messages.UnusedImport
self.report(messg, value.source, str(value))
for node in value.redefined:
if isinstance(self.getParent(node), FOR_TYPES):
messg = messages.ImportShadowedByLoopVar
elif used:
continue
else:
messg = messages.RedefinedWhileUnused
self.report(messg, node, value.name, value.source)
def pushScope(self, scopeClass=FunctionScope):
self.scopeStack.append(scopeClass())
def report(self, messageClass, *args, **kwargs):
self.messages.append(messageClass(self.filename, *args, **kwargs))
def getParent(self, node):
# Lookup the first parent which is not Tuple, List or Starred
while True:
node = node.parent
if not hasattr(node, 'elts') and not hasattr(node, 'ctx'):
return node
def getCommonAncestor(self, lnode, rnode, stop):
if stop in (lnode, rnode) or not (hasattr(lnode, 'parent') and
hasattr(rnode, 'parent')):
return None
if lnode is rnode:
return lnode
if (lnode.depth > rnode.depth):
return self.getCommonAncestor(lnode.parent, rnode, stop)
if (lnode.depth < rnode.depth):
return self.getCommonAncestor(lnode, rnode.parent, stop)
return self.getCommonAncestor(lnode.parent, rnode.parent, stop)
def descendantOf(self, node, ancestors, stop):
for a in ancestors:
if self.getCommonAncestor(node, a, stop):
return True
return False
def _getAncestor(self, node, ancestor_type):
parent = node
while True:
if parent is self.root:
return None
parent = self.getParent(parent)
if isinstance(parent, ancestor_type):
return parent
def getScopeNode(self, node):
return self._getAncestor(node, tuple(Checker._ast_node_scope.keys()))
def differentForks(self, lnode, rnode):
"""True, if lnode and rnode are located on different forks of IF/TRY"""
ancestor = self.getCommonAncestor(lnode, rnode, self.root)
parts = getAlternatives(ancestor)
if parts:
for items in parts:
if self.descendantOf(lnode, items, ancestor) ^ \
self.descendantOf(rnode, items, ancestor):
return True
return False
def getNodeHandler(self, node_class):
try:
return self._nodeHandlers[node_class]
except KeyError:
nodeType = getNodeType(node_class)
self._nodeHandlers[node_class] = handler = getattr(self, nodeType)
return handler
def handleNodeLoad(self, node):
name = getNodeName(node)
if not name:
return
in_generators = None
importStarred = None
# try enclosing function scopes and global scope
for scope in self.scopeStack[-1::-1]:
if isinstance(scope, ClassScope):
if not PY2 and name == '__class__':
return
elif in_generators is False:
# only generators used in a class scope can access the
# names of the class. this is skipped during the first
# iteration
continue
if (name == 'print' and
isinstance(scope.get(name, None), Builtin)):
parent = self.getParent(node)
if (isinstance(parent, ast.BinOp) and
isinstance(parent.op, ast.RShift)):
self.report(messages.InvalidPrintSyntax, node)
try:
scope[name].used = (self.scope, node)
# if the name of SubImportation is same as
# alias of other Importation and the alias
# is used, SubImportation also should be marked as used.
n = scope[name]
if isinstance(n, Importation) and n._has_alias():
try:
scope[n.fullName].used = (self.scope, node)
except KeyError:
pass
except KeyError:
pass
else:
return
importStarred = importStarred or scope.importStarred
if in_generators is not False:
in_generators = isinstance(scope, GeneratorScope)
if importStarred:
from_list = []
for scope in self.scopeStack[-1::-1]:
for binding in scope.values():
if isinstance(binding, StarImportation):
# mark '*' imports as used for each scope
binding.used = (self.scope, node)
from_list.append(binding.fullName)
# report * usage, with a list of possible sources
from_list = ', '.join(sorted(from_list))
self.report(messages.ImportStarUsage, node, name, from_list)
return
if name == '__path__' and os.path.basename(self.filename) == '__init__.py':
# the special name __path__ is valid only in packages
return
if name == '__module__' and isinstance(self.scope, ClassScope):
return
# protected with a NameError handler?
if 'NameError' not in self.exceptHandlers[-1]:
self.report(messages.UndefinedName, node, name)
def handleNodeStore(self, node):
name = getNodeName(node)
if not name:
return
# if the name hasn't already been defined in the current scope
if isinstance(self.scope, FunctionScope) and name not in self.scope:
# for each function or module scope above us
for scope in self.scopeStack[:-1]:
if not isinstance(scope, (FunctionScope, ModuleScope)):
continue
# if the name was defined in that scope, and the name has
# been accessed already in the current scope, and hasn't
# been declared global
used = name in scope and scope[name].used
if used and used[0] is self.scope and name not in self.scope.globals:
# then it's probably a mistake
self.report(messages.UndefinedLocal,
scope[name].used[1], name, scope[name].source)
break
parent_stmt = self.getParent(node)
if isinstance(parent_stmt, (FOR_TYPES, ast.comprehension)) or (
parent_stmt != node.parent and
not self.isLiteralTupleUnpacking(parent_stmt)):
binding = Binding(name, node)
elif name == '__all__' and isinstance(self.scope, ModuleScope):
binding = ExportBinding(name, node.parent, self.scope)
elif isinstance(getattr(node, 'ctx', None), ast.Param):
binding = Argument(name, self.getScopeNode(node))
else:
binding = Assignment(name, node)
self.addBinding(node, binding)
def handleNodeDelete(self, node):
def on_conditional_branch():
"""
Return `True` if node is part of a conditional body.
"""
current = getattr(node, 'parent', None)
while current:
if isinstance(current, (ast.If, ast.While, ast.IfExp)):
return True
current = getattr(current, 'parent', None)
return False
name = getNodeName(node)
if not name:
return
if on_conditional_branch():
# We cannot predict if this conditional branch is going to
# be executed.
return
if isinstance(self.scope, FunctionScope) and name in self.scope.globals:
self.scope.globals.remove(name)
else:
try:
del self.scope[name]
except KeyError:
self.report(messages.UndefinedName, node, name)
def _handle_type_comments(self, node):
for (lineno, col_offset), comment in self._type_comments.get(node, ()):
comment = comment.split(':', 1)[1].strip()
func_match = TYPE_FUNC_RE.match(comment)
if func_match:
parts = (
func_match.group(1).replace('*', ''),
func_match.group(2).strip(),
)
else:
parts = (comment,)
for part in parts:
if PY2:
part = part.replace('...', 'Ellipsis')
self.deferFunction(functools.partial(
self.handleStringAnnotation,
part, DummyNode(lineno, col_offset), lineno, col_offset,
messages.CommentAnnotationSyntaxError,
))
def handleChildren(self, tree, omit=None):
self._handle_type_comments(tree)
for node in iter_child_nodes(tree, omit=omit):
self.handleNode(node, tree)
def isLiteralTupleUnpacking(self, node):
if isinstance(node, ast.Assign):
for child in node.targets + [node.value]:
if not hasattr(child, 'elts'):
return False
return True
def isDocstring(self, node):
"""
Determine if the given node is a docstring, as long as it is at the
correct place in the node tree.
"""
return isinstance(node, ast.Str) or (isinstance(node, ast.Expr) and
isinstance(node.value, ast.Str))
def getDocstring(self, node):
if isinstance(node, ast.Expr):
node = node.value
if not isinstance(node, ast.Str):
return (None, None)
if PYPY or PY38_PLUS:
doctest_lineno = node.lineno - 1
else:
# Computed incorrectly if the docstring has backslash
doctest_lineno = node.lineno - node.s.count('\n') - 1
return (node.s, doctest_lineno)
def handleNode(self, node, parent):
if node is None:
return
if self.offset and getattr(node, 'lineno', None) is not None:
node.lineno += self.offset[0]
node.col_offset += self.offset[1]
if self.traceTree:
print(' ' * self.nodeDepth + node.__class__.__name__)
if self.futuresAllowed and not (isinstance(node, ast.ImportFrom) or
self.isDocstring(node)):
self.futuresAllowed = False
self.nodeDepth += 1
node.depth = self.nodeDepth
node.parent = parent
try:
handler = self.getNodeHandler(node.__class__)
handler(node)
finally:
self.nodeDepth -= 1
if self.traceTree:
print(' ' * self.nodeDepth + 'end ' + node.__class__.__name__)
_getDoctestExamples = doctest.DocTestParser().get_examples
def handleDoctests(self, node):
try:
if hasattr(node, 'docstring'):
docstring = node.docstring
# This is just a reasonable guess. In Python 3.7, docstrings no
# longer have line numbers associated with them. This will be
# incorrect if there are empty lines between the beginning
# of the function and the docstring.
node_lineno = node.lineno
if hasattr(node, 'args'):
node_lineno = max([node_lineno] +
[arg.lineno for arg in node.args.args])
else:
(docstring, node_lineno) = self.getDocstring(node.body[0])
examples = docstring and self._getDoctestExamples(docstring)
except (ValueError, IndexError):
# e.g. line 6 of the docstring for <string> has inconsistent
# leading whitespace: ...
return
if not examples:
return
# Place doctest in module scope
saved_stack = self.scopeStack
self.scopeStack = [self.scopeStack[0]]
node_offset = self.offset or (0, 0)
self.pushScope(DoctestScope)
self.addBinding(None, Builtin('_'))
for example in examples:
try:
tree = ast.parse(example.source, "<doctest>")
except SyntaxError:
e = sys.exc_info()[1]
if PYPY:
e.offset += 1
position = (node_lineno + example.lineno + e.lineno,
example.indent + 4 + (e.offset or 0))
self.report(messages.DoctestSyntaxError, node, position)
else:
self.offset = (node_offset[0] + node_lineno + example.lineno,
node_offset[1] + example.indent + 4)
self.handleChildren(tree)
self.offset = node_offset
self.popScope()
self.scopeStack = saved_stack
def handleStringAnnotation(self, s, node, ref_lineno, ref_col_offset, err):
try:
tree = ast.parse(s)
except SyntaxError:
self.report(err, node, s)
return
body = tree.body
if len(body) != 1 or not isinstance(body[0], ast.Expr):
self.report(err, node, s)
return
parsed_annotation = tree.body[0].value
for descendant in ast.walk(parsed_annotation):
if (
'lineno' in descendant._attributes and
'col_offset' in descendant._attributes
):
descendant.lineno = ref_lineno
descendant.col_offset = ref_col_offset
self.handleNode(parsed_annotation, node)
def handleAnnotation(self, annotation, node):
if isinstance(annotation, ast.Str):
# Defer handling forward annotation.
self.deferFunction(functools.partial(
self.handleStringAnnotation,
annotation.s,
node,
annotation.lineno,
annotation.col_offset,
messages.ForwardAnnotationSyntaxError,
))
elif self.annotationsFutureEnabled:
self.deferFunction(lambda: self.handleNode(annotation, node))
else:
self.handleNode(annotation, node)
def ignore(self, node):
pass
# "stmt" type nodes
DELETE = PRINT = FOR = ASYNCFOR = WHILE = IF = WITH = WITHITEM = \
ASYNCWITH = ASYNCWITHITEM = TRYFINALLY = EXEC = \
EXPR = ASSIGN = handleChildren
PASS = ignore
# "expr" type nodes
BOOLOP = BINOP = UNARYOP = IFEXP = SET = \
CALL = REPR = ATTRIBUTE = SUBSCRIPT = \
STARRED = NAMECONSTANT = handleChildren
NUM = STR = BYTES = ELLIPSIS = CONSTANT = ignore
# "slice" type nodes
SLICE = EXTSLICE = INDEX = handleChildren
# expression contexts are node instances too, though being constants
LOAD = STORE = DEL = AUGLOAD = AUGSTORE = PARAM = ignore
# same for operators
AND = OR = ADD = SUB = MULT = DIV = MOD = POW = LSHIFT = RSHIFT = \
BITOR = BITXOR = BITAND = FLOORDIV = INVERT = NOT = UADD = USUB = \
EQ = NOTEQ = LT = LTE = GT = GTE = IS = ISNOT = IN = NOTIN = \
MATMULT = ignore
def RAISE(self, node):
self.handleChildren(node)
arg = get_raise_argument(node)
if isinstance(arg, ast.Call):
if is_notimplemented_name_node(arg.func):
# Handle "raise NotImplemented(...)"
self.report(messages.RaiseNotImplemented, node)
elif is_notimplemented_name_node(arg):
# Handle "raise NotImplemented"
self.report(messages.RaiseNotImplemented, node)
# additional node types
COMPREHENSION = KEYWORD = FORMATTEDVALUE = JOINEDSTR = handleChildren
def DICT(self, node):
# Complain if there are duplicate keys with different values
# If they have the same value it's not going to cause potentially
# unexpected behaviour so we'll not complain.
keys = [
convert_to_value(key) for key in node.keys
]
key_counts = counter(keys)
duplicate_keys = [
key for key, count in key_counts.items()
if count > 1
]
for key in duplicate_keys:
key_indices = [i for i, i_key in enumerate(keys) if i_key == key]
values = counter(
convert_to_value(node.values[index])
for index in key_indices
)
if any(count == 1 for value, count in values.items()):
for key_index in key_indices:
key_node = node.keys[key_index]
if isinstance(key, VariableKey):
self.report(messages.MultiValueRepeatedKeyVariable,
key_node,
key.name)
else:
self.report(
messages.MultiValueRepeatedKeyLiteral,
key_node,
key,
)
self.handleChildren(node)
def ASSERT(self, node):
if isinstance(node.test, ast.Tuple) and node.test.elts != []:
self.report(messages.AssertTuple, node)
self.handleChildren(node)
def GLOBAL(self, node):
"""
Keep track of globals declarations.
"""
global_scope_index = 1 if self._in_doctest() else 0
global_scope = self.scopeStack[global_scope_index]
# Ignore 'global' statement in global scope.
if self.scope is not global_scope:
# One 'global' statement can bind multiple (comma-delimited) names.
for node_name in node.names:
node_value = Assignment(node_name, node)
# Remove UndefinedName messages already reported for this name.
# TODO: if the global is not used in this scope, it does not
# become a globally defined name. See test_unused_global.
self.messages = [
m for m in self.messages if not
isinstance(m, messages.UndefinedName) or
m.message_args[0] != node_name]
# Bind name to global scope if it doesn't exist already.
global_scope.setdefault(node_name, node_value)
# Bind name to non-global scopes, but as already "used".
node_value.used = (global_scope, node)
for scope in self.scopeStack[global_scope_index + 1:]:
scope[node_name] = node_value
NONLOCAL = GLOBAL
def GENERATOREXP(self, node):
self.pushScope(GeneratorScope)
self.handleChildren(node)
self.popScope()
LISTCOMP = handleChildren if PY2 else GENERATOREXP
DICTCOMP = SETCOMP = GENERATOREXP
def NAME(self, node):
"""
Handle occurrence of Name (which can be a load/store/delete access.)
"""
# Locate the name in locals / function / globals scopes.
if isinstance(node.ctx, (ast.Load, ast.AugLoad)):
self.handleNodeLoad(node)
if (node.id == 'locals' and isinstance(self.scope, FunctionScope) and
isinstance(node.parent, ast.Call)):
# we are doing locals() call in current scope
self.scope.usesLocals = True
elif isinstance(node.ctx, (ast.Store, ast.AugStore, ast.Param)):
self.handleNodeStore(node)
elif isinstance(node.ctx, ast.Del):
self.handleNodeDelete(node)
else:
# Unknown context
raise RuntimeError("Got impossible expression context: %r" % (node.ctx,))
def CONTINUE(self, node):
# Walk the tree up until we see a loop (OK), a function or class
# definition (not OK), for 'continue', a finally block (not OK), or
# the top module scope (not OK)
n = node
while hasattr(n, 'parent'):
n, n_child = n.parent, n
if isinstance(n, LOOP_TYPES):
# Doesn't apply unless it's in the loop itself
if n_child not in n.orelse:
return
if isinstance(n, (ast.FunctionDef, ast.ClassDef)):
break
# Handle Try/TryFinally difference in Python < and >= 3.3
if hasattr(n, 'finalbody') and isinstance(node, ast.Continue):
if n_child in n.finalbody:
self.report(messages.ContinueInFinally, node)
return
if isinstance(node, ast.Continue):
self.report(messages.ContinueOutsideLoop, node)
else: # ast.Break
self.report(messages.BreakOutsideLoop, node)
BREAK = CONTINUE
def RETURN(self, node):
if isinstance(self.scope, (ClassScope, ModuleScope)):
self.report(messages.ReturnOutsideFunction, node)
return
if (
node.value and
hasattr(self.scope, 'returnValue') and
not self.scope.returnValue
):
self.scope.returnValue = node.value
self.handleNode(node.value, node)
def YIELD(self, node):
if isinstance(self.scope, (ClassScope, ModuleScope)):
self.report(messages.YieldOutsideFunction, node)
return
self.scope.isGenerator = True
self.handleNode(node.value, node)
AWAIT = YIELDFROM = YIELD
def FUNCTIONDEF(self, node):
for deco in node.decorator_list:
self.handleNode(deco, node)
self.LAMBDA(node)
self.addBinding(node, FunctionDefinition(node.name, node))
# doctest does not process doctest within a doctest,
# or in nested functions.
if (self.withDoctest and
not self._in_doctest() and
not isinstance(self.scope, FunctionScope)):
self.deferFunction(lambda: self.handleDoctests(node))
ASYNCFUNCTIONDEF = FUNCTIONDEF
def LAMBDA(self, node):
args = []
annotations = []
if PY2:
def addArgs(arglist):
for arg in arglist:
if isinstance(arg, ast.Tuple):
addArgs(arg.elts)
else:
args.append(arg.id)
addArgs(node.args.args)
defaults = node.args.defaults
else:
for arg in node.args.args + node.args.kwonlyargs:
args.append(arg.arg)
annotations.append(arg.annotation)
defaults = node.args.defaults + node.args.kw_defaults
# Only for Python3 FunctionDefs
is_py3_func = hasattr(node, 'returns')
for arg_name in ('vararg', 'kwarg'):
wildcard = getattr(node.args, arg_name)
if not wildcard:
continue
args.append(wildcard if PY2 else wildcard.arg)
if is_py3_func:
if PY2: # Python 2.7
argannotation = arg_name + 'annotation'
annotations.append(getattr(node.args, argannotation))
else: # Python >= 3.4
annotations.append(wildcard.annotation)
if is_py3_func:
annotations.append(node.returns)
if len(set(args)) < len(args):
for (idx, arg) in enumerate(args):
if arg in args[:idx]:
self.report(messages.DuplicateArgument, node, arg)
for annotation in annotations:
self.handleAnnotation(annotation, node)
for default in defaults:
self.handleNode(default, node)
def runFunction():
self.pushScope()
self.handleChildren(node, omit='decorator_list')
def checkUnusedAssignments():
"""
Check to see if any assignments have not been used.
"""
for name, binding in self.scope.unusedAssignments():
self.report(messages.UnusedVariable, binding.source, name)
self.deferAssignment(checkUnusedAssignments)
if PY2:
def checkReturnWithArgumentInsideGenerator():
"""
Check to see if there is any return statement with
arguments but the function is a generator.
"""
if self.scope.isGenerator and self.scope.returnValue:
self.report(messages.ReturnWithArgsInsideGenerator,
self.scope.returnValue)
self.deferAssignment(checkReturnWithArgumentInsideGenerator)
self.popScope()
self.deferFunction(runFunction)
def ARGUMENTS(self, node):
self.handleChildren(node, omit=('defaults', 'kw_defaults'))
if PY2:
scope_node = self.getScopeNode(node)
if node.vararg:
self.addBinding(node, Argument(node.vararg, scope_node))
if node.kwarg:
self.addBinding(node, Argument(node.kwarg, scope_node))
def ARG(self, node):
self.addBinding(node, Argument(node.arg, self.getScopeNode(node)))
def CLASSDEF(self, node):
"""
Check names used in a class definition, including its decorators, base
classes, and the body of its definition. Additionally, add its name to
the current scope.
"""
for deco in node.decorator_list:
self.handleNode(deco, node)
for baseNode in node.bases:
self.handleNode(baseNode, node)
if not PY2:
for keywordNode in node.keywords:
self.handleNode(keywordNode, node)
self.pushScope(ClassScope)
# doctest does not process doctest within a doctest
# classes within classes are processed.
if (self.withDoctest and
not self._in_doctest() and
not isinstance(self.scope, FunctionScope)):
self.deferFunction(lambda: self.handleDoctests(node))
for stmt in node.body:
self.handleNode(stmt, node)
self.popScope()
self.addBinding(node, ClassDefinition(node.name, node))
def AUGASSIGN(self, node):
self.handleNodeLoad(node.target)
self.handleNode(node.value, node)
self.handleNode(node.target, node)
def TUPLE(self, node):
if not PY2 and isinstance(node.ctx, ast.Store):
# Python 3 advanced tuple unpacking: a, *b, c = d.
# Only one starred expression is allowed, and no more than 1<<8
# assignments are allowed before a stared expression. There is
# also a limit of 1<<24 expressions after the starred expression,
# which is impossible to test due to memory restrictions, but we
# add it here anyway
has_starred = False
star_loc = -1
for i, n in enumerate(node.elts):
if isinstance(n, ast.Starred):
if has_starred:
self.report(messages.TwoStarredExpressions, node)
# The SyntaxError doesn't distinguish two from more
# than two.
break
has_starred = True
star_loc = i
if star_loc >= 1 << 8 or len(node.elts) - star_loc - 1 >= 1 << 24:
self.report(messages.TooManyExpressionsInStarredAssignment, node)
self.handleChildren(node)
LIST = TUPLE
def IMPORT(self, node):
for alias in node.names:
if '.' in alias.name and not alias.asname:
importation = SubmoduleImportation(alias.name, node)
else:
name = alias.asname or alias.name
importation = Importation(name, node, alias.name)
self.addBinding(node, importation)
def IMPORTFROM(self, node):
if node.module == '__future__':
if not self.futuresAllowed:
self.report(messages.LateFutureImport,
node, [n.name for n in node.names])
else:
self.futuresAllowed = False
module = ('.' * node.level) + (node.module or '')
for alias in node.names:
name = alias.asname or alias.name
if node.module == '__future__':
importation = FutureImportation(name, node, self.scope)
if alias.name not in __future__.all_feature_names:
self.report(messages.FutureFeatureNotDefined,
node, alias.name)
if alias.name == 'annotations':
self.annotationsFutureEnabled = True
elif alias.name == '*':
# Only Python 2, local import * is a SyntaxWarning
if not PY2 and not isinstance(self.scope, ModuleScope):
self.report(messages.ImportStarNotPermitted,
node, module)
continue
self.scope.importStarred = True
self.report(messages.ImportStarUsed, node, module)
importation = StarImportation(module, node)
else:
importation = ImportationFrom(name, node,
module, alias.name)
self.addBinding(node, importation)
def TRY(self, node):
handler_names = []
# List the exception handlers
for i, handler in enumerate(node.handlers):
if isinstance(handler.type, ast.Tuple):
for exc_type in handler.type.elts:
handler_names.append(getNodeName(exc_type))
elif handler.type:
handler_names.append(getNodeName(handler.type))
if handler.type is None and i < len(node.handlers) - 1:
self.report(messages.DefaultExceptNotLast, handler)
# Memorize the except handlers and process the body
self.exceptHandlers.append(handler_names)
for child in node.body:
self.handleNode(child, node)
self.exceptHandlers.pop()
# Process the other nodes: "except:", "else:", "finally:"
self.handleChildren(node, omit='body')
TRYEXCEPT = TRY
def EXCEPTHANDLER(self, node):
if PY2 or node.name is None:
self.handleChildren(node)
return
# If the name already exists in the scope, modify state of existing
# binding.
if node.name in self.scope:
self.handleNodeStore(node)
# 3.x: the name of the exception, which is not a Name node, but a
# simple string, creates a local that is only bound within the scope of
# the except: block. As such, temporarily remove the existing binding
# to more accurately determine if the name is used in the except:
# block.
try:
prev_definition = self.scope.pop(node.name)
except KeyError:
prev_definition = None
self.handleNodeStore(node)
self.handleChildren(node)
# See discussion on https://github.com/PyCQA/pyflakes/pull/59
# We're removing the local name since it's being unbound after leaving
# the except: block and it's always unbound if the except: block is
# never entered. This will cause an "undefined name" error raised if
# the checked code tries to use the name afterwards.
#
# Unless it's been removed already. Then do nothing.
try:
binding = self.scope.pop(node.name)
except KeyError:
pass
else:
if not binding.used:
self.report(messages.UnusedVariable, node, node.name)
# Restore.
if prev_definition:
self.scope[node.name] = prev_definition
def ANNASSIGN(self, node):
if node.value:
# Only bind the *targets* if the assignment has a value.
# Otherwise it's not really ast.Store and shouldn't silence
# UndefinedLocal warnings.
self.handleNode(node.target, node)
self.handleAnnotation(node.annotation, node)
if node.value:
# If the assignment has value, handle the *value* now.
self.handleNode(node.value, node)
def COMPARE(self, node):
literals = (ast.Str, ast.Num)
if not PY2:
literals += (ast.Bytes,)
left = node.left
for op, right in zip(node.ops, node.comparators):
if (isinstance(op, (ast.Is, ast.IsNot)) and
(isinstance(left, literals) or isinstance(right, literals))):
self.report(messages.IsLiteral, node)
left = right
self.handleChildren(node)
|
PyCQA/pyflakes | pyflakes/checker.py | Checker.isDocstring | python | def isDocstring(self, node):
return isinstance(node, ast.Str) or (isinstance(node, ast.Expr) and
isinstance(node.value, ast.Str)) | Determine if the given node is a docstring, as long as it is at the
correct place in the node tree. | train | https://github.com/PyCQA/pyflakes/blob/232cb1d27ee134bf96adc8f37e53589dc259b159/pyflakes/checker.py#L1091-L1097 | null | class Checker(object):
"""
I check the cleanliness and sanity of Python code.
@ivar _deferredFunctions: Tracking list used by L{deferFunction}. Elements
of the list are two-tuples. The first element is the callable passed
to L{deferFunction}. The second element is a copy of the scope stack
at the time L{deferFunction} was called.
@ivar _deferredAssignments: Similar to C{_deferredFunctions}, but for
callables which are deferred assignment checks.
"""
_ast_node_scope = {
ast.Module: ModuleScope,
ast.ClassDef: ClassScope,
ast.FunctionDef: FunctionScope,
ast.Lambda: FunctionScope,
ast.ListComp: GeneratorScope,
ast.SetComp: GeneratorScope,
ast.GeneratorExp: GeneratorScope,
ast.DictComp: GeneratorScope,
}
if PY35_PLUS:
_ast_node_scope[ast.AsyncFunctionDef] = FunctionScope,
nodeDepth = 0
offset = None
traceTree = False
builtIns = set(builtin_vars).union(_MAGIC_GLOBALS)
_customBuiltIns = os.environ.get('PYFLAKES_BUILTINS')
if _customBuiltIns:
builtIns.update(_customBuiltIns.split(','))
del _customBuiltIns
# TODO: file_tokens= is required to perform checks on type comments,
# eventually make this a required positional argument. For now it
# is defaulted to `()` for api compatibility.
def __init__(self, tree, filename='(none)', builtins=None,
withDoctest='PYFLAKES_DOCTEST' in os.environ, file_tokens=()):
self._nodeHandlers = {}
self._deferredFunctions = []
self._deferredAssignments = []
self.deadScopes = []
self.messages = []
self.filename = filename
if builtins:
self.builtIns = self.builtIns.union(builtins)
self.withDoctest = withDoctest
try:
self.scopeStack = [Checker._ast_node_scope[type(tree)]()]
except KeyError:
raise RuntimeError('No scope implemented for the node %r' % tree)
self.exceptHandlers = [()]
self.root = tree
self._type_comments = _collect_type_comments(tree, file_tokens)
for builtin in self.builtIns:
self.addBinding(None, Builtin(builtin))
self.handleChildren(tree)
self.runDeferred(self._deferredFunctions)
# Set _deferredFunctions to None so that deferFunction will fail
# noisily if called after we've run through the deferred functions.
self._deferredFunctions = None
self.runDeferred(self._deferredAssignments)
# Set _deferredAssignments to None so that deferAssignment will fail
# noisily if called after we've run through the deferred assignments.
self._deferredAssignments = None
del self.scopeStack[1:]
self.popScope()
self.checkDeadScopes()
def deferFunction(self, callable):
"""
Schedule a function handler to be called just before completion.
This is used for handling function bodies, which must be deferred
because code later in the file might modify the global scope. When
`callable` is called, the scope at the time this is called will be
restored, however it will contain any new bindings added to it.
"""
self._deferredFunctions.append((callable, self.scopeStack[:], self.offset))
def deferAssignment(self, callable):
"""
Schedule an assignment handler to be called just after deferred
function handlers.
"""
self._deferredAssignments.append((callable, self.scopeStack[:], self.offset))
def runDeferred(self, deferred):
"""
Run the callables in C{deferred} using their associated scope stack.
"""
for handler, scope, offset in deferred:
self.scopeStack = scope
self.offset = offset
handler()
def _in_doctest(self):
return (len(self.scopeStack) >= 2 and
isinstance(self.scopeStack[1], DoctestScope))
@property
def futuresAllowed(self):
if not all(isinstance(scope, ModuleScope)
for scope in self.scopeStack):
return False
return self.scope._futures_allowed
@futuresAllowed.setter
def futuresAllowed(self, value):
assert value is False
if isinstance(self.scope, ModuleScope):
self.scope._futures_allowed = False
@property
def annotationsFutureEnabled(self):
scope = self.scopeStack[0]
if not isinstance(scope, ModuleScope):
return False
return scope._annotations_future_enabled
@annotationsFutureEnabled.setter
def annotationsFutureEnabled(self, value):
assert value is True
assert isinstance(self.scope, ModuleScope)
self.scope._annotations_future_enabled = True
@property
def scope(self):
return self.scopeStack[-1]
def popScope(self):
self.deadScopes.append(self.scopeStack.pop())
def checkDeadScopes(self):
"""
Look at scopes which have been fully examined and report names in them
which were imported but unused.
"""
for scope in self.deadScopes:
# imports in classes are public members
if isinstance(scope, ClassScope):
continue
all_binding = scope.get('__all__')
if all_binding and not isinstance(all_binding, ExportBinding):
all_binding = None
if all_binding:
all_names = set(all_binding.names)
undefined = all_names.difference(scope)
else:
all_names = undefined = []
if undefined:
if not scope.importStarred and \
os.path.basename(self.filename) != '__init__.py':
# Look for possible mistakes in the export list
for name in undefined:
self.report(messages.UndefinedExport,
scope['__all__'].source, name)
# mark all import '*' as used by the undefined in __all__
if scope.importStarred:
from_list = []
for binding in scope.values():
if isinstance(binding, StarImportation):
binding.used = all_binding
from_list.append(binding.fullName)
# report * usage, with a list of possible sources
from_list = ', '.join(sorted(from_list))
for name in undefined:
self.report(messages.ImportStarUsage,
scope['__all__'].source, name, from_list)
# Look for imported names that aren't used.
for value in scope.values():
if isinstance(value, Importation):
used = value.used or value.name in all_names
if not used:
messg = messages.UnusedImport
self.report(messg, value.source, str(value))
for node in value.redefined:
if isinstance(self.getParent(node), FOR_TYPES):
messg = messages.ImportShadowedByLoopVar
elif used:
continue
else:
messg = messages.RedefinedWhileUnused
self.report(messg, node, value.name, value.source)
def pushScope(self, scopeClass=FunctionScope):
self.scopeStack.append(scopeClass())
def report(self, messageClass, *args, **kwargs):
self.messages.append(messageClass(self.filename, *args, **kwargs))
def getParent(self, node):
# Lookup the first parent which is not Tuple, List or Starred
while True:
node = node.parent
if not hasattr(node, 'elts') and not hasattr(node, 'ctx'):
return node
def getCommonAncestor(self, lnode, rnode, stop):
if stop in (lnode, rnode) or not (hasattr(lnode, 'parent') and
hasattr(rnode, 'parent')):
return None
if lnode is rnode:
return lnode
if (lnode.depth > rnode.depth):
return self.getCommonAncestor(lnode.parent, rnode, stop)
if (lnode.depth < rnode.depth):
return self.getCommonAncestor(lnode, rnode.parent, stop)
return self.getCommonAncestor(lnode.parent, rnode.parent, stop)
def descendantOf(self, node, ancestors, stop):
for a in ancestors:
if self.getCommonAncestor(node, a, stop):
return True
return False
def _getAncestor(self, node, ancestor_type):
parent = node
while True:
if parent is self.root:
return None
parent = self.getParent(parent)
if isinstance(parent, ancestor_type):
return parent
def getScopeNode(self, node):
return self._getAncestor(node, tuple(Checker._ast_node_scope.keys()))
def differentForks(self, lnode, rnode):
"""True, if lnode and rnode are located on different forks of IF/TRY"""
ancestor = self.getCommonAncestor(lnode, rnode, self.root)
parts = getAlternatives(ancestor)
if parts:
for items in parts:
if self.descendantOf(lnode, items, ancestor) ^ \
self.descendantOf(rnode, items, ancestor):
return True
return False
def addBinding(self, node, value):
"""
Called when a binding is altered.
- `node` is the statement responsible for the change
- `value` is the new value, a Binding instance
"""
# assert value.source in (node, node.parent):
for scope in self.scopeStack[::-1]:
if value.name in scope:
break
existing = scope.get(value.name)
if (existing and not isinstance(existing, Builtin) and
not self.differentForks(node, existing.source)):
parent_stmt = self.getParent(value.source)
if isinstance(existing, Importation) and isinstance(parent_stmt, FOR_TYPES):
self.report(messages.ImportShadowedByLoopVar,
node, value.name, existing.source)
elif scope is self.scope:
if (isinstance(parent_stmt, ast.comprehension) and
not isinstance(self.getParent(existing.source),
(FOR_TYPES, ast.comprehension))):
self.report(messages.RedefinedInListComp,
node, value.name, existing.source)
elif not existing.used and value.redefines(existing):
if value.name != '_' or isinstance(existing, Importation):
if not is_typing_overload(existing, self.scopeStack):
self.report(messages.RedefinedWhileUnused,
node, value.name, existing.source)
elif isinstance(existing, Importation) and value.redefines(existing):
existing.redefined.append(node)
if value.name in self.scope:
# then assume the rebound name is used as a global or within a loop
value.used = self.scope[value.name].used
self.scope[value.name] = value
def getNodeHandler(self, node_class):
try:
return self._nodeHandlers[node_class]
except KeyError:
nodeType = getNodeType(node_class)
self._nodeHandlers[node_class] = handler = getattr(self, nodeType)
return handler
def handleNodeLoad(self, node):
name = getNodeName(node)
if not name:
return
in_generators = None
importStarred = None
# try enclosing function scopes and global scope
for scope in self.scopeStack[-1::-1]:
if isinstance(scope, ClassScope):
if not PY2 and name == '__class__':
return
elif in_generators is False:
# only generators used in a class scope can access the
# names of the class. this is skipped during the first
# iteration
continue
if (name == 'print' and
isinstance(scope.get(name, None), Builtin)):
parent = self.getParent(node)
if (isinstance(parent, ast.BinOp) and
isinstance(parent.op, ast.RShift)):
self.report(messages.InvalidPrintSyntax, node)
try:
scope[name].used = (self.scope, node)
# if the name of SubImportation is same as
# alias of other Importation and the alias
# is used, SubImportation also should be marked as used.
n = scope[name]
if isinstance(n, Importation) and n._has_alias():
try:
scope[n.fullName].used = (self.scope, node)
except KeyError:
pass
except KeyError:
pass
else:
return
importStarred = importStarred or scope.importStarred
if in_generators is not False:
in_generators = isinstance(scope, GeneratorScope)
if importStarred:
from_list = []
for scope in self.scopeStack[-1::-1]:
for binding in scope.values():
if isinstance(binding, StarImportation):
# mark '*' imports as used for each scope
binding.used = (self.scope, node)
from_list.append(binding.fullName)
# report * usage, with a list of possible sources
from_list = ', '.join(sorted(from_list))
self.report(messages.ImportStarUsage, node, name, from_list)
return
if name == '__path__' and os.path.basename(self.filename) == '__init__.py':
# the special name __path__ is valid only in packages
return
if name == '__module__' and isinstance(self.scope, ClassScope):
return
# protected with a NameError handler?
if 'NameError' not in self.exceptHandlers[-1]:
self.report(messages.UndefinedName, node, name)
def handleNodeStore(self, node):
name = getNodeName(node)
if not name:
return
# if the name hasn't already been defined in the current scope
if isinstance(self.scope, FunctionScope) and name not in self.scope:
# for each function or module scope above us
for scope in self.scopeStack[:-1]:
if not isinstance(scope, (FunctionScope, ModuleScope)):
continue
# if the name was defined in that scope, and the name has
# been accessed already in the current scope, and hasn't
# been declared global
used = name in scope and scope[name].used
if used and used[0] is self.scope and name not in self.scope.globals:
# then it's probably a mistake
self.report(messages.UndefinedLocal,
scope[name].used[1], name, scope[name].source)
break
parent_stmt = self.getParent(node)
if isinstance(parent_stmt, (FOR_TYPES, ast.comprehension)) or (
parent_stmt != node.parent and
not self.isLiteralTupleUnpacking(parent_stmt)):
binding = Binding(name, node)
elif name == '__all__' and isinstance(self.scope, ModuleScope):
binding = ExportBinding(name, node.parent, self.scope)
elif isinstance(getattr(node, 'ctx', None), ast.Param):
binding = Argument(name, self.getScopeNode(node))
else:
binding = Assignment(name, node)
self.addBinding(node, binding)
def handleNodeDelete(self, node):
def on_conditional_branch():
"""
Return `True` if node is part of a conditional body.
"""
current = getattr(node, 'parent', None)
while current:
if isinstance(current, (ast.If, ast.While, ast.IfExp)):
return True
current = getattr(current, 'parent', None)
return False
name = getNodeName(node)
if not name:
return
if on_conditional_branch():
# We cannot predict if this conditional branch is going to
# be executed.
return
if isinstance(self.scope, FunctionScope) and name in self.scope.globals:
self.scope.globals.remove(name)
else:
try:
del self.scope[name]
except KeyError:
self.report(messages.UndefinedName, node, name)
def _handle_type_comments(self, node):
for (lineno, col_offset), comment in self._type_comments.get(node, ()):
comment = comment.split(':', 1)[1].strip()
func_match = TYPE_FUNC_RE.match(comment)
if func_match:
parts = (
func_match.group(1).replace('*', ''),
func_match.group(2).strip(),
)
else:
parts = (comment,)
for part in parts:
if PY2:
part = part.replace('...', 'Ellipsis')
self.deferFunction(functools.partial(
self.handleStringAnnotation,
part, DummyNode(lineno, col_offset), lineno, col_offset,
messages.CommentAnnotationSyntaxError,
))
def handleChildren(self, tree, omit=None):
self._handle_type_comments(tree)
for node in iter_child_nodes(tree, omit=omit):
self.handleNode(node, tree)
def isLiteralTupleUnpacking(self, node):
if isinstance(node, ast.Assign):
for child in node.targets + [node.value]:
if not hasattr(child, 'elts'):
return False
return True
def getDocstring(self, node):
if isinstance(node, ast.Expr):
node = node.value
if not isinstance(node, ast.Str):
return (None, None)
if PYPY or PY38_PLUS:
doctest_lineno = node.lineno - 1
else:
# Computed incorrectly if the docstring has backslash
doctest_lineno = node.lineno - node.s.count('\n') - 1
return (node.s, doctest_lineno)
def handleNode(self, node, parent):
if node is None:
return
if self.offset and getattr(node, 'lineno', None) is not None:
node.lineno += self.offset[0]
node.col_offset += self.offset[1]
if self.traceTree:
print(' ' * self.nodeDepth + node.__class__.__name__)
if self.futuresAllowed and not (isinstance(node, ast.ImportFrom) or
self.isDocstring(node)):
self.futuresAllowed = False
self.nodeDepth += 1
node.depth = self.nodeDepth
node.parent = parent
try:
handler = self.getNodeHandler(node.__class__)
handler(node)
finally:
self.nodeDepth -= 1
if self.traceTree:
print(' ' * self.nodeDepth + 'end ' + node.__class__.__name__)
_getDoctestExamples = doctest.DocTestParser().get_examples
def handleDoctests(self, node):
try:
if hasattr(node, 'docstring'):
docstring = node.docstring
# This is just a reasonable guess. In Python 3.7, docstrings no
# longer have line numbers associated with them. This will be
# incorrect if there are empty lines between the beginning
# of the function and the docstring.
node_lineno = node.lineno
if hasattr(node, 'args'):
node_lineno = max([node_lineno] +
[arg.lineno for arg in node.args.args])
else:
(docstring, node_lineno) = self.getDocstring(node.body[0])
examples = docstring and self._getDoctestExamples(docstring)
except (ValueError, IndexError):
# e.g. line 6 of the docstring for <string> has inconsistent
# leading whitespace: ...
return
if not examples:
return
# Place doctest in module scope
saved_stack = self.scopeStack
self.scopeStack = [self.scopeStack[0]]
node_offset = self.offset or (0, 0)
self.pushScope(DoctestScope)
self.addBinding(None, Builtin('_'))
for example in examples:
try:
tree = ast.parse(example.source, "<doctest>")
except SyntaxError:
e = sys.exc_info()[1]
if PYPY:
e.offset += 1
position = (node_lineno + example.lineno + e.lineno,
example.indent + 4 + (e.offset or 0))
self.report(messages.DoctestSyntaxError, node, position)
else:
self.offset = (node_offset[0] + node_lineno + example.lineno,
node_offset[1] + example.indent + 4)
self.handleChildren(tree)
self.offset = node_offset
self.popScope()
self.scopeStack = saved_stack
def handleStringAnnotation(self, s, node, ref_lineno, ref_col_offset, err):
try:
tree = ast.parse(s)
except SyntaxError:
self.report(err, node, s)
return
body = tree.body
if len(body) != 1 or not isinstance(body[0], ast.Expr):
self.report(err, node, s)
return
parsed_annotation = tree.body[0].value
for descendant in ast.walk(parsed_annotation):
if (
'lineno' in descendant._attributes and
'col_offset' in descendant._attributes
):
descendant.lineno = ref_lineno
descendant.col_offset = ref_col_offset
self.handleNode(parsed_annotation, node)
def handleAnnotation(self, annotation, node):
if isinstance(annotation, ast.Str):
# Defer handling forward annotation.
self.deferFunction(functools.partial(
self.handleStringAnnotation,
annotation.s,
node,
annotation.lineno,
annotation.col_offset,
messages.ForwardAnnotationSyntaxError,
))
elif self.annotationsFutureEnabled:
self.deferFunction(lambda: self.handleNode(annotation, node))
else:
self.handleNode(annotation, node)
def ignore(self, node):
pass
# "stmt" type nodes
DELETE = PRINT = FOR = ASYNCFOR = WHILE = IF = WITH = WITHITEM = \
ASYNCWITH = ASYNCWITHITEM = TRYFINALLY = EXEC = \
EXPR = ASSIGN = handleChildren
PASS = ignore
# "expr" type nodes
BOOLOP = BINOP = UNARYOP = IFEXP = SET = \
CALL = REPR = ATTRIBUTE = SUBSCRIPT = \
STARRED = NAMECONSTANT = handleChildren
NUM = STR = BYTES = ELLIPSIS = CONSTANT = ignore
# "slice" type nodes
SLICE = EXTSLICE = INDEX = handleChildren
# expression contexts are node instances too, though being constants
LOAD = STORE = DEL = AUGLOAD = AUGSTORE = PARAM = ignore
# same for operators
AND = OR = ADD = SUB = MULT = DIV = MOD = POW = LSHIFT = RSHIFT = \
BITOR = BITXOR = BITAND = FLOORDIV = INVERT = NOT = UADD = USUB = \
EQ = NOTEQ = LT = LTE = GT = GTE = IS = ISNOT = IN = NOTIN = \
MATMULT = ignore
def RAISE(self, node):
self.handleChildren(node)
arg = get_raise_argument(node)
if isinstance(arg, ast.Call):
if is_notimplemented_name_node(arg.func):
# Handle "raise NotImplemented(...)"
self.report(messages.RaiseNotImplemented, node)
elif is_notimplemented_name_node(arg):
# Handle "raise NotImplemented"
self.report(messages.RaiseNotImplemented, node)
# additional node types
COMPREHENSION = KEYWORD = FORMATTEDVALUE = JOINEDSTR = handleChildren
def DICT(self, node):
# Complain if there are duplicate keys with different values
# If they have the same value it's not going to cause potentially
# unexpected behaviour so we'll not complain.
keys = [
convert_to_value(key) for key in node.keys
]
key_counts = counter(keys)
duplicate_keys = [
key for key, count in key_counts.items()
if count > 1
]
for key in duplicate_keys:
key_indices = [i for i, i_key in enumerate(keys) if i_key == key]
values = counter(
convert_to_value(node.values[index])
for index in key_indices
)
if any(count == 1 for value, count in values.items()):
for key_index in key_indices:
key_node = node.keys[key_index]
if isinstance(key, VariableKey):
self.report(messages.MultiValueRepeatedKeyVariable,
key_node,
key.name)
else:
self.report(
messages.MultiValueRepeatedKeyLiteral,
key_node,
key,
)
self.handleChildren(node)
def ASSERT(self, node):
if isinstance(node.test, ast.Tuple) and node.test.elts != []:
self.report(messages.AssertTuple, node)
self.handleChildren(node)
def GLOBAL(self, node):
"""
Keep track of globals declarations.
"""
global_scope_index = 1 if self._in_doctest() else 0
global_scope = self.scopeStack[global_scope_index]
# Ignore 'global' statement in global scope.
if self.scope is not global_scope:
# One 'global' statement can bind multiple (comma-delimited) names.
for node_name in node.names:
node_value = Assignment(node_name, node)
# Remove UndefinedName messages already reported for this name.
# TODO: if the global is not used in this scope, it does not
# become a globally defined name. See test_unused_global.
self.messages = [
m for m in self.messages if not
isinstance(m, messages.UndefinedName) or
m.message_args[0] != node_name]
# Bind name to global scope if it doesn't exist already.
global_scope.setdefault(node_name, node_value)
# Bind name to non-global scopes, but as already "used".
node_value.used = (global_scope, node)
for scope in self.scopeStack[global_scope_index + 1:]:
scope[node_name] = node_value
NONLOCAL = GLOBAL
def GENERATOREXP(self, node):
self.pushScope(GeneratorScope)
self.handleChildren(node)
self.popScope()
LISTCOMP = handleChildren if PY2 else GENERATOREXP
DICTCOMP = SETCOMP = GENERATOREXP
def NAME(self, node):
"""
Handle occurrence of Name (which can be a load/store/delete access.)
"""
# Locate the name in locals / function / globals scopes.
if isinstance(node.ctx, (ast.Load, ast.AugLoad)):
self.handleNodeLoad(node)
if (node.id == 'locals' and isinstance(self.scope, FunctionScope) and
isinstance(node.parent, ast.Call)):
# we are doing locals() call in current scope
self.scope.usesLocals = True
elif isinstance(node.ctx, (ast.Store, ast.AugStore, ast.Param)):
self.handleNodeStore(node)
elif isinstance(node.ctx, ast.Del):
self.handleNodeDelete(node)
else:
# Unknown context
raise RuntimeError("Got impossible expression context: %r" % (node.ctx,))
def CONTINUE(self, node):
# Walk the tree up until we see a loop (OK), a function or class
# definition (not OK), for 'continue', a finally block (not OK), or
# the top module scope (not OK)
n = node
while hasattr(n, 'parent'):
n, n_child = n.parent, n
if isinstance(n, LOOP_TYPES):
# Doesn't apply unless it's in the loop itself
if n_child not in n.orelse:
return
if isinstance(n, (ast.FunctionDef, ast.ClassDef)):
break
# Handle Try/TryFinally difference in Python < and >= 3.3
if hasattr(n, 'finalbody') and isinstance(node, ast.Continue):
if n_child in n.finalbody:
self.report(messages.ContinueInFinally, node)
return
if isinstance(node, ast.Continue):
self.report(messages.ContinueOutsideLoop, node)
else: # ast.Break
self.report(messages.BreakOutsideLoop, node)
BREAK = CONTINUE
def RETURN(self, node):
if isinstance(self.scope, (ClassScope, ModuleScope)):
self.report(messages.ReturnOutsideFunction, node)
return
if (
node.value and
hasattr(self.scope, 'returnValue') and
not self.scope.returnValue
):
self.scope.returnValue = node.value
self.handleNode(node.value, node)
def YIELD(self, node):
if isinstance(self.scope, (ClassScope, ModuleScope)):
self.report(messages.YieldOutsideFunction, node)
return
self.scope.isGenerator = True
self.handleNode(node.value, node)
AWAIT = YIELDFROM = YIELD
def FUNCTIONDEF(self, node):
for deco in node.decorator_list:
self.handleNode(deco, node)
self.LAMBDA(node)
self.addBinding(node, FunctionDefinition(node.name, node))
# doctest does not process doctest within a doctest,
# or in nested functions.
if (self.withDoctest and
not self._in_doctest() and
not isinstance(self.scope, FunctionScope)):
self.deferFunction(lambda: self.handleDoctests(node))
ASYNCFUNCTIONDEF = FUNCTIONDEF
def LAMBDA(self, node):
args = []
annotations = []
if PY2:
def addArgs(arglist):
for arg in arglist:
if isinstance(arg, ast.Tuple):
addArgs(arg.elts)
else:
args.append(arg.id)
addArgs(node.args.args)
defaults = node.args.defaults
else:
for arg in node.args.args + node.args.kwonlyargs:
args.append(arg.arg)
annotations.append(arg.annotation)
defaults = node.args.defaults + node.args.kw_defaults
# Only for Python3 FunctionDefs
is_py3_func = hasattr(node, 'returns')
for arg_name in ('vararg', 'kwarg'):
wildcard = getattr(node.args, arg_name)
if not wildcard:
continue
args.append(wildcard if PY2 else wildcard.arg)
if is_py3_func:
if PY2: # Python 2.7
argannotation = arg_name + 'annotation'
annotations.append(getattr(node.args, argannotation))
else: # Python >= 3.4
annotations.append(wildcard.annotation)
if is_py3_func:
annotations.append(node.returns)
if len(set(args)) < len(args):
for (idx, arg) in enumerate(args):
if arg in args[:idx]:
self.report(messages.DuplicateArgument, node, arg)
for annotation in annotations:
self.handleAnnotation(annotation, node)
for default in defaults:
self.handleNode(default, node)
def runFunction():
self.pushScope()
self.handleChildren(node, omit='decorator_list')
def checkUnusedAssignments():
"""
Check to see if any assignments have not been used.
"""
for name, binding in self.scope.unusedAssignments():
self.report(messages.UnusedVariable, binding.source, name)
self.deferAssignment(checkUnusedAssignments)
if PY2:
def checkReturnWithArgumentInsideGenerator():
"""
Check to see if there is any return statement with
arguments but the function is a generator.
"""
if self.scope.isGenerator and self.scope.returnValue:
self.report(messages.ReturnWithArgsInsideGenerator,
self.scope.returnValue)
self.deferAssignment(checkReturnWithArgumentInsideGenerator)
self.popScope()
self.deferFunction(runFunction)
def ARGUMENTS(self, node):
self.handleChildren(node, omit=('defaults', 'kw_defaults'))
if PY2:
scope_node = self.getScopeNode(node)
if node.vararg:
self.addBinding(node, Argument(node.vararg, scope_node))
if node.kwarg:
self.addBinding(node, Argument(node.kwarg, scope_node))
def ARG(self, node):
self.addBinding(node, Argument(node.arg, self.getScopeNode(node)))
def CLASSDEF(self, node):
"""
Check names used in a class definition, including its decorators, base
classes, and the body of its definition. Additionally, add its name to
the current scope.
"""
for deco in node.decorator_list:
self.handleNode(deco, node)
for baseNode in node.bases:
self.handleNode(baseNode, node)
if not PY2:
for keywordNode in node.keywords:
self.handleNode(keywordNode, node)
self.pushScope(ClassScope)
# doctest does not process doctest within a doctest
# classes within classes are processed.
if (self.withDoctest and
not self._in_doctest() and
not isinstance(self.scope, FunctionScope)):
self.deferFunction(lambda: self.handleDoctests(node))
for stmt in node.body:
self.handleNode(stmt, node)
self.popScope()
self.addBinding(node, ClassDefinition(node.name, node))
def AUGASSIGN(self, node):
self.handleNodeLoad(node.target)
self.handleNode(node.value, node)
self.handleNode(node.target, node)
def TUPLE(self, node):
if not PY2 and isinstance(node.ctx, ast.Store):
# Python 3 advanced tuple unpacking: a, *b, c = d.
# Only one starred expression is allowed, and no more than 1<<8
# assignments are allowed before a stared expression. There is
# also a limit of 1<<24 expressions after the starred expression,
# which is impossible to test due to memory restrictions, but we
# add it here anyway
has_starred = False
star_loc = -1
for i, n in enumerate(node.elts):
if isinstance(n, ast.Starred):
if has_starred:
self.report(messages.TwoStarredExpressions, node)
# The SyntaxError doesn't distinguish two from more
# than two.
break
has_starred = True
star_loc = i
if star_loc >= 1 << 8 or len(node.elts) - star_loc - 1 >= 1 << 24:
self.report(messages.TooManyExpressionsInStarredAssignment, node)
self.handleChildren(node)
LIST = TUPLE
def IMPORT(self, node):
for alias in node.names:
if '.' in alias.name and not alias.asname:
importation = SubmoduleImportation(alias.name, node)
else:
name = alias.asname or alias.name
importation = Importation(name, node, alias.name)
self.addBinding(node, importation)
def IMPORTFROM(self, node):
if node.module == '__future__':
if not self.futuresAllowed:
self.report(messages.LateFutureImport,
node, [n.name for n in node.names])
else:
self.futuresAllowed = False
module = ('.' * node.level) + (node.module or '')
for alias in node.names:
name = alias.asname or alias.name
if node.module == '__future__':
importation = FutureImportation(name, node, self.scope)
if alias.name not in __future__.all_feature_names:
self.report(messages.FutureFeatureNotDefined,
node, alias.name)
if alias.name == 'annotations':
self.annotationsFutureEnabled = True
elif alias.name == '*':
# Only Python 2, local import * is a SyntaxWarning
if not PY2 and not isinstance(self.scope, ModuleScope):
self.report(messages.ImportStarNotPermitted,
node, module)
continue
self.scope.importStarred = True
self.report(messages.ImportStarUsed, node, module)
importation = StarImportation(module, node)
else:
importation = ImportationFrom(name, node,
module, alias.name)
self.addBinding(node, importation)
def TRY(self, node):
handler_names = []
# List the exception handlers
for i, handler in enumerate(node.handlers):
if isinstance(handler.type, ast.Tuple):
for exc_type in handler.type.elts:
handler_names.append(getNodeName(exc_type))
elif handler.type:
handler_names.append(getNodeName(handler.type))
if handler.type is None and i < len(node.handlers) - 1:
self.report(messages.DefaultExceptNotLast, handler)
# Memorize the except handlers and process the body
self.exceptHandlers.append(handler_names)
for child in node.body:
self.handleNode(child, node)
self.exceptHandlers.pop()
# Process the other nodes: "except:", "else:", "finally:"
self.handleChildren(node, omit='body')
TRYEXCEPT = TRY
def EXCEPTHANDLER(self, node):
if PY2 or node.name is None:
self.handleChildren(node)
return
# If the name already exists in the scope, modify state of existing
# binding.
if node.name in self.scope:
self.handleNodeStore(node)
# 3.x: the name of the exception, which is not a Name node, but a
# simple string, creates a local that is only bound within the scope of
# the except: block. As such, temporarily remove the existing binding
# to more accurately determine if the name is used in the except:
# block.
try:
prev_definition = self.scope.pop(node.name)
except KeyError:
prev_definition = None
self.handleNodeStore(node)
self.handleChildren(node)
# See discussion on https://github.com/PyCQA/pyflakes/pull/59
# We're removing the local name since it's being unbound after leaving
# the except: block and it's always unbound if the except: block is
# never entered. This will cause an "undefined name" error raised if
# the checked code tries to use the name afterwards.
#
# Unless it's been removed already. Then do nothing.
try:
binding = self.scope.pop(node.name)
except KeyError:
pass
else:
if not binding.used:
self.report(messages.UnusedVariable, node, node.name)
# Restore.
if prev_definition:
self.scope[node.name] = prev_definition
def ANNASSIGN(self, node):
if node.value:
# Only bind the *targets* if the assignment has a value.
# Otherwise it's not really ast.Store and shouldn't silence
# UndefinedLocal warnings.
self.handleNode(node.target, node)
self.handleAnnotation(node.annotation, node)
if node.value:
# If the assignment has value, handle the *value* now.
self.handleNode(node.value, node)
def COMPARE(self, node):
literals = (ast.Str, ast.Num)
if not PY2:
literals += (ast.Bytes,)
left = node.left
for op, right in zip(node.ops, node.comparators):
if (isinstance(op, (ast.Is, ast.IsNot)) and
(isinstance(left, literals) or isinstance(right, literals))):
self.report(messages.IsLiteral, node)
left = right
self.handleChildren(node)
|
PyCQA/pyflakes | pyflakes/checker.py | Checker.GLOBAL | python | def GLOBAL(self, node):
global_scope_index = 1 if self._in_doctest() else 0
global_scope = self.scopeStack[global_scope_index]
# Ignore 'global' statement in global scope.
if self.scope is not global_scope:
# One 'global' statement can bind multiple (comma-delimited) names.
for node_name in node.names:
node_value = Assignment(node_name, node)
# Remove UndefinedName messages already reported for this name.
# TODO: if the global is not used in this scope, it does not
# become a globally defined name. See test_unused_global.
self.messages = [
m for m in self.messages if not
isinstance(m, messages.UndefinedName) or
m.message_args[0] != node_name]
# Bind name to global scope if it doesn't exist already.
global_scope.setdefault(node_name, node_value)
# Bind name to non-global scopes, but as already "used".
node_value.used = (global_scope, node)
for scope in self.scopeStack[global_scope_index + 1:]:
scope[node_name] = node_value | Keep track of globals declarations. | train | https://github.com/PyCQA/pyflakes/blob/232cb1d27ee134bf96adc8f37e53589dc259b159/pyflakes/checker.py#L1309-L1337 | [
"def _in_doctest(self):\n return (len(self.scopeStack) >= 2 and\n isinstance(self.scopeStack[1], DoctestScope))\n"
] | class Checker(object):
"""
I check the cleanliness and sanity of Python code.
@ivar _deferredFunctions: Tracking list used by L{deferFunction}. Elements
of the list are two-tuples. The first element is the callable passed
to L{deferFunction}. The second element is a copy of the scope stack
at the time L{deferFunction} was called.
@ivar _deferredAssignments: Similar to C{_deferredFunctions}, but for
callables which are deferred assignment checks.
"""
_ast_node_scope = {
ast.Module: ModuleScope,
ast.ClassDef: ClassScope,
ast.FunctionDef: FunctionScope,
ast.Lambda: FunctionScope,
ast.ListComp: GeneratorScope,
ast.SetComp: GeneratorScope,
ast.GeneratorExp: GeneratorScope,
ast.DictComp: GeneratorScope,
}
if PY35_PLUS:
_ast_node_scope[ast.AsyncFunctionDef] = FunctionScope,
nodeDepth = 0
offset = None
traceTree = False
builtIns = set(builtin_vars).union(_MAGIC_GLOBALS)
_customBuiltIns = os.environ.get('PYFLAKES_BUILTINS')
if _customBuiltIns:
builtIns.update(_customBuiltIns.split(','))
del _customBuiltIns
# TODO: file_tokens= is required to perform checks on type comments,
# eventually make this a required positional argument. For now it
# is defaulted to `()` for api compatibility.
def __init__(self, tree, filename='(none)', builtins=None,
withDoctest='PYFLAKES_DOCTEST' in os.environ, file_tokens=()):
self._nodeHandlers = {}
self._deferredFunctions = []
self._deferredAssignments = []
self.deadScopes = []
self.messages = []
self.filename = filename
if builtins:
self.builtIns = self.builtIns.union(builtins)
self.withDoctest = withDoctest
try:
self.scopeStack = [Checker._ast_node_scope[type(tree)]()]
except KeyError:
raise RuntimeError('No scope implemented for the node %r' % tree)
self.exceptHandlers = [()]
self.root = tree
self._type_comments = _collect_type_comments(tree, file_tokens)
for builtin in self.builtIns:
self.addBinding(None, Builtin(builtin))
self.handleChildren(tree)
self.runDeferred(self._deferredFunctions)
# Set _deferredFunctions to None so that deferFunction will fail
# noisily if called after we've run through the deferred functions.
self._deferredFunctions = None
self.runDeferred(self._deferredAssignments)
# Set _deferredAssignments to None so that deferAssignment will fail
# noisily if called after we've run through the deferred assignments.
self._deferredAssignments = None
del self.scopeStack[1:]
self.popScope()
self.checkDeadScopes()
def deferFunction(self, callable):
"""
Schedule a function handler to be called just before completion.
This is used for handling function bodies, which must be deferred
because code later in the file might modify the global scope. When
`callable` is called, the scope at the time this is called will be
restored, however it will contain any new bindings added to it.
"""
self._deferredFunctions.append((callable, self.scopeStack[:], self.offset))
def deferAssignment(self, callable):
"""
Schedule an assignment handler to be called just after deferred
function handlers.
"""
self._deferredAssignments.append((callable, self.scopeStack[:], self.offset))
def runDeferred(self, deferred):
"""
Run the callables in C{deferred} using their associated scope stack.
"""
for handler, scope, offset in deferred:
self.scopeStack = scope
self.offset = offset
handler()
def _in_doctest(self):
return (len(self.scopeStack) >= 2 and
isinstance(self.scopeStack[1], DoctestScope))
@property
def futuresAllowed(self):
if not all(isinstance(scope, ModuleScope)
for scope in self.scopeStack):
return False
return self.scope._futures_allowed
@futuresAllowed.setter
def futuresAllowed(self, value):
assert value is False
if isinstance(self.scope, ModuleScope):
self.scope._futures_allowed = False
@property
def annotationsFutureEnabled(self):
scope = self.scopeStack[0]
if not isinstance(scope, ModuleScope):
return False
return scope._annotations_future_enabled
@annotationsFutureEnabled.setter
def annotationsFutureEnabled(self, value):
assert value is True
assert isinstance(self.scope, ModuleScope)
self.scope._annotations_future_enabled = True
@property
def scope(self):
return self.scopeStack[-1]
def popScope(self):
self.deadScopes.append(self.scopeStack.pop())
def checkDeadScopes(self):
"""
Look at scopes which have been fully examined and report names in them
which were imported but unused.
"""
for scope in self.deadScopes:
# imports in classes are public members
if isinstance(scope, ClassScope):
continue
all_binding = scope.get('__all__')
if all_binding and not isinstance(all_binding, ExportBinding):
all_binding = None
if all_binding:
all_names = set(all_binding.names)
undefined = all_names.difference(scope)
else:
all_names = undefined = []
if undefined:
if not scope.importStarred and \
os.path.basename(self.filename) != '__init__.py':
# Look for possible mistakes in the export list
for name in undefined:
self.report(messages.UndefinedExport,
scope['__all__'].source, name)
# mark all import '*' as used by the undefined in __all__
if scope.importStarred:
from_list = []
for binding in scope.values():
if isinstance(binding, StarImportation):
binding.used = all_binding
from_list.append(binding.fullName)
# report * usage, with a list of possible sources
from_list = ', '.join(sorted(from_list))
for name in undefined:
self.report(messages.ImportStarUsage,
scope['__all__'].source, name, from_list)
# Look for imported names that aren't used.
for value in scope.values():
if isinstance(value, Importation):
used = value.used or value.name in all_names
if not used:
messg = messages.UnusedImport
self.report(messg, value.source, str(value))
for node in value.redefined:
if isinstance(self.getParent(node), FOR_TYPES):
messg = messages.ImportShadowedByLoopVar
elif used:
continue
else:
messg = messages.RedefinedWhileUnused
self.report(messg, node, value.name, value.source)
def pushScope(self, scopeClass=FunctionScope):
self.scopeStack.append(scopeClass())
def report(self, messageClass, *args, **kwargs):
self.messages.append(messageClass(self.filename, *args, **kwargs))
def getParent(self, node):
# Lookup the first parent which is not Tuple, List or Starred
while True:
node = node.parent
if not hasattr(node, 'elts') and not hasattr(node, 'ctx'):
return node
def getCommonAncestor(self, lnode, rnode, stop):
if stop in (lnode, rnode) or not (hasattr(lnode, 'parent') and
hasattr(rnode, 'parent')):
return None
if lnode is rnode:
return lnode
if (lnode.depth > rnode.depth):
return self.getCommonAncestor(lnode.parent, rnode, stop)
if (lnode.depth < rnode.depth):
return self.getCommonAncestor(lnode, rnode.parent, stop)
return self.getCommonAncestor(lnode.parent, rnode.parent, stop)
def descendantOf(self, node, ancestors, stop):
for a in ancestors:
if self.getCommonAncestor(node, a, stop):
return True
return False
def _getAncestor(self, node, ancestor_type):
parent = node
while True:
if parent is self.root:
return None
parent = self.getParent(parent)
if isinstance(parent, ancestor_type):
return parent
def getScopeNode(self, node):
return self._getAncestor(node, tuple(Checker._ast_node_scope.keys()))
def differentForks(self, lnode, rnode):
"""True, if lnode and rnode are located on different forks of IF/TRY"""
ancestor = self.getCommonAncestor(lnode, rnode, self.root)
parts = getAlternatives(ancestor)
if parts:
for items in parts:
if self.descendantOf(lnode, items, ancestor) ^ \
self.descendantOf(rnode, items, ancestor):
return True
return False
def addBinding(self, node, value):
"""
Called when a binding is altered.
- `node` is the statement responsible for the change
- `value` is the new value, a Binding instance
"""
# assert value.source in (node, node.parent):
for scope in self.scopeStack[::-1]:
if value.name in scope:
break
existing = scope.get(value.name)
if (existing and not isinstance(existing, Builtin) and
not self.differentForks(node, existing.source)):
parent_stmt = self.getParent(value.source)
if isinstance(existing, Importation) and isinstance(parent_stmt, FOR_TYPES):
self.report(messages.ImportShadowedByLoopVar,
node, value.name, existing.source)
elif scope is self.scope:
if (isinstance(parent_stmt, ast.comprehension) and
not isinstance(self.getParent(existing.source),
(FOR_TYPES, ast.comprehension))):
self.report(messages.RedefinedInListComp,
node, value.name, existing.source)
elif not existing.used and value.redefines(existing):
if value.name != '_' or isinstance(existing, Importation):
if not is_typing_overload(existing, self.scopeStack):
self.report(messages.RedefinedWhileUnused,
node, value.name, existing.source)
elif isinstance(existing, Importation) and value.redefines(existing):
existing.redefined.append(node)
if value.name in self.scope:
# then assume the rebound name is used as a global or within a loop
value.used = self.scope[value.name].used
self.scope[value.name] = value
def getNodeHandler(self, node_class):
try:
return self._nodeHandlers[node_class]
except KeyError:
nodeType = getNodeType(node_class)
self._nodeHandlers[node_class] = handler = getattr(self, nodeType)
return handler
def handleNodeLoad(self, node):
name = getNodeName(node)
if not name:
return
in_generators = None
importStarred = None
# try enclosing function scopes and global scope
for scope in self.scopeStack[-1::-1]:
if isinstance(scope, ClassScope):
if not PY2 and name == '__class__':
return
elif in_generators is False:
# only generators used in a class scope can access the
# names of the class. this is skipped during the first
# iteration
continue
if (name == 'print' and
isinstance(scope.get(name, None), Builtin)):
parent = self.getParent(node)
if (isinstance(parent, ast.BinOp) and
isinstance(parent.op, ast.RShift)):
self.report(messages.InvalidPrintSyntax, node)
try:
scope[name].used = (self.scope, node)
# if the name of SubImportation is same as
# alias of other Importation and the alias
# is used, SubImportation also should be marked as used.
n = scope[name]
if isinstance(n, Importation) and n._has_alias():
try:
scope[n.fullName].used = (self.scope, node)
except KeyError:
pass
except KeyError:
pass
else:
return
importStarred = importStarred or scope.importStarred
if in_generators is not False:
in_generators = isinstance(scope, GeneratorScope)
if importStarred:
from_list = []
for scope in self.scopeStack[-1::-1]:
for binding in scope.values():
if isinstance(binding, StarImportation):
# mark '*' imports as used for each scope
binding.used = (self.scope, node)
from_list.append(binding.fullName)
# report * usage, with a list of possible sources
from_list = ', '.join(sorted(from_list))
self.report(messages.ImportStarUsage, node, name, from_list)
return
if name == '__path__' and os.path.basename(self.filename) == '__init__.py':
# the special name __path__ is valid only in packages
return
if name == '__module__' and isinstance(self.scope, ClassScope):
return
# protected with a NameError handler?
if 'NameError' not in self.exceptHandlers[-1]:
self.report(messages.UndefinedName, node, name)
def handleNodeStore(self, node):
name = getNodeName(node)
if not name:
return
# if the name hasn't already been defined in the current scope
if isinstance(self.scope, FunctionScope) and name not in self.scope:
# for each function or module scope above us
for scope in self.scopeStack[:-1]:
if not isinstance(scope, (FunctionScope, ModuleScope)):
continue
# if the name was defined in that scope, and the name has
# been accessed already in the current scope, and hasn't
# been declared global
used = name in scope and scope[name].used
if used and used[0] is self.scope and name not in self.scope.globals:
# then it's probably a mistake
self.report(messages.UndefinedLocal,
scope[name].used[1], name, scope[name].source)
break
parent_stmt = self.getParent(node)
if isinstance(parent_stmt, (FOR_TYPES, ast.comprehension)) or (
parent_stmt != node.parent and
not self.isLiteralTupleUnpacking(parent_stmt)):
binding = Binding(name, node)
elif name == '__all__' and isinstance(self.scope, ModuleScope):
binding = ExportBinding(name, node.parent, self.scope)
elif isinstance(getattr(node, 'ctx', None), ast.Param):
binding = Argument(name, self.getScopeNode(node))
else:
binding = Assignment(name, node)
self.addBinding(node, binding)
def handleNodeDelete(self, node):
def on_conditional_branch():
"""
Return `True` if node is part of a conditional body.
"""
current = getattr(node, 'parent', None)
while current:
if isinstance(current, (ast.If, ast.While, ast.IfExp)):
return True
current = getattr(current, 'parent', None)
return False
name = getNodeName(node)
if not name:
return
if on_conditional_branch():
# We cannot predict if this conditional branch is going to
# be executed.
return
if isinstance(self.scope, FunctionScope) and name in self.scope.globals:
self.scope.globals.remove(name)
else:
try:
del self.scope[name]
except KeyError:
self.report(messages.UndefinedName, node, name)
def _handle_type_comments(self, node):
for (lineno, col_offset), comment in self._type_comments.get(node, ()):
comment = comment.split(':', 1)[1].strip()
func_match = TYPE_FUNC_RE.match(comment)
if func_match:
parts = (
func_match.group(1).replace('*', ''),
func_match.group(2).strip(),
)
else:
parts = (comment,)
for part in parts:
if PY2:
part = part.replace('...', 'Ellipsis')
self.deferFunction(functools.partial(
self.handleStringAnnotation,
part, DummyNode(lineno, col_offset), lineno, col_offset,
messages.CommentAnnotationSyntaxError,
))
def handleChildren(self, tree, omit=None):
self._handle_type_comments(tree)
for node in iter_child_nodes(tree, omit=omit):
self.handleNode(node, tree)
def isLiteralTupleUnpacking(self, node):
if isinstance(node, ast.Assign):
for child in node.targets + [node.value]:
if not hasattr(child, 'elts'):
return False
return True
def isDocstring(self, node):
"""
Determine if the given node is a docstring, as long as it is at the
correct place in the node tree.
"""
return isinstance(node, ast.Str) or (isinstance(node, ast.Expr) and
isinstance(node.value, ast.Str))
def getDocstring(self, node):
if isinstance(node, ast.Expr):
node = node.value
if not isinstance(node, ast.Str):
return (None, None)
if PYPY or PY38_PLUS:
doctest_lineno = node.lineno - 1
else:
# Computed incorrectly if the docstring has backslash
doctest_lineno = node.lineno - node.s.count('\n') - 1
return (node.s, doctest_lineno)
def handleNode(self, node, parent):
if node is None:
return
if self.offset and getattr(node, 'lineno', None) is not None:
node.lineno += self.offset[0]
node.col_offset += self.offset[1]
if self.traceTree:
print(' ' * self.nodeDepth + node.__class__.__name__)
if self.futuresAllowed and not (isinstance(node, ast.ImportFrom) or
self.isDocstring(node)):
self.futuresAllowed = False
self.nodeDepth += 1
node.depth = self.nodeDepth
node.parent = parent
try:
handler = self.getNodeHandler(node.__class__)
handler(node)
finally:
self.nodeDepth -= 1
if self.traceTree:
print(' ' * self.nodeDepth + 'end ' + node.__class__.__name__)
_getDoctestExamples = doctest.DocTestParser().get_examples
def handleDoctests(self, node):
try:
if hasattr(node, 'docstring'):
docstring = node.docstring
# This is just a reasonable guess. In Python 3.7, docstrings no
# longer have line numbers associated with them. This will be
# incorrect if there are empty lines between the beginning
# of the function and the docstring.
node_lineno = node.lineno
if hasattr(node, 'args'):
node_lineno = max([node_lineno] +
[arg.lineno for arg in node.args.args])
else:
(docstring, node_lineno) = self.getDocstring(node.body[0])
examples = docstring and self._getDoctestExamples(docstring)
except (ValueError, IndexError):
# e.g. line 6 of the docstring for <string> has inconsistent
# leading whitespace: ...
return
if not examples:
return
# Place doctest in module scope
saved_stack = self.scopeStack
self.scopeStack = [self.scopeStack[0]]
node_offset = self.offset or (0, 0)
self.pushScope(DoctestScope)
self.addBinding(None, Builtin('_'))
for example in examples:
try:
tree = ast.parse(example.source, "<doctest>")
except SyntaxError:
e = sys.exc_info()[1]
if PYPY:
e.offset += 1
position = (node_lineno + example.lineno + e.lineno,
example.indent + 4 + (e.offset or 0))
self.report(messages.DoctestSyntaxError, node, position)
else:
self.offset = (node_offset[0] + node_lineno + example.lineno,
node_offset[1] + example.indent + 4)
self.handleChildren(tree)
self.offset = node_offset
self.popScope()
self.scopeStack = saved_stack
def handleStringAnnotation(self, s, node, ref_lineno, ref_col_offset, err):
try:
tree = ast.parse(s)
except SyntaxError:
self.report(err, node, s)
return
body = tree.body
if len(body) != 1 or not isinstance(body[0], ast.Expr):
self.report(err, node, s)
return
parsed_annotation = tree.body[0].value
for descendant in ast.walk(parsed_annotation):
if (
'lineno' in descendant._attributes and
'col_offset' in descendant._attributes
):
descendant.lineno = ref_lineno
descendant.col_offset = ref_col_offset
self.handleNode(parsed_annotation, node)
def handleAnnotation(self, annotation, node):
if isinstance(annotation, ast.Str):
# Defer handling forward annotation.
self.deferFunction(functools.partial(
self.handleStringAnnotation,
annotation.s,
node,
annotation.lineno,
annotation.col_offset,
messages.ForwardAnnotationSyntaxError,
))
elif self.annotationsFutureEnabled:
self.deferFunction(lambda: self.handleNode(annotation, node))
else:
self.handleNode(annotation, node)
def ignore(self, node):
pass
# "stmt" type nodes
DELETE = PRINT = FOR = ASYNCFOR = WHILE = IF = WITH = WITHITEM = \
ASYNCWITH = ASYNCWITHITEM = TRYFINALLY = EXEC = \
EXPR = ASSIGN = handleChildren
PASS = ignore
# "expr" type nodes
BOOLOP = BINOP = UNARYOP = IFEXP = SET = \
CALL = REPR = ATTRIBUTE = SUBSCRIPT = \
STARRED = NAMECONSTANT = handleChildren
NUM = STR = BYTES = ELLIPSIS = CONSTANT = ignore
# "slice" type nodes
SLICE = EXTSLICE = INDEX = handleChildren
# expression contexts are node instances too, though being constants
LOAD = STORE = DEL = AUGLOAD = AUGSTORE = PARAM = ignore
# same for operators
AND = OR = ADD = SUB = MULT = DIV = MOD = POW = LSHIFT = RSHIFT = \
BITOR = BITXOR = BITAND = FLOORDIV = INVERT = NOT = UADD = USUB = \
EQ = NOTEQ = LT = LTE = GT = GTE = IS = ISNOT = IN = NOTIN = \
MATMULT = ignore
def RAISE(self, node):
self.handleChildren(node)
arg = get_raise_argument(node)
if isinstance(arg, ast.Call):
if is_notimplemented_name_node(arg.func):
# Handle "raise NotImplemented(...)"
self.report(messages.RaiseNotImplemented, node)
elif is_notimplemented_name_node(arg):
# Handle "raise NotImplemented"
self.report(messages.RaiseNotImplemented, node)
# additional node types
COMPREHENSION = KEYWORD = FORMATTEDVALUE = JOINEDSTR = handleChildren
def DICT(self, node):
# Complain if there are duplicate keys with different values
# If they have the same value it's not going to cause potentially
# unexpected behaviour so we'll not complain.
keys = [
convert_to_value(key) for key in node.keys
]
key_counts = counter(keys)
duplicate_keys = [
key for key, count in key_counts.items()
if count > 1
]
for key in duplicate_keys:
key_indices = [i for i, i_key in enumerate(keys) if i_key == key]
values = counter(
convert_to_value(node.values[index])
for index in key_indices
)
if any(count == 1 for value, count in values.items()):
for key_index in key_indices:
key_node = node.keys[key_index]
if isinstance(key, VariableKey):
self.report(messages.MultiValueRepeatedKeyVariable,
key_node,
key.name)
else:
self.report(
messages.MultiValueRepeatedKeyLiteral,
key_node,
key,
)
self.handleChildren(node)
def ASSERT(self, node):
if isinstance(node.test, ast.Tuple) and node.test.elts != []:
self.report(messages.AssertTuple, node)
self.handleChildren(node)
NONLOCAL = GLOBAL
def GENERATOREXP(self, node):
self.pushScope(GeneratorScope)
self.handleChildren(node)
self.popScope()
LISTCOMP = handleChildren if PY2 else GENERATOREXP
DICTCOMP = SETCOMP = GENERATOREXP
def NAME(self, node):
"""
Handle occurrence of Name (which can be a load/store/delete access.)
"""
# Locate the name in locals / function / globals scopes.
if isinstance(node.ctx, (ast.Load, ast.AugLoad)):
self.handleNodeLoad(node)
if (node.id == 'locals' and isinstance(self.scope, FunctionScope) and
isinstance(node.parent, ast.Call)):
# we are doing locals() call in current scope
self.scope.usesLocals = True
elif isinstance(node.ctx, (ast.Store, ast.AugStore, ast.Param)):
self.handleNodeStore(node)
elif isinstance(node.ctx, ast.Del):
self.handleNodeDelete(node)
else:
# Unknown context
raise RuntimeError("Got impossible expression context: %r" % (node.ctx,))
def CONTINUE(self, node):
# Walk the tree up until we see a loop (OK), a function or class
# definition (not OK), for 'continue', a finally block (not OK), or
# the top module scope (not OK)
n = node
while hasattr(n, 'parent'):
n, n_child = n.parent, n
if isinstance(n, LOOP_TYPES):
# Doesn't apply unless it's in the loop itself
if n_child not in n.orelse:
return
if isinstance(n, (ast.FunctionDef, ast.ClassDef)):
break
# Handle Try/TryFinally difference in Python < and >= 3.3
if hasattr(n, 'finalbody') and isinstance(node, ast.Continue):
if n_child in n.finalbody:
self.report(messages.ContinueInFinally, node)
return
if isinstance(node, ast.Continue):
self.report(messages.ContinueOutsideLoop, node)
else: # ast.Break
self.report(messages.BreakOutsideLoop, node)
BREAK = CONTINUE
def RETURN(self, node):
if isinstance(self.scope, (ClassScope, ModuleScope)):
self.report(messages.ReturnOutsideFunction, node)
return
if (
node.value and
hasattr(self.scope, 'returnValue') and
not self.scope.returnValue
):
self.scope.returnValue = node.value
self.handleNode(node.value, node)
def YIELD(self, node):
if isinstance(self.scope, (ClassScope, ModuleScope)):
self.report(messages.YieldOutsideFunction, node)
return
self.scope.isGenerator = True
self.handleNode(node.value, node)
AWAIT = YIELDFROM = YIELD
def FUNCTIONDEF(self, node):
for deco in node.decorator_list:
self.handleNode(deco, node)
self.LAMBDA(node)
self.addBinding(node, FunctionDefinition(node.name, node))
# doctest does not process doctest within a doctest,
# or in nested functions.
if (self.withDoctest and
not self._in_doctest() and
not isinstance(self.scope, FunctionScope)):
self.deferFunction(lambda: self.handleDoctests(node))
ASYNCFUNCTIONDEF = FUNCTIONDEF
def LAMBDA(self, node):
args = []
annotations = []
if PY2:
def addArgs(arglist):
for arg in arglist:
if isinstance(arg, ast.Tuple):
addArgs(arg.elts)
else:
args.append(arg.id)
addArgs(node.args.args)
defaults = node.args.defaults
else:
for arg in node.args.args + node.args.kwonlyargs:
args.append(arg.arg)
annotations.append(arg.annotation)
defaults = node.args.defaults + node.args.kw_defaults
# Only for Python3 FunctionDefs
is_py3_func = hasattr(node, 'returns')
for arg_name in ('vararg', 'kwarg'):
wildcard = getattr(node.args, arg_name)
if not wildcard:
continue
args.append(wildcard if PY2 else wildcard.arg)
if is_py3_func:
if PY2: # Python 2.7
argannotation = arg_name + 'annotation'
annotations.append(getattr(node.args, argannotation))
else: # Python >= 3.4
annotations.append(wildcard.annotation)
if is_py3_func:
annotations.append(node.returns)
if len(set(args)) < len(args):
for (idx, arg) in enumerate(args):
if arg in args[:idx]:
self.report(messages.DuplicateArgument, node, arg)
for annotation in annotations:
self.handleAnnotation(annotation, node)
for default in defaults:
self.handleNode(default, node)
def runFunction():
self.pushScope()
self.handleChildren(node, omit='decorator_list')
def checkUnusedAssignments():
"""
Check to see if any assignments have not been used.
"""
for name, binding in self.scope.unusedAssignments():
self.report(messages.UnusedVariable, binding.source, name)
self.deferAssignment(checkUnusedAssignments)
if PY2:
def checkReturnWithArgumentInsideGenerator():
"""
Check to see if there is any return statement with
arguments but the function is a generator.
"""
if self.scope.isGenerator and self.scope.returnValue:
self.report(messages.ReturnWithArgsInsideGenerator,
self.scope.returnValue)
self.deferAssignment(checkReturnWithArgumentInsideGenerator)
self.popScope()
self.deferFunction(runFunction)
def ARGUMENTS(self, node):
self.handleChildren(node, omit=('defaults', 'kw_defaults'))
if PY2:
scope_node = self.getScopeNode(node)
if node.vararg:
self.addBinding(node, Argument(node.vararg, scope_node))
if node.kwarg:
self.addBinding(node, Argument(node.kwarg, scope_node))
def ARG(self, node):
self.addBinding(node, Argument(node.arg, self.getScopeNode(node)))
def CLASSDEF(self, node):
"""
Check names used in a class definition, including its decorators, base
classes, and the body of its definition. Additionally, add its name to
the current scope.
"""
for deco in node.decorator_list:
self.handleNode(deco, node)
for baseNode in node.bases:
self.handleNode(baseNode, node)
if not PY2:
for keywordNode in node.keywords:
self.handleNode(keywordNode, node)
self.pushScope(ClassScope)
# doctest does not process doctest within a doctest
# classes within classes are processed.
if (self.withDoctest and
not self._in_doctest() and
not isinstance(self.scope, FunctionScope)):
self.deferFunction(lambda: self.handleDoctests(node))
for stmt in node.body:
self.handleNode(stmt, node)
self.popScope()
self.addBinding(node, ClassDefinition(node.name, node))
def AUGASSIGN(self, node):
self.handleNodeLoad(node.target)
self.handleNode(node.value, node)
self.handleNode(node.target, node)
def TUPLE(self, node):
if not PY2 and isinstance(node.ctx, ast.Store):
# Python 3 advanced tuple unpacking: a, *b, c = d.
# Only one starred expression is allowed, and no more than 1<<8
# assignments are allowed before a stared expression. There is
# also a limit of 1<<24 expressions after the starred expression,
# which is impossible to test due to memory restrictions, but we
# add it here anyway
has_starred = False
star_loc = -1
for i, n in enumerate(node.elts):
if isinstance(n, ast.Starred):
if has_starred:
self.report(messages.TwoStarredExpressions, node)
# The SyntaxError doesn't distinguish two from more
# than two.
break
has_starred = True
star_loc = i
if star_loc >= 1 << 8 or len(node.elts) - star_loc - 1 >= 1 << 24:
self.report(messages.TooManyExpressionsInStarredAssignment, node)
self.handleChildren(node)
LIST = TUPLE
def IMPORT(self, node):
for alias in node.names:
if '.' in alias.name and not alias.asname:
importation = SubmoduleImportation(alias.name, node)
else:
name = alias.asname or alias.name
importation = Importation(name, node, alias.name)
self.addBinding(node, importation)
def IMPORTFROM(self, node):
if node.module == '__future__':
if not self.futuresAllowed:
self.report(messages.LateFutureImport,
node, [n.name for n in node.names])
else:
self.futuresAllowed = False
module = ('.' * node.level) + (node.module or '')
for alias in node.names:
name = alias.asname or alias.name
if node.module == '__future__':
importation = FutureImportation(name, node, self.scope)
if alias.name not in __future__.all_feature_names:
self.report(messages.FutureFeatureNotDefined,
node, alias.name)
if alias.name == 'annotations':
self.annotationsFutureEnabled = True
elif alias.name == '*':
# Only Python 2, local import * is a SyntaxWarning
if not PY2 and not isinstance(self.scope, ModuleScope):
self.report(messages.ImportStarNotPermitted,
node, module)
continue
self.scope.importStarred = True
self.report(messages.ImportStarUsed, node, module)
importation = StarImportation(module, node)
else:
importation = ImportationFrom(name, node,
module, alias.name)
self.addBinding(node, importation)
def TRY(self, node):
handler_names = []
# List the exception handlers
for i, handler in enumerate(node.handlers):
if isinstance(handler.type, ast.Tuple):
for exc_type in handler.type.elts:
handler_names.append(getNodeName(exc_type))
elif handler.type:
handler_names.append(getNodeName(handler.type))
if handler.type is None and i < len(node.handlers) - 1:
self.report(messages.DefaultExceptNotLast, handler)
# Memorize the except handlers and process the body
self.exceptHandlers.append(handler_names)
for child in node.body:
self.handleNode(child, node)
self.exceptHandlers.pop()
# Process the other nodes: "except:", "else:", "finally:"
self.handleChildren(node, omit='body')
TRYEXCEPT = TRY
def EXCEPTHANDLER(self, node):
if PY2 or node.name is None:
self.handleChildren(node)
return
# If the name already exists in the scope, modify state of existing
# binding.
if node.name in self.scope:
self.handleNodeStore(node)
# 3.x: the name of the exception, which is not a Name node, but a
# simple string, creates a local that is only bound within the scope of
# the except: block. As such, temporarily remove the existing binding
# to more accurately determine if the name is used in the except:
# block.
try:
prev_definition = self.scope.pop(node.name)
except KeyError:
prev_definition = None
self.handleNodeStore(node)
self.handleChildren(node)
# See discussion on https://github.com/PyCQA/pyflakes/pull/59
# We're removing the local name since it's being unbound after leaving
# the except: block and it's always unbound if the except: block is
# never entered. This will cause an "undefined name" error raised if
# the checked code tries to use the name afterwards.
#
# Unless it's been removed already. Then do nothing.
try:
binding = self.scope.pop(node.name)
except KeyError:
pass
else:
if not binding.used:
self.report(messages.UnusedVariable, node, node.name)
# Restore.
if prev_definition:
self.scope[node.name] = prev_definition
def ANNASSIGN(self, node):
if node.value:
# Only bind the *targets* if the assignment has a value.
# Otherwise it's not really ast.Store and shouldn't silence
# UndefinedLocal warnings.
self.handleNode(node.target, node)
self.handleAnnotation(node.annotation, node)
if node.value:
# If the assignment has value, handle the *value* now.
self.handleNode(node.value, node)
def COMPARE(self, node):
literals = (ast.Str, ast.Num)
if not PY2:
literals += (ast.Bytes,)
left = node.left
for op, right in zip(node.ops, node.comparators):
if (isinstance(op, (ast.Is, ast.IsNot)) and
(isinstance(left, literals) or isinstance(right, literals))):
self.report(messages.IsLiteral, node)
left = right
self.handleChildren(node)
|
PyCQA/pyflakes | pyflakes/checker.py | Checker.NAME | python | def NAME(self, node):
# Locate the name in locals / function / globals scopes.
if isinstance(node.ctx, (ast.Load, ast.AugLoad)):
self.handleNodeLoad(node)
if (node.id == 'locals' and isinstance(self.scope, FunctionScope) and
isinstance(node.parent, ast.Call)):
# we are doing locals() call in current scope
self.scope.usesLocals = True
elif isinstance(node.ctx, (ast.Store, ast.AugStore, ast.Param)):
self.handleNodeStore(node)
elif isinstance(node.ctx, ast.Del):
self.handleNodeDelete(node)
else:
# Unknown context
raise RuntimeError("Got impossible expression context: %r" % (node.ctx,)) | Handle occurrence of Name (which can be a load/store/delete access.) | train | https://github.com/PyCQA/pyflakes/blob/232cb1d27ee134bf96adc8f37e53589dc259b159/pyflakes/checker.py#L1350-L1367 | [
"def handleNodeLoad(self, node):\n name = getNodeName(node)\n if not name:\n return\n\n in_generators = None\n importStarred = None\n\n # try enclosing function scopes and global scope\n for scope in self.scopeStack[-1::-1]:\n if isinstance(scope, ClassScope):\n if not PY2 and name == '__class__':\n return\n elif in_generators is False:\n # only generators used in a class scope can access the\n # names of the class. this is skipped during the first\n # iteration\n continue\n\n if (name == 'print' and\n isinstance(scope.get(name, None), Builtin)):\n parent = self.getParent(node)\n if (isinstance(parent, ast.BinOp) and\n isinstance(parent.op, ast.RShift)):\n self.report(messages.InvalidPrintSyntax, node)\n\n try:\n scope[name].used = (self.scope, node)\n\n # if the name of SubImportation is same as\n # alias of other Importation and the alias\n # is used, SubImportation also should be marked as used.\n n = scope[name]\n if isinstance(n, Importation) and n._has_alias():\n try:\n scope[n.fullName].used = (self.scope, node)\n except KeyError:\n pass\n except KeyError:\n pass\n else:\n return\n\n importStarred = importStarred or scope.importStarred\n\n if in_generators is not False:\n in_generators = isinstance(scope, GeneratorScope)\n\n if importStarred:\n from_list = []\n\n for scope in self.scopeStack[-1::-1]:\n for binding in scope.values():\n if isinstance(binding, StarImportation):\n # mark '*' imports as used for each scope\n binding.used = (self.scope, node)\n from_list.append(binding.fullName)\n\n # report * usage, with a list of possible sources\n from_list = ', '.join(sorted(from_list))\n self.report(messages.ImportStarUsage, node, name, from_list)\n return\n\n if name == '__path__' and os.path.basename(self.filename) == '__init__.py':\n # the special name __path__ is valid only in packages\n return\n\n if name == '__module__' and isinstance(self.scope, ClassScope):\n return\n\n # protected with a NameError handler?\n if 'NameError' not in self.exceptHandlers[-1]:\n self.report(messages.UndefinedName, node, name)\n",
"def handleNodeStore(self, node):\n name = getNodeName(node)\n if not name:\n return\n # if the name hasn't already been defined in the current scope\n if isinstance(self.scope, FunctionScope) and name not in self.scope:\n # for each function or module scope above us\n for scope in self.scopeStack[:-1]:\n if not isinstance(scope, (FunctionScope, ModuleScope)):\n continue\n # if the name was defined in that scope, and the name has\n # been accessed already in the current scope, and hasn't\n # been declared global\n used = name in scope and scope[name].used\n if used and used[0] is self.scope and name not in self.scope.globals:\n # then it's probably a mistake\n self.report(messages.UndefinedLocal,\n scope[name].used[1], name, scope[name].source)\n break\n\n parent_stmt = self.getParent(node)\n if isinstance(parent_stmt, (FOR_TYPES, ast.comprehension)) or (\n parent_stmt != node.parent and\n not self.isLiteralTupleUnpacking(parent_stmt)):\n binding = Binding(name, node)\n elif name == '__all__' and isinstance(self.scope, ModuleScope):\n binding = ExportBinding(name, node.parent, self.scope)\n elif isinstance(getattr(node, 'ctx', None), ast.Param):\n binding = Argument(name, self.getScopeNode(node))\n else:\n binding = Assignment(name, node)\n self.addBinding(node, binding)\n"
] | class Checker(object):
"""
I check the cleanliness and sanity of Python code.
@ivar _deferredFunctions: Tracking list used by L{deferFunction}. Elements
of the list are two-tuples. The first element is the callable passed
to L{deferFunction}. The second element is a copy of the scope stack
at the time L{deferFunction} was called.
@ivar _deferredAssignments: Similar to C{_deferredFunctions}, but for
callables which are deferred assignment checks.
"""
_ast_node_scope = {
ast.Module: ModuleScope,
ast.ClassDef: ClassScope,
ast.FunctionDef: FunctionScope,
ast.Lambda: FunctionScope,
ast.ListComp: GeneratorScope,
ast.SetComp: GeneratorScope,
ast.GeneratorExp: GeneratorScope,
ast.DictComp: GeneratorScope,
}
if PY35_PLUS:
_ast_node_scope[ast.AsyncFunctionDef] = FunctionScope,
nodeDepth = 0
offset = None
traceTree = False
builtIns = set(builtin_vars).union(_MAGIC_GLOBALS)
_customBuiltIns = os.environ.get('PYFLAKES_BUILTINS')
if _customBuiltIns:
builtIns.update(_customBuiltIns.split(','))
del _customBuiltIns
# TODO: file_tokens= is required to perform checks on type comments,
# eventually make this a required positional argument. For now it
# is defaulted to `()` for api compatibility.
def __init__(self, tree, filename='(none)', builtins=None,
withDoctest='PYFLAKES_DOCTEST' in os.environ, file_tokens=()):
self._nodeHandlers = {}
self._deferredFunctions = []
self._deferredAssignments = []
self.deadScopes = []
self.messages = []
self.filename = filename
if builtins:
self.builtIns = self.builtIns.union(builtins)
self.withDoctest = withDoctest
try:
self.scopeStack = [Checker._ast_node_scope[type(tree)]()]
except KeyError:
raise RuntimeError('No scope implemented for the node %r' % tree)
self.exceptHandlers = [()]
self.root = tree
self._type_comments = _collect_type_comments(tree, file_tokens)
for builtin in self.builtIns:
self.addBinding(None, Builtin(builtin))
self.handleChildren(tree)
self.runDeferred(self._deferredFunctions)
# Set _deferredFunctions to None so that deferFunction will fail
# noisily if called after we've run through the deferred functions.
self._deferredFunctions = None
self.runDeferred(self._deferredAssignments)
# Set _deferredAssignments to None so that deferAssignment will fail
# noisily if called after we've run through the deferred assignments.
self._deferredAssignments = None
del self.scopeStack[1:]
self.popScope()
self.checkDeadScopes()
def deferFunction(self, callable):
"""
Schedule a function handler to be called just before completion.
This is used for handling function bodies, which must be deferred
because code later in the file might modify the global scope. When
`callable` is called, the scope at the time this is called will be
restored, however it will contain any new bindings added to it.
"""
self._deferredFunctions.append((callable, self.scopeStack[:], self.offset))
def deferAssignment(self, callable):
"""
Schedule an assignment handler to be called just after deferred
function handlers.
"""
self._deferredAssignments.append((callable, self.scopeStack[:], self.offset))
def runDeferred(self, deferred):
"""
Run the callables in C{deferred} using their associated scope stack.
"""
for handler, scope, offset in deferred:
self.scopeStack = scope
self.offset = offset
handler()
def _in_doctest(self):
return (len(self.scopeStack) >= 2 and
isinstance(self.scopeStack[1], DoctestScope))
@property
def futuresAllowed(self):
if not all(isinstance(scope, ModuleScope)
for scope in self.scopeStack):
return False
return self.scope._futures_allowed
@futuresAllowed.setter
def futuresAllowed(self, value):
assert value is False
if isinstance(self.scope, ModuleScope):
self.scope._futures_allowed = False
@property
def annotationsFutureEnabled(self):
scope = self.scopeStack[0]
if not isinstance(scope, ModuleScope):
return False
return scope._annotations_future_enabled
@annotationsFutureEnabled.setter
def annotationsFutureEnabled(self, value):
assert value is True
assert isinstance(self.scope, ModuleScope)
self.scope._annotations_future_enabled = True
@property
def scope(self):
return self.scopeStack[-1]
def popScope(self):
self.deadScopes.append(self.scopeStack.pop())
def checkDeadScopes(self):
"""
Look at scopes which have been fully examined and report names in them
which were imported but unused.
"""
for scope in self.deadScopes:
# imports in classes are public members
if isinstance(scope, ClassScope):
continue
all_binding = scope.get('__all__')
if all_binding and not isinstance(all_binding, ExportBinding):
all_binding = None
if all_binding:
all_names = set(all_binding.names)
undefined = all_names.difference(scope)
else:
all_names = undefined = []
if undefined:
if not scope.importStarred and \
os.path.basename(self.filename) != '__init__.py':
# Look for possible mistakes in the export list
for name in undefined:
self.report(messages.UndefinedExport,
scope['__all__'].source, name)
# mark all import '*' as used by the undefined in __all__
if scope.importStarred:
from_list = []
for binding in scope.values():
if isinstance(binding, StarImportation):
binding.used = all_binding
from_list.append(binding.fullName)
# report * usage, with a list of possible sources
from_list = ', '.join(sorted(from_list))
for name in undefined:
self.report(messages.ImportStarUsage,
scope['__all__'].source, name, from_list)
# Look for imported names that aren't used.
for value in scope.values():
if isinstance(value, Importation):
used = value.used or value.name in all_names
if not used:
messg = messages.UnusedImport
self.report(messg, value.source, str(value))
for node in value.redefined:
if isinstance(self.getParent(node), FOR_TYPES):
messg = messages.ImportShadowedByLoopVar
elif used:
continue
else:
messg = messages.RedefinedWhileUnused
self.report(messg, node, value.name, value.source)
def pushScope(self, scopeClass=FunctionScope):
self.scopeStack.append(scopeClass())
def report(self, messageClass, *args, **kwargs):
self.messages.append(messageClass(self.filename, *args, **kwargs))
def getParent(self, node):
# Lookup the first parent which is not Tuple, List or Starred
while True:
node = node.parent
if not hasattr(node, 'elts') and not hasattr(node, 'ctx'):
return node
def getCommonAncestor(self, lnode, rnode, stop):
if stop in (lnode, rnode) or not (hasattr(lnode, 'parent') and
hasattr(rnode, 'parent')):
return None
if lnode is rnode:
return lnode
if (lnode.depth > rnode.depth):
return self.getCommonAncestor(lnode.parent, rnode, stop)
if (lnode.depth < rnode.depth):
return self.getCommonAncestor(lnode, rnode.parent, stop)
return self.getCommonAncestor(lnode.parent, rnode.parent, stop)
def descendantOf(self, node, ancestors, stop):
for a in ancestors:
if self.getCommonAncestor(node, a, stop):
return True
return False
def _getAncestor(self, node, ancestor_type):
parent = node
while True:
if parent is self.root:
return None
parent = self.getParent(parent)
if isinstance(parent, ancestor_type):
return parent
def getScopeNode(self, node):
return self._getAncestor(node, tuple(Checker._ast_node_scope.keys()))
def differentForks(self, lnode, rnode):
"""True, if lnode and rnode are located on different forks of IF/TRY"""
ancestor = self.getCommonAncestor(lnode, rnode, self.root)
parts = getAlternatives(ancestor)
if parts:
for items in parts:
if self.descendantOf(lnode, items, ancestor) ^ \
self.descendantOf(rnode, items, ancestor):
return True
return False
def addBinding(self, node, value):
"""
Called when a binding is altered.
- `node` is the statement responsible for the change
- `value` is the new value, a Binding instance
"""
# assert value.source in (node, node.parent):
for scope in self.scopeStack[::-1]:
if value.name in scope:
break
existing = scope.get(value.name)
if (existing and not isinstance(existing, Builtin) and
not self.differentForks(node, existing.source)):
parent_stmt = self.getParent(value.source)
if isinstance(existing, Importation) and isinstance(parent_stmt, FOR_TYPES):
self.report(messages.ImportShadowedByLoopVar,
node, value.name, existing.source)
elif scope is self.scope:
if (isinstance(parent_stmt, ast.comprehension) and
not isinstance(self.getParent(existing.source),
(FOR_TYPES, ast.comprehension))):
self.report(messages.RedefinedInListComp,
node, value.name, existing.source)
elif not existing.used and value.redefines(existing):
if value.name != '_' or isinstance(existing, Importation):
if not is_typing_overload(existing, self.scopeStack):
self.report(messages.RedefinedWhileUnused,
node, value.name, existing.source)
elif isinstance(existing, Importation) and value.redefines(existing):
existing.redefined.append(node)
if value.name in self.scope:
# then assume the rebound name is used as a global or within a loop
value.used = self.scope[value.name].used
self.scope[value.name] = value
def getNodeHandler(self, node_class):
try:
return self._nodeHandlers[node_class]
except KeyError:
nodeType = getNodeType(node_class)
self._nodeHandlers[node_class] = handler = getattr(self, nodeType)
return handler
def handleNodeLoad(self, node):
name = getNodeName(node)
if not name:
return
in_generators = None
importStarred = None
# try enclosing function scopes and global scope
for scope in self.scopeStack[-1::-1]:
if isinstance(scope, ClassScope):
if not PY2 and name == '__class__':
return
elif in_generators is False:
# only generators used in a class scope can access the
# names of the class. this is skipped during the first
# iteration
continue
if (name == 'print' and
isinstance(scope.get(name, None), Builtin)):
parent = self.getParent(node)
if (isinstance(parent, ast.BinOp) and
isinstance(parent.op, ast.RShift)):
self.report(messages.InvalidPrintSyntax, node)
try:
scope[name].used = (self.scope, node)
# if the name of SubImportation is same as
# alias of other Importation and the alias
# is used, SubImportation also should be marked as used.
n = scope[name]
if isinstance(n, Importation) and n._has_alias():
try:
scope[n.fullName].used = (self.scope, node)
except KeyError:
pass
except KeyError:
pass
else:
return
importStarred = importStarred or scope.importStarred
if in_generators is not False:
in_generators = isinstance(scope, GeneratorScope)
if importStarred:
from_list = []
for scope in self.scopeStack[-1::-1]:
for binding in scope.values():
if isinstance(binding, StarImportation):
# mark '*' imports as used for each scope
binding.used = (self.scope, node)
from_list.append(binding.fullName)
# report * usage, with a list of possible sources
from_list = ', '.join(sorted(from_list))
self.report(messages.ImportStarUsage, node, name, from_list)
return
if name == '__path__' and os.path.basename(self.filename) == '__init__.py':
# the special name __path__ is valid only in packages
return
if name == '__module__' and isinstance(self.scope, ClassScope):
return
# protected with a NameError handler?
if 'NameError' not in self.exceptHandlers[-1]:
self.report(messages.UndefinedName, node, name)
def handleNodeStore(self, node):
name = getNodeName(node)
if not name:
return
# if the name hasn't already been defined in the current scope
if isinstance(self.scope, FunctionScope) and name not in self.scope:
# for each function or module scope above us
for scope in self.scopeStack[:-1]:
if not isinstance(scope, (FunctionScope, ModuleScope)):
continue
# if the name was defined in that scope, and the name has
# been accessed already in the current scope, and hasn't
# been declared global
used = name in scope and scope[name].used
if used and used[0] is self.scope and name not in self.scope.globals:
# then it's probably a mistake
self.report(messages.UndefinedLocal,
scope[name].used[1], name, scope[name].source)
break
parent_stmt = self.getParent(node)
if isinstance(parent_stmt, (FOR_TYPES, ast.comprehension)) or (
parent_stmt != node.parent and
not self.isLiteralTupleUnpacking(parent_stmt)):
binding = Binding(name, node)
elif name == '__all__' and isinstance(self.scope, ModuleScope):
binding = ExportBinding(name, node.parent, self.scope)
elif isinstance(getattr(node, 'ctx', None), ast.Param):
binding = Argument(name, self.getScopeNode(node))
else:
binding = Assignment(name, node)
self.addBinding(node, binding)
def handleNodeDelete(self, node):
def on_conditional_branch():
"""
Return `True` if node is part of a conditional body.
"""
current = getattr(node, 'parent', None)
while current:
if isinstance(current, (ast.If, ast.While, ast.IfExp)):
return True
current = getattr(current, 'parent', None)
return False
name = getNodeName(node)
if not name:
return
if on_conditional_branch():
# We cannot predict if this conditional branch is going to
# be executed.
return
if isinstance(self.scope, FunctionScope) and name in self.scope.globals:
self.scope.globals.remove(name)
else:
try:
del self.scope[name]
except KeyError:
self.report(messages.UndefinedName, node, name)
def _handle_type_comments(self, node):
for (lineno, col_offset), comment in self._type_comments.get(node, ()):
comment = comment.split(':', 1)[1].strip()
func_match = TYPE_FUNC_RE.match(comment)
if func_match:
parts = (
func_match.group(1).replace('*', ''),
func_match.group(2).strip(),
)
else:
parts = (comment,)
for part in parts:
if PY2:
part = part.replace('...', 'Ellipsis')
self.deferFunction(functools.partial(
self.handleStringAnnotation,
part, DummyNode(lineno, col_offset), lineno, col_offset,
messages.CommentAnnotationSyntaxError,
))
def handleChildren(self, tree, omit=None):
self._handle_type_comments(tree)
for node in iter_child_nodes(tree, omit=omit):
self.handleNode(node, tree)
def isLiteralTupleUnpacking(self, node):
if isinstance(node, ast.Assign):
for child in node.targets + [node.value]:
if not hasattr(child, 'elts'):
return False
return True
def isDocstring(self, node):
"""
Determine if the given node is a docstring, as long as it is at the
correct place in the node tree.
"""
return isinstance(node, ast.Str) or (isinstance(node, ast.Expr) and
isinstance(node.value, ast.Str))
def getDocstring(self, node):
if isinstance(node, ast.Expr):
node = node.value
if not isinstance(node, ast.Str):
return (None, None)
if PYPY or PY38_PLUS:
doctest_lineno = node.lineno - 1
else:
# Computed incorrectly if the docstring has backslash
doctest_lineno = node.lineno - node.s.count('\n') - 1
return (node.s, doctest_lineno)
def handleNode(self, node, parent):
if node is None:
return
if self.offset and getattr(node, 'lineno', None) is not None:
node.lineno += self.offset[0]
node.col_offset += self.offset[1]
if self.traceTree:
print(' ' * self.nodeDepth + node.__class__.__name__)
if self.futuresAllowed and not (isinstance(node, ast.ImportFrom) or
self.isDocstring(node)):
self.futuresAllowed = False
self.nodeDepth += 1
node.depth = self.nodeDepth
node.parent = parent
try:
handler = self.getNodeHandler(node.__class__)
handler(node)
finally:
self.nodeDepth -= 1
if self.traceTree:
print(' ' * self.nodeDepth + 'end ' + node.__class__.__name__)
_getDoctestExamples = doctest.DocTestParser().get_examples
def handleDoctests(self, node):
try:
if hasattr(node, 'docstring'):
docstring = node.docstring
# This is just a reasonable guess. In Python 3.7, docstrings no
# longer have line numbers associated with them. This will be
# incorrect if there are empty lines between the beginning
# of the function and the docstring.
node_lineno = node.lineno
if hasattr(node, 'args'):
node_lineno = max([node_lineno] +
[arg.lineno for arg in node.args.args])
else:
(docstring, node_lineno) = self.getDocstring(node.body[0])
examples = docstring and self._getDoctestExamples(docstring)
except (ValueError, IndexError):
# e.g. line 6 of the docstring for <string> has inconsistent
# leading whitespace: ...
return
if not examples:
return
# Place doctest in module scope
saved_stack = self.scopeStack
self.scopeStack = [self.scopeStack[0]]
node_offset = self.offset or (0, 0)
self.pushScope(DoctestScope)
self.addBinding(None, Builtin('_'))
for example in examples:
try:
tree = ast.parse(example.source, "<doctest>")
except SyntaxError:
e = sys.exc_info()[1]
if PYPY:
e.offset += 1
position = (node_lineno + example.lineno + e.lineno,
example.indent + 4 + (e.offset or 0))
self.report(messages.DoctestSyntaxError, node, position)
else:
self.offset = (node_offset[0] + node_lineno + example.lineno,
node_offset[1] + example.indent + 4)
self.handleChildren(tree)
self.offset = node_offset
self.popScope()
self.scopeStack = saved_stack
def handleStringAnnotation(self, s, node, ref_lineno, ref_col_offset, err):
try:
tree = ast.parse(s)
except SyntaxError:
self.report(err, node, s)
return
body = tree.body
if len(body) != 1 or not isinstance(body[0], ast.Expr):
self.report(err, node, s)
return
parsed_annotation = tree.body[0].value
for descendant in ast.walk(parsed_annotation):
if (
'lineno' in descendant._attributes and
'col_offset' in descendant._attributes
):
descendant.lineno = ref_lineno
descendant.col_offset = ref_col_offset
self.handleNode(parsed_annotation, node)
def handleAnnotation(self, annotation, node):
if isinstance(annotation, ast.Str):
# Defer handling forward annotation.
self.deferFunction(functools.partial(
self.handleStringAnnotation,
annotation.s,
node,
annotation.lineno,
annotation.col_offset,
messages.ForwardAnnotationSyntaxError,
))
elif self.annotationsFutureEnabled:
self.deferFunction(lambda: self.handleNode(annotation, node))
else:
self.handleNode(annotation, node)
def ignore(self, node):
pass
# "stmt" type nodes
DELETE = PRINT = FOR = ASYNCFOR = WHILE = IF = WITH = WITHITEM = \
ASYNCWITH = ASYNCWITHITEM = TRYFINALLY = EXEC = \
EXPR = ASSIGN = handleChildren
PASS = ignore
# "expr" type nodes
BOOLOP = BINOP = UNARYOP = IFEXP = SET = \
CALL = REPR = ATTRIBUTE = SUBSCRIPT = \
STARRED = NAMECONSTANT = handleChildren
NUM = STR = BYTES = ELLIPSIS = CONSTANT = ignore
# "slice" type nodes
SLICE = EXTSLICE = INDEX = handleChildren
# expression contexts are node instances too, though being constants
LOAD = STORE = DEL = AUGLOAD = AUGSTORE = PARAM = ignore
# same for operators
AND = OR = ADD = SUB = MULT = DIV = MOD = POW = LSHIFT = RSHIFT = \
BITOR = BITXOR = BITAND = FLOORDIV = INVERT = NOT = UADD = USUB = \
EQ = NOTEQ = LT = LTE = GT = GTE = IS = ISNOT = IN = NOTIN = \
MATMULT = ignore
def RAISE(self, node):
self.handleChildren(node)
arg = get_raise_argument(node)
if isinstance(arg, ast.Call):
if is_notimplemented_name_node(arg.func):
# Handle "raise NotImplemented(...)"
self.report(messages.RaiseNotImplemented, node)
elif is_notimplemented_name_node(arg):
# Handle "raise NotImplemented"
self.report(messages.RaiseNotImplemented, node)
# additional node types
COMPREHENSION = KEYWORD = FORMATTEDVALUE = JOINEDSTR = handleChildren
def DICT(self, node):
# Complain if there are duplicate keys with different values
# If they have the same value it's not going to cause potentially
# unexpected behaviour so we'll not complain.
keys = [
convert_to_value(key) for key in node.keys
]
key_counts = counter(keys)
duplicate_keys = [
key for key, count in key_counts.items()
if count > 1
]
for key in duplicate_keys:
key_indices = [i for i, i_key in enumerate(keys) if i_key == key]
values = counter(
convert_to_value(node.values[index])
for index in key_indices
)
if any(count == 1 for value, count in values.items()):
for key_index in key_indices:
key_node = node.keys[key_index]
if isinstance(key, VariableKey):
self.report(messages.MultiValueRepeatedKeyVariable,
key_node,
key.name)
else:
self.report(
messages.MultiValueRepeatedKeyLiteral,
key_node,
key,
)
self.handleChildren(node)
def ASSERT(self, node):
if isinstance(node.test, ast.Tuple) and node.test.elts != []:
self.report(messages.AssertTuple, node)
self.handleChildren(node)
def GLOBAL(self, node):
"""
Keep track of globals declarations.
"""
global_scope_index = 1 if self._in_doctest() else 0
global_scope = self.scopeStack[global_scope_index]
# Ignore 'global' statement in global scope.
if self.scope is not global_scope:
# One 'global' statement can bind multiple (comma-delimited) names.
for node_name in node.names:
node_value = Assignment(node_name, node)
# Remove UndefinedName messages already reported for this name.
# TODO: if the global is not used in this scope, it does not
# become a globally defined name. See test_unused_global.
self.messages = [
m for m in self.messages if not
isinstance(m, messages.UndefinedName) or
m.message_args[0] != node_name]
# Bind name to global scope if it doesn't exist already.
global_scope.setdefault(node_name, node_value)
# Bind name to non-global scopes, but as already "used".
node_value.used = (global_scope, node)
for scope in self.scopeStack[global_scope_index + 1:]:
scope[node_name] = node_value
NONLOCAL = GLOBAL
def GENERATOREXP(self, node):
self.pushScope(GeneratorScope)
self.handleChildren(node)
self.popScope()
LISTCOMP = handleChildren if PY2 else GENERATOREXP
DICTCOMP = SETCOMP = GENERATOREXP
def CONTINUE(self, node):
# Walk the tree up until we see a loop (OK), a function or class
# definition (not OK), for 'continue', a finally block (not OK), or
# the top module scope (not OK)
n = node
while hasattr(n, 'parent'):
n, n_child = n.parent, n
if isinstance(n, LOOP_TYPES):
# Doesn't apply unless it's in the loop itself
if n_child not in n.orelse:
return
if isinstance(n, (ast.FunctionDef, ast.ClassDef)):
break
# Handle Try/TryFinally difference in Python < and >= 3.3
if hasattr(n, 'finalbody') and isinstance(node, ast.Continue):
if n_child in n.finalbody:
self.report(messages.ContinueInFinally, node)
return
if isinstance(node, ast.Continue):
self.report(messages.ContinueOutsideLoop, node)
else: # ast.Break
self.report(messages.BreakOutsideLoop, node)
BREAK = CONTINUE
def RETURN(self, node):
if isinstance(self.scope, (ClassScope, ModuleScope)):
self.report(messages.ReturnOutsideFunction, node)
return
if (
node.value and
hasattr(self.scope, 'returnValue') and
not self.scope.returnValue
):
self.scope.returnValue = node.value
self.handleNode(node.value, node)
def YIELD(self, node):
if isinstance(self.scope, (ClassScope, ModuleScope)):
self.report(messages.YieldOutsideFunction, node)
return
self.scope.isGenerator = True
self.handleNode(node.value, node)
AWAIT = YIELDFROM = YIELD
def FUNCTIONDEF(self, node):
for deco in node.decorator_list:
self.handleNode(deco, node)
self.LAMBDA(node)
self.addBinding(node, FunctionDefinition(node.name, node))
# doctest does not process doctest within a doctest,
# or in nested functions.
if (self.withDoctest and
not self._in_doctest() and
not isinstance(self.scope, FunctionScope)):
self.deferFunction(lambda: self.handleDoctests(node))
ASYNCFUNCTIONDEF = FUNCTIONDEF
def LAMBDA(self, node):
args = []
annotations = []
if PY2:
def addArgs(arglist):
for arg in arglist:
if isinstance(arg, ast.Tuple):
addArgs(arg.elts)
else:
args.append(arg.id)
addArgs(node.args.args)
defaults = node.args.defaults
else:
for arg in node.args.args + node.args.kwonlyargs:
args.append(arg.arg)
annotations.append(arg.annotation)
defaults = node.args.defaults + node.args.kw_defaults
# Only for Python3 FunctionDefs
is_py3_func = hasattr(node, 'returns')
for arg_name in ('vararg', 'kwarg'):
wildcard = getattr(node.args, arg_name)
if not wildcard:
continue
args.append(wildcard if PY2 else wildcard.arg)
if is_py3_func:
if PY2: # Python 2.7
argannotation = arg_name + 'annotation'
annotations.append(getattr(node.args, argannotation))
else: # Python >= 3.4
annotations.append(wildcard.annotation)
if is_py3_func:
annotations.append(node.returns)
if len(set(args)) < len(args):
for (idx, arg) in enumerate(args):
if arg in args[:idx]:
self.report(messages.DuplicateArgument, node, arg)
for annotation in annotations:
self.handleAnnotation(annotation, node)
for default in defaults:
self.handleNode(default, node)
def runFunction():
self.pushScope()
self.handleChildren(node, omit='decorator_list')
def checkUnusedAssignments():
"""
Check to see if any assignments have not been used.
"""
for name, binding in self.scope.unusedAssignments():
self.report(messages.UnusedVariable, binding.source, name)
self.deferAssignment(checkUnusedAssignments)
if PY2:
def checkReturnWithArgumentInsideGenerator():
"""
Check to see if there is any return statement with
arguments but the function is a generator.
"""
if self.scope.isGenerator and self.scope.returnValue:
self.report(messages.ReturnWithArgsInsideGenerator,
self.scope.returnValue)
self.deferAssignment(checkReturnWithArgumentInsideGenerator)
self.popScope()
self.deferFunction(runFunction)
def ARGUMENTS(self, node):
self.handleChildren(node, omit=('defaults', 'kw_defaults'))
if PY2:
scope_node = self.getScopeNode(node)
if node.vararg:
self.addBinding(node, Argument(node.vararg, scope_node))
if node.kwarg:
self.addBinding(node, Argument(node.kwarg, scope_node))
def ARG(self, node):
self.addBinding(node, Argument(node.arg, self.getScopeNode(node)))
def CLASSDEF(self, node):
"""
Check names used in a class definition, including its decorators, base
classes, and the body of its definition. Additionally, add its name to
the current scope.
"""
for deco in node.decorator_list:
self.handleNode(deco, node)
for baseNode in node.bases:
self.handleNode(baseNode, node)
if not PY2:
for keywordNode in node.keywords:
self.handleNode(keywordNode, node)
self.pushScope(ClassScope)
# doctest does not process doctest within a doctest
# classes within classes are processed.
if (self.withDoctest and
not self._in_doctest() and
not isinstance(self.scope, FunctionScope)):
self.deferFunction(lambda: self.handleDoctests(node))
for stmt in node.body:
self.handleNode(stmt, node)
self.popScope()
self.addBinding(node, ClassDefinition(node.name, node))
def AUGASSIGN(self, node):
self.handleNodeLoad(node.target)
self.handleNode(node.value, node)
self.handleNode(node.target, node)
def TUPLE(self, node):
if not PY2 and isinstance(node.ctx, ast.Store):
# Python 3 advanced tuple unpacking: a, *b, c = d.
# Only one starred expression is allowed, and no more than 1<<8
# assignments are allowed before a stared expression. There is
# also a limit of 1<<24 expressions after the starred expression,
# which is impossible to test due to memory restrictions, but we
# add it here anyway
has_starred = False
star_loc = -1
for i, n in enumerate(node.elts):
if isinstance(n, ast.Starred):
if has_starred:
self.report(messages.TwoStarredExpressions, node)
# The SyntaxError doesn't distinguish two from more
# than two.
break
has_starred = True
star_loc = i
if star_loc >= 1 << 8 or len(node.elts) - star_loc - 1 >= 1 << 24:
self.report(messages.TooManyExpressionsInStarredAssignment, node)
self.handleChildren(node)
LIST = TUPLE
def IMPORT(self, node):
for alias in node.names:
if '.' in alias.name and not alias.asname:
importation = SubmoduleImportation(alias.name, node)
else:
name = alias.asname or alias.name
importation = Importation(name, node, alias.name)
self.addBinding(node, importation)
def IMPORTFROM(self, node):
if node.module == '__future__':
if not self.futuresAllowed:
self.report(messages.LateFutureImport,
node, [n.name for n in node.names])
else:
self.futuresAllowed = False
module = ('.' * node.level) + (node.module or '')
for alias in node.names:
name = alias.asname or alias.name
if node.module == '__future__':
importation = FutureImportation(name, node, self.scope)
if alias.name not in __future__.all_feature_names:
self.report(messages.FutureFeatureNotDefined,
node, alias.name)
if alias.name == 'annotations':
self.annotationsFutureEnabled = True
elif alias.name == '*':
# Only Python 2, local import * is a SyntaxWarning
if not PY2 and not isinstance(self.scope, ModuleScope):
self.report(messages.ImportStarNotPermitted,
node, module)
continue
self.scope.importStarred = True
self.report(messages.ImportStarUsed, node, module)
importation = StarImportation(module, node)
else:
importation = ImportationFrom(name, node,
module, alias.name)
self.addBinding(node, importation)
def TRY(self, node):
handler_names = []
# List the exception handlers
for i, handler in enumerate(node.handlers):
if isinstance(handler.type, ast.Tuple):
for exc_type in handler.type.elts:
handler_names.append(getNodeName(exc_type))
elif handler.type:
handler_names.append(getNodeName(handler.type))
if handler.type is None and i < len(node.handlers) - 1:
self.report(messages.DefaultExceptNotLast, handler)
# Memorize the except handlers and process the body
self.exceptHandlers.append(handler_names)
for child in node.body:
self.handleNode(child, node)
self.exceptHandlers.pop()
# Process the other nodes: "except:", "else:", "finally:"
self.handleChildren(node, omit='body')
TRYEXCEPT = TRY
def EXCEPTHANDLER(self, node):
if PY2 or node.name is None:
self.handleChildren(node)
return
# If the name already exists in the scope, modify state of existing
# binding.
if node.name in self.scope:
self.handleNodeStore(node)
# 3.x: the name of the exception, which is not a Name node, but a
# simple string, creates a local that is only bound within the scope of
# the except: block. As such, temporarily remove the existing binding
# to more accurately determine if the name is used in the except:
# block.
try:
prev_definition = self.scope.pop(node.name)
except KeyError:
prev_definition = None
self.handleNodeStore(node)
self.handleChildren(node)
# See discussion on https://github.com/PyCQA/pyflakes/pull/59
# We're removing the local name since it's being unbound after leaving
# the except: block and it's always unbound if the except: block is
# never entered. This will cause an "undefined name" error raised if
# the checked code tries to use the name afterwards.
#
# Unless it's been removed already. Then do nothing.
try:
binding = self.scope.pop(node.name)
except KeyError:
pass
else:
if not binding.used:
self.report(messages.UnusedVariable, node, node.name)
# Restore.
if prev_definition:
self.scope[node.name] = prev_definition
def ANNASSIGN(self, node):
if node.value:
# Only bind the *targets* if the assignment has a value.
# Otherwise it's not really ast.Store and shouldn't silence
# UndefinedLocal warnings.
self.handleNode(node.target, node)
self.handleAnnotation(node.annotation, node)
if node.value:
# If the assignment has value, handle the *value* now.
self.handleNode(node.value, node)
def COMPARE(self, node):
literals = (ast.Str, ast.Num)
if not PY2:
literals += (ast.Bytes,)
left = node.left
for op, right in zip(node.ops, node.comparators):
if (isinstance(op, (ast.Is, ast.IsNot)) and
(isinstance(left, literals) or isinstance(right, literals))):
self.report(messages.IsLiteral, node)
left = right
self.handleChildren(node)
|
PyCQA/pyflakes | pyflakes/checker.py | Checker.CLASSDEF | python | def CLASSDEF(self, node):
for deco in node.decorator_list:
self.handleNode(deco, node)
for baseNode in node.bases:
self.handleNode(baseNode, node)
if not PY2:
for keywordNode in node.keywords:
self.handleNode(keywordNode, node)
self.pushScope(ClassScope)
# doctest does not process doctest within a doctest
# classes within classes are processed.
if (self.withDoctest and
not self._in_doctest() and
not isinstance(self.scope, FunctionScope)):
self.deferFunction(lambda: self.handleDoctests(node))
for stmt in node.body:
self.handleNode(stmt, node)
self.popScope()
self.addBinding(node, ClassDefinition(node.name, node)) | Check names used in a class definition, including its decorators, base
classes, and the body of its definition. Additionally, add its name to
the current scope. | train | https://github.com/PyCQA/pyflakes/blob/232cb1d27ee134bf96adc8f37e53589dc259b159/pyflakes/checker.py#L1519-L1542 | [
"def _in_doctest(self):\n return (len(self.scopeStack) >= 2 and\n isinstance(self.scopeStack[1], DoctestScope))\n",
"def popScope(self):\n self.deadScopes.append(self.scopeStack.pop())\n",
"def pushScope(self, scopeClass=FunctionScope):\n self.scopeStack.append(scopeClass())\n",
"def addBinding(self, node, value):\n \"\"\"\n Called when a binding is altered.\n\n - `node` is the statement responsible for the change\n - `value` is the new value, a Binding instance\n \"\"\"\n # assert value.source in (node, node.parent):\n for scope in self.scopeStack[::-1]:\n if value.name in scope:\n break\n existing = scope.get(value.name)\n\n if (existing and not isinstance(existing, Builtin) and\n not self.differentForks(node, existing.source)):\n\n parent_stmt = self.getParent(value.source)\n if isinstance(existing, Importation) and isinstance(parent_stmt, FOR_TYPES):\n self.report(messages.ImportShadowedByLoopVar,\n node, value.name, existing.source)\n\n elif scope is self.scope:\n if (isinstance(parent_stmt, ast.comprehension) and\n not isinstance(self.getParent(existing.source),\n (FOR_TYPES, ast.comprehension))):\n self.report(messages.RedefinedInListComp,\n node, value.name, existing.source)\n elif not existing.used and value.redefines(existing):\n if value.name != '_' or isinstance(existing, Importation):\n if not is_typing_overload(existing, self.scopeStack):\n self.report(messages.RedefinedWhileUnused,\n node, value.name, existing.source)\n\n elif isinstance(existing, Importation) and value.redefines(existing):\n existing.redefined.append(node)\n\n if value.name in self.scope:\n # then assume the rebound name is used as a global or within a loop\n value.used = self.scope[value.name].used\n\n self.scope[value.name] = value\n",
"def handleNode(self, node, parent):\n if node is None:\n return\n if self.offset and getattr(node, 'lineno', None) is not None:\n node.lineno += self.offset[0]\n node.col_offset += self.offset[1]\n if self.traceTree:\n print(' ' * self.nodeDepth + node.__class__.__name__)\n if self.futuresAllowed and not (isinstance(node, ast.ImportFrom) or\n self.isDocstring(node)):\n self.futuresAllowed = False\n self.nodeDepth += 1\n node.depth = self.nodeDepth\n node.parent = parent\n try:\n handler = self.getNodeHandler(node.__class__)\n handler(node)\n finally:\n self.nodeDepth -= 1\n if self.traceTree:\n print(' ' * self.nodeDepth + 'end ' + node.__class__.__name__)\n"
] | class Checker(object):
"""
I check the cleanliness and sanity of Python code.
@ivar _deferredFunctions: Tracking list used by L{deferFunction}. Elements
of the list are two-tuples. The first element is the callable passed
to L{deferFunction}. The second element is a copy of the scope stack
at the time L{deferFunction} was called.
@ivar _deferredAssignments: Similar to C{_deferredFunctions}, but for
callables which are deferred assignment checks.
"""
_ast_node_scope = {
ast.Module: ModuleScope,
ast.ClassDef: ClassScope,
ast.FunctionDef: FunctionScope,
ast.Lambda: FunctionScope,
ast.ListComp: GeneratorScope,
ast.SetComp: GeneratorScope,
ast.GeneratorExp: GeneratorScope,
ast.DictComp: GeneratorScope,
}
if PY35_PLUS:
_ast_node_scope[ast.AsyncFunctionDef] = FunctionScope,
nodeDepth = 0
offset = None
traceTree = False
builtIns = set(builtin_vars).union(_MAGIC_GLOBALS)
_customBuiltIns = os.environ.get('PYFLAKES_BUILTINS')
if _customBuiltIns:
builtIns.update(_customBuiltIns.split(','))
del _customBuiltIns
# TODO: file_tokens= is required to perform checks on type comments,
# eventually make this a required positional argument. For now it
# is defaulted to `()` for api compatibility.
def __init__(self, tree, filename='(none)', builtins=None,
withDoctest='PYFLAKES_DOCTEST' in os.environ, file_tokens=()):
self._nodeHandlers = {}
self._deferredFunctions = []
self._deferredAssignments = []
self.deadScopes = []
self.messages = []
self.filename = filename
if builtins:
self.builtIns = self.builtIns.union(builtins)
self.withDoctest = withDoctest
try:
self.scopeStack = [Checker._ast_node_scope[type(tree)]()]
except KeyError:
raise RuntimeError('No scope implemented for the node %r' % tree)
self.exceptHandlers = [()]
self.root = tree
self._type_comments = _collect_type_comments(tree, file_tokens)
for builtin in self.builtIns:
self.addBinding(None, Builtin(builtin))
self.handleChildren(tree)
self.runDeferred(self._deferredFunctions)
# Set _deferredFunctions to None so that deferFunction will fail
# noisily if called after we've run through the deferred functions.
self._deferredFunctions = None
self.runDeferred(self._deferredAssignments)
# Set _deferredAssignments to None so that deferAssignment will fail
# noisily if called after we've run through the deferred assignments.
self._deferredAssignments = None
del self.scopeStack[1:]
self.popScope()
self.checkDeadScopes()
def deferFunction(self, callable):
"""
Schedule a function handler to be called just before completion.
This is used for handling function bodies, which must be deferred
because code later in the file might modify the global scope. When
`callable` is called, the scope at the time this is called will be
restored, however it will contain any new bindings added to it.
"""
self._deferredFunctions.append((callable, self.scopeStack[:], self.offset))
def deferAssignment(self, callable):
"""
Schedule an assignment handler to be called just after deferred
function handlers.
"""
self._deferredAssignments.append((callable, self.scopeStack[:], self.offset))
def runDeferred(self, deferred):
"""
Run the callables in C{deferred} using their associated scope stack.
"""
for handler, scope, offset in deferred:
self.scopeStack = scope
self.offset = offset
handler()
def _in_doctest(self):
return (len(self.scopeStack) >= 2 and
isinstance(self.scopeStack[1], DoctestScope))
@property
def futuresAllowed(self):
if not all(isinstance(scope, ModuleScope)
for scope in self.scopeStack):
return False
return self.scope._futures_allowed
@futuresAllowed.setter
def futuresAllowed(self, value):
assert value is False
if isinstance(self.scope, ModuleScope):
self.scope._futures_allowed = False
@property
def annotationsFutureEnabled(self):
scope = self.scopeStack[0]
if not isinstance(scope, ModuleScope):
return False
return scope._annotations_future_enabled
@annotationsFutureEnabled.setter
def annotationsFutureEnabled(self, value):
assert value is True
assert isinstance(self.scope, ModuleScope)
self.scope._annotations_future_enabled = True
@property
def scope(self):
return self.scopeStack[-1]
def popScope(self):
self.deadScopes.append(self.scopeStack.pop())
def checkDeadScopes(self):
"""
Look at scopes which have been fully examined and report names in them
which were imported but unused.
"""
for scope in self.deadScopes:
# imports in classes are public members
if isinstance(scope, ClassScope):
continue
all_binding = scope.get('__all__')
if all_binding and not isinstance(all_binding, ExportBinding):
all_binding = None
if all_binding:
all_names = set(all_binding.names)
undefined = all_names.difference(scope)
else:
all_names = undefined = []
if undefined:
if not scope.importStarred and \
os.path.basename(self.filename) != '__init__.py':
# Look for possible mistakes in the export list
for name in undefined:
self.report(messages.UndefinedExport,
scope['__all__'].source, name)
# mark all import '*' as used by the undefined in __all__
if scope.importStarred:
from_list = []
for binding in scope.values():
if isinstance(binding, StarImportation):
binding.used = all_binding
from_list.append(binding.fullName)
# report * usage, with a list of possible sources
from_list = ', '.join(sorted(from_list))
for name in undefined:
self.report(messages.ImportStarUsage,
scope['__all__'].source, name, from_list)
# Look for imported names that aren't used.
for value in scope.values():
if isinstance(value, Importation):
used = value.used or value.name in all_names
if not used:
messg = messages.UnusedImport
self.report(messg, value.source, str(value))
for node in value.redefined:
if isinstance(self.getParent(node), FOR_TYPES):
messg = messages.ImportShadowedByLoopVar
elif used:
continue
else:
messg = messages.RedefinedWhileUnused
self.report(messg, node, value.name, value.source)
def pushScope(self, scopeClass=FunctionScope):
self.scopeStack.append(scopeClass())
def report(self, messageClass, *args, **kwargs):
self.messages.append(messageClass(self.filename, *args, **kwargs))
def getParent(self, node):
# Lookup the first parent which is not Tuple, List or Starred
while True:
node = node.parent
if not hasattr(node, 'elts') and not hasattr(node, 'ctx'):
return node
def getCommonAncestor(self, lnode, rnode, stop):
if stop in (lnode, rnode) or not (hasattr(lnode, 'parent') and
hasattr(rnode, 'parent')):
return None
if lnode is rnode:
return lnode
if (lnode.depth > rnode.depth):
return self.getCommonAncestor(lnode.parent, rnode, stop)
if (lnode.depth < rnode.depth):
return self.getCommonAncestor(lnode, rnode.parent, stop)
return self.getCommonAncestor(lnode.parent, rnode.parent, stop)
def descendantOf(self, node, ancestors, stop):
for a in ancestors:
if self.getCommonAncestor(node, a, stop):
return True
return False
def _getAncestor(self, node, ancestor_type):
parent = node
while True:
if parent is self.root:
return None
parent = self.getParent(parent)
if isinstance(parent, ancestor_type):
return parent
def getScopeNode(self, node):
return self._getAncestor(node, tuple(Checker._ast_node_scope.keys()))
def differentForks(self, lnode, rnode):
"""True, if lnode and rnode are located on different forks of IF/TRY"""
ancestor = self.getCommonAncestor(lnode, rnode, self.root)
parts = getAlternatives(ancestor)
if parts:
for items in parts:
if self.descendantOf(lnode, items, ancestor) ^ \
self.descendantOf(rnode, items, ancestor):
return True
return False
def addBinding(self, node, value):
"""
Called when a binding is altered.
- `node` is the statement responsible for the change
- `value` is the new value, a Binding instance
"""
# assert value.source in (node, node.parent):
for scope in self.scopeStack[::-1]:
if value.name in scope:
break
existing = scope.get(value.name)
if (existing and not isinstance(existing, Builtin) and
not self.differentForks(node, existing.source)):
parent_stmt = self.getParent(value.source)
if isinstance(existing, Importation) and isinstance(parent_stmt, FOR_TYPES):
self.report(messages.ImportShadowedByLoopVar,
node, value.name, existing.source)
elif scope is self.scope:
if (isinstance(parent_stmt, ast.comprehension) and
not isinstance(self.getParent(existing.source),
(FOR_TYPES, ast.comprehension))):
self.report(messages.RedefinedInListComp,
node, value.name, existing.source)
elif not existing.used and value.redefines(existing):
if value.name != '_' or isinstance(existing, Importation):
if not is_typing_overload(existing, self.scopeStack):
self.report(messages.RedefinedWhileUnused,
node, value.name, existing.source)
elif isinstance(existing, Importation) and value.redefines(existing):
existing.redefined.append(node)
if value.name in self.scope:
# then assume the rebound name is used as a global or within a loop
value.used = self.scope[value.name].used
self.scope[value.name] = value
def getNodeHandler(self, node_class):
try:
return self._nodeHandlers[node_class]
except KeyError:
nodeType = getNodeType(node_class)
self._nodeHandlers[node_class] = handler = getattr(self, nodeType)
return handler
def handleNodeLoad(self, node):
name = getNodeName(node)
if not name:
return
in_generators = None
importStarred = None
# try enclosing function scopes and global scope
for scope in self.scopeStack[-1::-1]:
if isinstance(scope, ClassScope):
if not PY2 and name == '__class__':
return
elif in_generators is False:
# only generators used in a class scope can access the
# names of the class. this is skipped during the first
# iteration
continue
if (name == 'print' and
isinstance(scope.get(name, None), Builtin)):
parent = self.getParent(node)
if (isinstance(parent, ast.BinOp) and
isinstance(parent.op, ast.RShift)):
self.report(messages.InvalidPrintSyntax, node)
try:
scope[name].used = (self.scope, node)
# if the name of SubImportation is same as
# alias of other Importation and the alias
# is used, SubImportation also should be marked as used.
n = scope[name]
if isinstance(n, Importation) and n._has_alias():
try:
scope[n.fullName].used = (self.scope, node)
except KeyError:
pass
except KeyError:
pass
else:
return
importStarred = importStarred or scope.importStarred
if in_generators is not False:
in_generators = isinstance(scope, GeneratorScope)
if importStarred:
from_list = []
for scope in self.scopeStack[-1::-1]:
for binding in scope.values():
if isinstance(binding, StarImportation):
# mark '*' imports as used for each scope
binding.used = (self.scope, node)
from_list.append(binding.fullName)
# report * usage, with a list of possible sources
from_list = ', '.join(sorted(from_list))
self.report(messages.ImportStarUsage, node, name, from_list)
return
if name == '__path__' and os.path.basename(self.filename) == '__init__.py':
# the special name __path__ is valid only in packages
return
if name == '__module__' and isinstance(self.scope, ClassScope):
return
# protected with a NameError handler?
if 'NameError' not in self.exceptHandlers[-1]:
self.report(messages.UndefinedName, node, name)
def handleNodeStore(self, node):
name = getNodeName(node)
if not name:
return
# if the name hasn't already been defined in the current scope
if isinstance(self.scope, FunctionScope) and name not in self.scope:
# for each function or module scope above us
for scope in self.scopeStack[:-1]:
if not isinstance(scope, (FunctionScope, ModuleScope)):
continue
# if the name was defined in that scope, and the name has
# been accessed already in the current scope, and hasn't
# been declared global
used = name in scope and scope[name].used
if used and used[0] is self.scope and name not in self.scope.globals:
# then it's probably a mistake
self.report(messages.UndefinedLocal,
scope[name].used[1], name, scope[name].source)
break
parent_stmt = self.getParent(node)
if isinstance(parent_stmt, (FOR_TYPES, ast.comprehension)) or (
parent_stmt != node.parent and
not self.isLiteralTupleUnpacking(parent_stmt)):
binding = Binding(name, node)
elif name == '__all__' and isinstance(self.scope, ModuleScope):
binding = ExportBinding(name, node.parent, self.scope)
elif isinstance(getattr(node, 'ctx', None), ast.Param):
binding = Argument(name, self.getScopeNode(node))
else:
binding = Assignment(name, node)
self.addBinding(node, binding)
def handleNodeDelete(self, node):
def on_conditional_branch():
"""
Return `True` if node is part of a conditional body.
"""
current = getattr(node, 'parent', None)
while current:
if isinstance(current, (ast.If, ast.While, ast.IfExp)):
return True
current = getattr(current, 'parent', None)
return False
name = getNodeName(node)
if not name:
return
if on_conditional_branch():
# We cannot predict if this conditional branch is going to
# be executed.
return
if isinstance(self.scope, FunctionScope) and name in self.scope.globals:
self.scope.globals.remove(name)
else:
try:
del self.scope[name]
except KeyError:
self.report(messages.UndefinedName, node, name)
def _handle_type_comments(self, node):
for (lineno, col_offset), comment in self._type_comments.get(node, ()):
comment = comment.split(':', 1)[1].strip()
func_match = TYPE_FUNC_RE.match(comment)
if func_match:
parts = (
func_match.group(1).replace('*', ''),
func_match.group(2).strip(),
)
else:
parts = (comment,)
for part in parts:
if PY2:
part = part.replace('...', 'Ellipsis')
self.deferFunction(functools.partial(
self.handleStringAnnotation,
part, DummyNode(lineno, col_offset), lineno, col_offset,
messages.CommentAnnotationSyntaxError,
))
def handleChildren(self, tree, omit=None):
self._handle_type_comments(tree)
for node in iter_child_nodes(tree, omit=omit):
self.handleNode(node, tree)
def isLiteralTupleUnpacking(self, node):
if isinstance(node, ast.Assign):
for child in node.targets + [node.value]:
if not hasattr(child, 'elts'):
return False
return True
def isDocstring(self, node):
"""
Determine if the given node is a docstring, as long as it is at the
correct place in the node tree.
"""
return isinstance(node, ast.Str) or (isinstance(node, ast.Expr) and
isinstance(node.value, ast.Str))
def getDocstring(self, node):
if isinstance(node, ast.Expr):
node = node.value
if not isinstance(node, ast.Str):
return (None, None)
if PYPY or PY38_PLUS:
doctest_lineno = node.lineno - 1
else:
# Computed incorrectly if the docstring has backslash
doctest_lineno = node.lineno - node.s.count('\n') - 1
return (node.s, doctest_lineno)
def handleNode(self, node, parent):
if node is None:
return
if self.offset and getattr(node, 'lineno', None) is not None:
node.lineno += self.offset[0]
node.col_offset += self.offset[1]
if self.traceTree:
print(' ' * self.nodeDepth + node.__class__.__name__)
if self.futuresAllowed and not (isinstance(node, ast.ImportFrom) or
self.isDocstring(node)):
self.futuresAllowed = False
self.nodeDepth += 1
node.depth = self.nodeDepth
node.parent = parent
try:
handler = self.getNodeHandler(node.__class__)
handler(node)
finally:
self.nodeDepth -= 1
if self.traceTree:
print(' ' * self.nodeDepth + 'end ' + node.__class__.__name__)
_getDoctestExamples = doctest.DocTestParser().get_examples
def handleDoctests(self, node):
try:
if hasattr(node, 'docstring'):
docstring = node.docstring
# This is just a reasonable guess. In Python 3.7, docstrings no
# longer have line numbers associated with them. This will be
# incorrect if there are empty lines between the beginning
# of the function and the docstring.
node_lineno = node.lineno
if hasattr(node, 'args'):
node_lineno = max([node_lineno] +
[arg.lineno for arg in node.args.args])
else:
(docstring, node_lineno) = self.getDocstring(node.body[0])
examples = docstring and self._getDoctestExamples(docstring)
except (ValueError, IndexError):
# e.g. line 6 of the docstring for <string> has inconsistent
# leading whitespace: ...
return
if not examples:
return
# Place doctest in module scope
saved_stack = self.scopeStack
self.scopeStack = [self.scopeStack[0]]
node_offset = self.offset or (0, 0)
self.pushScope(DoctestScope)
self.addBinding(None, Builtin('_'))
for example in examples:
try:
tree = ast.parse(example.source, "<doctest>")
except SyntaxError:
e = sys.exc_info()[1]
if PYPY:
e.offset += 1
position = (node_lineno + example.lineno + e.lineno,
example.indent + 4 + (e.offset or 0))
self.report(messages.DoctestSyntaxError, node, position)
else:
self.offset = (node_offset[0] + node_lineno + example.lineno,
node_offset[1] + example.indent + 4)
self.handleChildren(tree)
self.offset = node_offset
self.popScope()
self.scopeStack = saved_stack
def handleStringAnnotation(self, s, node, ref_lineno, ref_col_offset, err):
try:
tree = ast.parse(s)
except SyntaxError:
self.report(err, node, s)
return
body = tree.body
if len(body) != 1 or not isinstance(body[0], ast.Expr):
self.report(err, node, s)
return
parsed_annotation = tree.body[0].value
for descendant in ast.walk(parsed_annotation):
if (
'lineno' in descendant._attributes and
'col_offset' in descendant._attributes
):
descendant.lineno = ref_lineno
descendant.col_offset = ref_col_offset
self.handleNode(parsed_annotation, node)
def handleAnnotation(self, annotation, node):
if isinstance(annotation, ast.Str):
# Defer handling forward annotation.
self.deferFunction(functools.partial(
self.handleStringAnnotation,
annotation.s,
node,
annotation.lineno,
annotation.col_offset,
messages.ForwardAnnotationSyntaxError,
))
elif self.annotationsFutureEnabled:
self.deferFunction(lambda: self.handleNode(annotation, node))
else:
self.handleNode(annotation, node)
def ignore(self, node):
pass
# "stmt" type nodes
DELETE = PRINT = FOR = ASYNCFOR = WHILE = IF = WITH = WITHITEM = \
ASYNCWITH = ASYNCWITHITEM = TRYFINALLY = EXEC = \
EXPR = ASSIGN = handleChildren
PASS = ignore
# "expr" type nodes
BOOLOP = BINOP = UNARYOP = IFEXP = SET = \
CALL = REPR = ATTRIBUTE = SUBSCRIPT = \
STARRED = NAMECONSTANT = handleChildren
NUM = STR = BYTES = ELLIPSIS = CONSTANT = ignore
# "slice" type nodes
SLICE = EXTSLICE = INDEX = handleChildren
# expression contexts are node instances too, though being constants
LOAD = STORE = DEL = AUGLOAD = AUGSTORE = PARAM = ignore
# same for operators
AND = OR = ADD = SUB = MULT = DIV = MOD = POW = LSHIFT = RSHIFT = \
BITOR = BITXOR = BITAND = FLOORDIV = INVERT = NOT = UADD = USUB = \
EQ = NOTEQ = LT = LTE = GT = GTE = IS = ISNOT = IN = NOTIN = \
MATMULT = ignore
def RAISE(self, node):
self.handleChildren(node)
arg = get_raise_argument(node)
if isinstance(arg, ast.Call):
if is_notimplemented_name_node(arg.func):
# Handle "raise NotImplemented(...)"
self.report(messages.RaiseNotImplemented, node)
elif is_notimplemented_name_node(arg):
# Handle "raise NotImplemented"
self.report(messages.RaiseNotImplemented, node)
# additional node types
COMPREHENSION = KEYWORD = FORMATTEDVALUE = JOINEDSTR = handleChildren
def DICT(self, node):
# Complain if there are duplicate keys with different values
# If they have the same value it's not going to cause potentially
# unexpected behaviour so we'll not complain.
keys = [
convert_to_value(key) for key in node.keys
]
key_counts = counter(keys)
duplicate_keys = [
key for key, count in key_counts.items()
if count > 1
]
for key in duplicate_keys:
key_indices = [i for i, i_key in enumerate(keys) if i_key == key]
values = counter(
convert_to_value(node.values[index])
for index in key_indices
)
if any(count == 1 for value, count in values.items()):
for key_index in key_indices:
key_node = node.keys[key_index]
if isinstance(key, VariableKey):
self.report(messages.MultiValueRepeatedKeyVariable,
key_node,
key.name)
else:
self.report(
messages.MultiValueRepeatedKeyLiteral,
key_node,
key,
)
self.handleChildren(node)
def ASSERT(self, node):
if isinstance(node.test, ast.Tuple) and node.test.elts != []:
self.report(messages.AssertTuple, node)
self.handleChildren(node)
def GLOBAL(self, node):
"""
Keep track of globals declarations.
"""
global_scope_index = 1 if self._in_doctest() else 0
global_scope = self.scopeStack[global_scope_index]
# Ignore 'global' statement in global scope.
if self.scope is not global_scope:
# One 'global' statement can bind multiple (comma-delimited) names.
for node_name in node.names:
node_value = Assignment(node_name, node)
# Remove UndefinedName messages already reported for this name.
# TODO: if the global is not used in this scope, it does not
# become a globally defined name. See test_unused_global.
self.messages = [
m for m in self.messages if not
isinstance(m, messages.UndefinedName) or
m.message_args[0] != node_name]
# Bind name to global scope if it doesn't exist already.
global_scope.setdefault(node_name, node_value)
# Bind name to non-global scopes, but as already "used".
node_value.used = (global_scope, node)
for scope in self.scopeStack[global_scope_index + 1:]:
scope[node_name] = node_value
NONLOCAL = GLOBAL
def GENERATOREXP(self, node):
self.pushScope(GeneratorScope)
self.handleChildren(node)
self.popScope()
LISTCOMP = handleChildren if PY2 else GENERATOREXP
DICTCOMP = SETCOMP = GENERATOREXP
def NAME(self, node):
"""
Handle occurrence of Name (which can be a load/store/delete access.)
"""
# Locate the name in locals / function / globals scopes.
if isinstance(node.ctx, (ast.Load, ast.AugLoad)):
self.handleNodeLoad(node)
if (node.id == 'locals' and isinstance(self.scope, FunctionScope) and
isinstance(node.parent, ast.Call)):
# we are doing locals() call in current scope
self.scope.usesLocals = True
elif isinstance(node.ctx, (ast.Store, ast.AugStore, ast.Param)):
self.handleNodeStore(node)
elif isinstance(node.ctx, ast.Del):
self.handleNodeDelete(node)
else:
# Unknown context
raise RuntimeError("Got impossible expression context: %r" % (node.ctx,))
def CONTINUE(self, node):
# Walk the tree up until we see a loop (OK), a function or class
# definition (not OK), for 'continue', a finally block (not OK), or
# the top module scope (not OK)
n = node
while hasattr(n, 'parent'):
n, n_child = n.parent, n
if isinstance(n, LOOP_TYPES):
# Doesn't apply unless it's in the loop itself
if n_child not in n.orelse:
return
if isinstance(n, (ast.FunctionDef, ast.ClassDef)):
break
# Handle Try/TryFinally difference in Python < and >= 3.3
if hasattr(n, 'finalbody') and isinstance(node, ast.Continue):
if n_child in n.finalbody:
self.report(messages.ContinueInFinally, node)
return
if isinstance(node, ast.Continue):
self.report(messages.ContinueOutsideLoop, node)
else: # ast.Break
self.report(messages.BreakOutsideLoop, node)
BREAK = CONTINUE
def RETURN(self, node):
if isinstance(self.scope, (ClassScope, ModuleScope)):
self.report(messages.ReturnOutsideFunction, node)
return
if (
node.value and
hasattr(self.scope, 'returnValue') and
not self.scope.returnValue
):
self.scope.returnValue = node.value
self.handleNode(node.value, node)
def YIELD(self, node):
if isinstance(self.scope, (ClassScope, ModuleScope)):
self.report(messages.YieldOutsideFunction, node)
return
self.scope.isGenerator = True
self.handleNode(node.value, node)
AWAIT = YIELDFROM = YIELD
def FUNCTIONDEF(self, node):
for deco in node.decorator_list:
self.handleNode(deco, node)
self.LAMBDA(node)
self.addBinding(node, FunctionDefinition(node.name, node))
# doctest does not process doctest within a doctest,
# or in nested functions.
if (self.withDoctest and
not self._in_doctest() and
not isinstance(self.scope, FunctionScope)):
self.deferFunction(lambda: self.handleDoctests(node))
ASYNCFUNCTIONDEF = FUNCTIONDEF
def LAMBDA(self, node):
args = []
annotations = []
if PY2:
def addArgs(arglist):
for arg in arglist:
if isinstance(arg, ast.Tuple):
addArgs(arg.elts)
else:
args.append(arg.id)
addArgs(node.args.args)
defaults = node.args.defaults
else:
for arg in node.args.args + node.args.kwonlyargs:
args.append(arg.arg)
annotations.append(arg.annotation)
defaults = node.args.defaults + node.args.kw_defaults
# Only for Python3 FunctionDefs
is_py3_func = hasattr(node, 'returns')
for arg_name in ('vararg', 'kwarg'):
wildcard = getattr(node.args, arg_name)
if not wildcard:
continue
args.append(wildcard if PY2 else wildcard.arg)
if is_py3_func:
if PY2: # Python 2.7
argannotation = arg_name + 'annotation'
annotations.append(getattr(node.args, argannotation))
else: # Python >= 3.4
annotations.append(wildcard.annotation)
if is_py3_func:
annotations.append(node.returns)
if len(set(args)) < len(args):
for (idx, arg) in enumerate(args):
if arg in args[:idx]:
self.report(messages.DuplicateArgument, node, arg)
for annotation in annotations:
self.handleAnnotation(annotation, node)
for default in defaults:
self.handleNode(default, node)
def runFunction():
self.pushScope()
self.handleChildren(node, omit='decorator_list')
def checkUnusedAssignments():
"""
Check to see if any assignments have not been used.
"""
for name, binding in self.scope.unusedAssignments():
self.report(messages.UnusedVariable, binding.source, name)
self.deferAssignment(checkUnusedAssignments)
if PY2:
def checkReturnWithArgumentInsideGenerator():
"""
Check to see if there is any return statement with
arguments but the function is a generator.
"""
if self.scope.isGenerator and self.scope.returnValue:
self.report(messages.ReturnWithArgsInsideGenerator,
self.scope.returnValue)
self.deferAssignment(checkReturnWithArgumentInsideGenerator)
self.popScope()
self.deferFunction(runFunction)
def ARGUMENTS(self, node):
self.handleChildren(node, omit=('defaults', 'kw_defaults'))
if PY2:
scope_node = self.getScopeNode(node)
if node.vararg:
self.addBinding(node, Argument(node.vararg, scope_node))
if node.kwarg:
self.addBinding(node, Argument(node.kwarg, scope_node))
def ARG(self, node):
self.addBinding(node, Argument(node.arg, self.getScopeNode(node)))
def AUGASSIGN(self, node):
self.handleNodeLoad(node.target)
self.handleNode(node.value, node)
self.handleNode(node.target, node)
def TUPLE(self, node):
if not PY2 and isinstance(node.ctx, ast.Store):
# Python 3 advanced tuple unpacking: a, *b, c = d.
# Only one starred expression is allowed, and no more than 1<<8
# assignments are allowed before a stared expression. There is
# also a limit of 1<<24 expressions after the starred expression,
# which is impossible to test due to memory restrictions, but we
# add it here anyway
has_starred = False
star_loc = -1
for i, n in enumerate(node.elts):
if isinstance(n, ast.Starred):
if has_starred:
self.report(messages.TwoStarredExpressions, node)
# The SyntaxError doesn't distinguish two from more
# than two.
break
has_starred = True
star_loc = i
if star_loc >= 1 << 8 or len(node.elts) - star_loc - 1 >= 1 << 24:
self.report(messages.TooManyExpressionsInStarredAssignment, node)
self.handleChildren(node)
LIST = TUPLE
def IMPORT(self, node):
for alias in node.names:
if '.' in alias.name and not alias.asname:
importation = SubmoduleImportation(alias.name, node)
else:
name = alias.asname or alias.name
importation = Importation(name, node, alias.name)
self.addBinding(node, importation)
def IMPORTFROM(self, node):
if node.module == '__future__':
if not self.futuresAllowed:
self.report(messages.LateFutureImport,
node, [n.name for n in node.names])
else:
self.futuresAllowed = False
module = ('.' * node.level) + (node.module or '')
for alias in node.names:
name = alias.asname or alias.name
if node.module == '__future__':
importation = FutureImportation(name, node, self.scope)
if alias.name not in __future__.all_feature_names:
self.report(messages.FutureFeatureNotDefined,
node, alias.name)
if alias.name == 'annotations':
self.annotationsFutureEnabled = True
elif alias.name == '*':
# Only Python 2, local import * is a SyntaxWarning
if not PY2 and not isinstance(self.scope, ModuleScope):
self.report(messages.ImportStarNotPermitted,
node, module)
continue
self.scope.importStarred = True
self.report(messages.ImportStarUsed, node, module)
importation = StarImportation(module, node)
else:
importation = ImportationFrom(name, node,
module, alias.name)
self.addBinding(node, importation)
def TRY(self, node):
handler_names = []
# List the exception handlers
for i, handler in enumerate(node.handlers):
if isinstance(handler.type, ast.Tuple):
for exc_type in handler.type.elts:
handler_names.append(getNodeName(exc_type))
elif handler.type:
handler_names.append(getNodeName(handler.type))
if handler.type is None and i < len(node.handlers) - 1:
self.report(messages.DefaultExceptNotLast, handler)
# Memorize the except handlers and process the body
self.exceptHandlers.append(handler_names)
for child in node.body:
self.handleNode(child, node)
self.exceptHandlers.pop()
# Process the other nodes: "except:", "else:", "finally:"
self.handleChildren(node, omit='body')
TRYEXCEPT = TRY
def EXCEPTHANDLER(self, node):
if PY2 or node.name is None:
self.handleChildren(node)
return
# If the name already exists in the scope, modify state of existing
# binding.
if node.name in self.scope:
self.handleNodeStore(node)
# 3.x: the name of the exception, which is not a Name node, but a
# simple string, creates a local that is only bound within the scope of
# the except: block. As such, temporarily remove the existing binding
# to more accurately determine if the name is used in the except:
# block.
try:
prev_definition = self.scope.pop(node.name)
except KeyError:
prev_definition = None
self.handleNodeStore(node)
self.handleChildren(node)
# See discussion on https://github.com/PyCQA/pyflakes/pull/59
# We're removing the local name since it's being unbound after leaving
# the except: block and it's always unbound if the except: block is
# never entered. This will cause an "undefined name" error raised if
# the checked code tries to use the name afterwards.
#
# Unless it's been removed already. Then do nothing.
try:
binding = self.scope.pop(node.name)
except KeyError:
pass
else:
if not binding.used:
self.report(messages.UnusedVariable, node, node.name)
# Restore.
if prev_definition:
self.scope[node.name] = prev_definition
def ANNASSIGN(self, node):
if node.value:
# Only bind the *targets* if the assignment has a value.
# Otherwise it's not really ast.Store and shouldn't silence
# UndefinedLocal warnings.
self.handleNode(node.target, node)
self.handleAnnotation(node.annotation, node)
if node.value:
# If the assignment has value, handle the *value* now.
self.handleNode(node.value, node)
def COMPARE(self, node):
literals = (ast.Str, ast.Num)
if not PY2:
literals += (ast.Bytes,)
left = node.left
for op, right in zip(node.ops, node.comparators):
if (isinstance(op, (ast.Is, ast.IsNot)) and
(isinstance(left, literals) or isinstance(right, literals))):
self.report(messages.IsLiteral, node)
left = right
self.handleChildren(node)
|
PyCQA/pyflakes | pyflakes/api.py | check | python | def check(codeString, filename, reporter=None):
if reporter is None:
reporter = modReporter._makeDefaultReporter()
# First, compile into an AST and handle syntax errors.
try:
tree = ast.parse(codeString, filename=filename)
except SyntaxError:
value = sys.exc_info()[1]
msg = value.args[0]
(lineno, offset, text) = value.lineno, value.offset, value.text
if checker.PYPY:
if text is None:
lines = codeString.splitlines()
if len(lines) >= lineno:
text = lines[lineno - 1]
if sys.version_info >= (3, ) and isinstance(text, bytes):
try:
text = text.decode('ascii')
except UnicodeDecodeError:
text = None
offset -= 1
# If there's an encoding problem with the file, the text is None.
if text is None:
# Avoid using msg, since for the only known case, it contains a
# bogus message that claims the encoding the file declared was
# unknown.
reporter.unexpectedError(filename, 'problem decoding source')
else:
reporter.syntaxError(filename, msg, lineno, offset, text)
return 1
except Exception:
reporter.unexpectedError(filename, 'problem decoding source')
return 1
# Okay, it's syntactically valid. Now check it.
file_tokens = checker.make_tokens(codeString)
w = checker.Checker(tree, file_tokens=file_tokens, filename=filename)
w.messages.sort(key=lambda m: m.lineno)
for warning in w.messages:
reporter.flake(warning)
return len(w.messages) | Check the Python source given by C{codeString} for flakes.
@param codeString: The Python source to check.
@type codeString: C{str}
@param filename: The name of the file the source came from, used to report
errors.
@type filename: C{str}
@param reporter: A L{Reporter} instance, where errors and warnings will be
reported.
@return: The number of warnings emitted.
@rtype: C{int} | train | https://github.com/PyCQA/pyflakes/blob/232cb1d27ee134bf96adc8f37e53589dc259b159/pyflakes/api.py#L20-L78 | [
"def _makeDefaultReporter():\n \"\"\"\n Make a reporter that can be used when no reporter is specified.\n \"\"\"\n return Reporter(sys.stdout, sys.stderr)\n",
"def make_tokens(code):\n # PY3: tokenize.tokenize requires readline of bytes\n if not isinstance(code, bytes):\n code = code.encode('UTF-8')\n lines = iter(code.splitlines(True))\n # next(lines, b'') is to prevent an error in pypy3\n return tuple(tokenize_tokenize(lambda: next(lines, b'')))\n",
"def unexpectedError(self, filename, msg):\n \"\"\"\n An unexpected error occurred trying to process C{filename}.\n\n @param filename: The path to a file that we could not process.\n @ptype filename: C{unicode}\n @param msg: A message explaining the problem.\n @ptype msg: C{unicode}\n \"\"\"\n self._stderr.write(\"%s: %s\\n\" % (filename, msg))\n",
"def syntaxError(self, filename, msg, lineno, offset, text):\n \"\"\"\n There was a syntax error in C{filename}.\n\n @param filename: The path to the file with the syntax error.\n @ptype filename: C{unicode}\n @param msg: An explanation of the syntax error.\n @ptype msg: C{unicode}\n @param lineno: The line number where the syntax error occurred.\n @ptype lineno: C{int}\n @param offset: The column on which the syntax error occurred, or None.\n @ptype offset: C{int}\n @param text: The source code containing the syntax error.\n @ptype text: C{unicode}\n \"\"\"\n line = text.splitlines()[-1]\n if offset is not None:\n if sys.version_info < (3, 8):\n offset = offset - (len(text) - len(line)) + 1\n self._stderr.write('%s:%d:%d: %s\\n' %\n (filename, lineno, offset, msg))\n else:\n self._stderr.write('%s:%d: %s\\n' % (filename, lineno, msg))\n self._stderr.write(line)\n self._stderr.write('\\n')\n if offset is not None:\n self._stderr.write(re.sub(r'\\S', ' ', line[:offset - 1]) +\n \"^\\n\")\n",
"def flake(self, message):\n \"\"\"\n pyflakes found something wrong with the code.\n\n @param: A L{pyflakes.messages.Message}.\n \"\"\"\n self._stdout.write(str(message))\n self._stdout.write('\\n')\n"
] | """
API for the command-line I{pyflakes} tool.
"""
from __future__ import with_statement
import ast
import os
import platform
import re
import sys
from pyflakes import checker, __version__
from pyflakes import reporter as modReporter
__all__ = ['check', 'checkPath', 'checkRecursive', 'iterSourceCode', 'main']
PYTHON_SHEBANG_REGEX = re.compile(br'^#!.*\bpython[23w]?\b\s*$')
def checkPath(filename, reporter=None):
"""
Check the given path, printing out any warnings detected.
@param reporter: A L{Reporter} instance, where errors and warnings will be
reported.
@return: the number of warnings printed
"""
if reporter is None:
reporter = modReporter._makeDefaultReporter()
try:
with open(filename, 'rb') as f:
codestr = f.read()
except IOError:
msg = sys.exc_info()[1]
reporter.unexpectedError(filename, msg.args[1])
return 1
return check(codestr, filename, reporter)
def isPythonFile(filename):
"""Return True if filename points to a Python file."""
if filename.endswith('.py'):
return True
# Avoid obvious Emacs backup files
if filename.endswith("~"):
return False
max_bytes = 128
try:
with open(filename, 'rb') as f:
text = f.read(max_bytes)
if not text:
return False
except IOError:
return False
first_line = text.splitlines()[0]
return PYTHON_SHEBANG_REGEX.match(first_line)
def iterSourceCode(paths):
"""
Iterate over all Python source files in C{paths}.
@param paths: A list of paths. Directories will be recursed into and
any .py files found will be yielded. Any non-directories will be
yielded as-is.
"""
for path in paths:
if os.path.isdir(path):
for dirpath, dirnames, filenames in os.walk(path):
for filename in filenames:
full_path = os.path.join(dirpath, filename)
if isPythonFile(full_path):
yield full_path
else:
yield path
def checkRecursive(paths, reporter):
"""
Recursively check all source files in C{paths}.
@param paths: A list of paths to Python source files and directories
containing Python source files.
@param reporter: A L{Reporter} where all of the warnings and errors
will be reported to.
@return: The number of warnings found.
"""
warnings = 0
for sourcePath in iterSourceCode(paths):
warnings += checkPath(sourcePath, reporter)
return warnings
def _exitOnSignal(sigName, message):
"""Handles a signal with sys.exit.
Some of these signals (SIGPIPE, for example) don't exist or are invalid on
Windows. So, ignore errors that might arise.
"""
import signal
try:
sigNumber = getattr(signal, sigName)
except AttributeError:
# the signal constants defined in the signal module are defined by
# whether the C library supports them or not. So, SIGPIPE might not
# even be defined.
return
def handler(sig, f):
sys.exit(message)
try:
signal.signal(sigNumber, handler)
except ValueError:
# It's also possible the signal is defined, but then it's invalid. In
# this case, signal.signal raises ValueError.
pass
def _get_version():
"""
Retrieve and format package version along with python version & OS used
"""
return ('%s Python %s on %s' %
(__version__, platform.python_version(), platform.system()))
def main(prog=None, args=None):
"""Entry point for the script "pyflakes"."""
import optparse
# Handle "Keyboard Interrupt" and "Broken pipe" gracefully
_exitOnSignal('SIGINT', '... stopped')
_exitOnSignal('SIGPIPE', 1)
parser = optparse.OptionParser(prog=prog, version=_get_version())
(__, args) = parser.parse_args(args=args)
reporter = modReporter._makeDefaultReporter()
if args:
warnings = checkRecursive(args, reporter)
else:
warnings = check(sys.stdin.read(), '<stdin>', reporter)
raise SystemExit(warnings > 0)
|
PyCQA/pyflakes | pyflakes/api.py | checkPath | python | def checkPath(filename, reporter=None):
if reporter is None:
reporter = modReporter._makeDefaultReporter()
try:
with open(filename, 'rb') as f:
codestr = f.read()
except IOError:
msg = sys.exc_info()[1]
reporter.unexpectedError(filename, msg.args[1])
return 1
return check(codestr, filename, reporter) | Check the given path, printing out any warnings detected.
@param reporter: A L{Reporter} instance, where errors and warnings will be
reported.
@return: the number of warnings printed | train | https://github.com/PyCQA/pyflakes/blob/232cb1d27ee134bf96adc8f37e53589dc259b159/pyflakes/api.py#L81-L99 | [
"def check(codeString, filename, reporter=None):\n \"\"\"\n Check the Python source given by C{codeString} for flakes.\n\n @param codeString: The Python source to check.\n @type codeString: C{str}\n\n @param filename: The name of the file the source came from, used to report\n errors.\n @type filename: C{str}\n\n @param reporter: A L{Reporter} instance, where errors and warnings will be\n reported.\n\n @return: The number of warnings emitted.\n @rtype: C{int}\n \"\"\"\n if reporter is None:\n reporter = modReporter._makeDefaultReporter()\n # First, compile into an AST and handle syntax errors.\n try:\n tree = ast.parse(codeString, filename=filename)\n except SyntaxError:\n value = sys.exc_info()[1]\n msg = value.args[0]\n\n (lineno, offset, text) = value.lineno, value.offset, value.text\n\n if checker.PYPY:\n if text is None:\n lines = codeString.splitlines()\n if len(lines) >= lineno:\n text = lines[lineno - 1]\n if sys.version_info >= (3, ) and isinstance(text, bytes):\n try:\n text = text.decode('ascii')\n except UnicodeDecodeError:\n text = None\n offset -= 1\n\n # If there's an encoding problem with the file, the text is None.\n if text is None:\n # Avoid using msg, since for the only known case, it contains a\n # bogus message that claims the encoding the file declared was\n # unknown.\n reporter.unexpectedError(filename, 'problem decoding source')\n else:\n reporter.syntaxError(filename, msg, lineno, offset, text)\n return 1\n except Exception:\n reporter.unexpectedError(filename, 'problem decoding source')\n return 1\n # Okay, it's syntactically valid. Now check it.\n file_tokens = checker.make_tokens(codeString)\n w = checker.Checker(tree, file_tokens=file_tokens, filename=filename)\n w.messages.sort(key=lambda m: m.lineno)\n for warning in w.messages:\n reporter.flake(warning)\n return len(w.messages)\n",
"def _makeDefaultReporter():\n \"\"\"\n Make a reporter that can be used when no reporter is specified.\n \"\"\"\n return Reporter(sys.stdout, sys.stderr)\n",
"def unexpectedError(self, filename, msg):\n \"\"\"\n An unexpected error occurred trying to process C{filename}.\n\n @param filename: The path to a file that we could not process.\n @ptype filename: C{unicode}\n @param msg: A message explaining the problem.\n @ptype msg: C{unicode}\n \"\"\"\n self._stderr.write(\"%s: %s\\n\" % (filename, msg))\n",
"def unexpectedError(self, filename, message):\n self.log.append(('unexpectedError', filename, message))\n"
] | """
API for the command-line I{pyflakes} tool.
"""
from __future__ import with_statement
import ast
import os
import platform
import re
import sys
from pyflakes import checker, __version__
from pyflakes import reporter as modReporter
__all__ = ['check', 'checkPath', 'checkRecursive', 'iterSourceCode', 'main']
PYTHON_SHEBANG_REGEX = re.compile(br'^#!.*\bpython[23w]?\b\s*$')
def check(codeString, filename, reporter=None):
"""
Check the Python source given by C{codeString} for flakes.
@param codeString: The Python source to check.
@type codeString: C{str}
@param filename: The name of the file the source came from, used to report
errors.
@type filename: C{str}
@param reporter: A L{Reporter} instance, where errors and warnings will be
reported.
@return: The number of warnings emitted.
@rtype: C{int}
"""
if reporter is None:
reporter = modReporter._makeDefaultReporter()
# First, compile into an AST and handle syntax errors.
try:
tree = ast.parse(codeString, filename=filename)
except SyntaxError:
value = sys.exc_info()[1]
msg = value.args[0]
(lineno, offset, text) = value.lineno, value.offset, value.text
if checker.PYPY:
if text is None:
lines = codeString.splitlines()
if len(lines) >= lineno:
text = lines[lineno - 1]
if sys.version_info >= (3, ) and isinstance(text, bytes):
try:
text = text.decode('ascii')
except UnicodeDecodeError:
text = None
offset -= 1
# If there's an encoding problem with the file, the text is None.
if text is None:
# Avoid using msg, since for the only known case, it contains a
# bogus message that claims the encoding the file declared was
# unknown.
reporter.unexpectedError(filename, 'problem decoding source')
else:
reporter.syntaxError(filename, msg, lineno, offset, text)
return 1
except Exception:
reporter.unexpectedError(filename, 'problem decoding source')
return 1
# Okay, it's syntactically valid. Now check it.
file_tokens = checker.make_tokens(codeString)
w = checker.Checker(tree, file_tokens=file_tokens, filename=filename)
w.messages.sort(key=lambda m: m.lineno)
for warning in w.messages:
reporter.flake(warning)
return len(w.messages)
def isPythonFile(filename):
"""Return True if filename points to a Python file."""
if filename.endswith('.py'):
return True
# Avoid obvious Emacs backup files
if filename.endswith("~"):
return False
max_bytes = 128
try:
with open(filename, 'rb') as f:
text = f.read(max_bytes)
if not text:
return False
except IOError:
return False
first_line = text.splitlines()[0]
return PYTHON_SHEBANG_REGEX.match(first_line)
def iterSourceCode(paths):
"""
Iterate over all Python source files in C{paths}.
@param paths: A list of paths. Directories will be recursed into and
any .py files found will be yielded. Any non-directories will be
yielded as-is.
"""
for path in paths:
if os.path.isdir(path):
for dirpath, dirnames, filenames in os.walk(path):
for filename in filenames:
full_path = os.path.join(dirpath, filename)
if isPythonFile(full_path):
yield full_path
else:
yield path
def checkRecursive(paths, reporter):
"""
Recursively check all source files in C{paths}.
@param paths: A list of paths to Python source files and directories
containing Python source files.
@param reporter: A L{Reporter} where all of the warnings and errors
will be reported to.
@return: The number of warnings found.
"""
warnings = 0
for sourcePath in iterSourceCode(paths):
warnings += checkPath(sourcePath, reporter)
return warnings
def _exitOnSignal(sigName, message):
"""Handles a signal with sys.exit.
Some of these signals (SIGPIPE, for example) don't exist or are invalid on
Windows. So, ignore errors that might arise.
"""
import signal
try:
sigNumber = getattr(signal, sigName)
except AttributeError:
# the signal constants defined in the signal module are defined by
# whether the C library supports them or not. So, SIGPIPE might not
# even be defined.
return
def handler(sig, f):
sys.exit(message)
try:
signal.signal(sigNumber, handler)
except ValueError:
# It's also possible the signal is defined, but then it's invalid. In
# this case, signal.signal raises ValueError.
pass
def _get_version():
"""
Retrieve and format package version along with python version & OS used
"""
return ('%s Python %s on %s' %
(__version__, platform.python_version(), platform.system()))
def main(prog=None, args=None):
"""Entry point for the script "pyflakes"."""
import optparse
# Handle "Keyboard Interrupt" and "Broken pipe" gracefully
_exitOnSignal('SIGINT', '... stopped')
_exitOnSignal('SIGPIPE', 1)
parser = optparse.OptionParser(prog=prog, version=_get_version())
(__, args) = parser.parse_args(args=args)
reporter = modReporter._makeDefaultReporter()
if args:
warnings = checkRecursive(args, reporter)
else:
warnings = check(sys.stdin.read(), '<stdin>', reporter)
raise SystemExit(warnings > 0)
|
PyCQA/pyflakes | pyflakes/api.py | isPythonFile | python | def isPythonFile(filename):
if filename.endswith('.py'):
return True
# Avoid obvious Emacs backup files
if filename.endswith("~"):
return False
max_bytes = 128
try:
with open(filename, 'rb') as f:
text = f.read(max_bytes)
if not text:
return False
except IOError:
return False
first_line = text.splitlines()[0]
return PYTHON_SHEBANG_REGEX.match(first_line) | Return True if filename points to a Python file. | train | https://github.com/PyCQA/pyflakes/blob/232cb1d27ee134bf96adc8f37e53589dc259b159/pyflakes/api.py#L102-L122 | null | """
API for the command-line I{pyflakes} tool.
"""
from __future__ import with_statement
import ast
import os
import platform
import re
import sys
from pyflakes import checker, __version__
from pyflakes import reporter as modReporter
__all__ = ['check', 'checkPath', 'checkRecursive', 'iterSourceCode', 'main']
PYTHON_SHEBANG_REGEX = re.compile(br'^#!.*\bpython[23w]?\b\s*$')
def check(codeString, filename, reporter=None):
"""
Check the Python source given by C{codeString} for flakes.
@param codeString: The Python source to check.
@type codeString: C{str}
@param filename: The name of the file the source came from, used to report
errors.
@type filename: C{str}
@param reporter: A L{Reporter} instance, where errors and warnings will be
reported.
@return: The number of warnings emitted.
@rtype: C{int}
"""
if reporter is None:
reporter = modReporter._makeDefaultReporter()
# First, compile into an AST and handle syntax errors.
try:
tree = ast.parse(codeString, filename=filename)
except SyntaxError:
value = sys.exc_info()[1]
msg = value.args[0]
(lineno, offset, text) = value.lineno, value.offset, value.text
if checker.PYPY:
if text is None:
lines = codeString.splitlines()
if len(lines) >= lineno:
text = lines[lineno - 1]
if sys.version_info >= (3, ) and isinstance(text, bytes):
try:
text = text.decode('ascii')
except UnicodeDecodeError:
text = None
offset -= 1
# If there's an encoding problem with the file, the text is None.
if text is None:
# Avoid using msg, since for the only known case, it contains a
# bogus message that claims the encoding the file declared was
# unknown.
reporter.unexpectedError(filename, 'problem decoding source')
else:
reporter.syntaxError(filename, msg, lineno, offset, text)
return 1
except Exception:
reporter.unexpectedError(filename, 'problem decoding source')
return 1
# Okay, it's syntactically valid. Now check it.
file_tokens = checker.make_tokens(codeString)
w = checker.Checker(tree, file_tokens=file_tokens, filename=filename)
w.messages.sort(key=lambda m: m.lineno)
for warning in w.messages:
reporter.flake(warning)
return len(w.messages)
def checkPath(filename, reporter=None):
"""
Check the given path, printing out any warnings detected.
@param reporter: A L{Reporter} instance, where errors and warnings will be
reported.
@return: the number of warnings printed
"""
if reporter is None:
reporter = modReporter._makeDefaultReporter()
try:
with open(filename, 'rb') as f:
codestr = f.read()
except IOError:
msg = sys.exc_info()[1]
reporter.unexpectedError(filename, msg.args[1])
return 1
return check(codestr, filename, reporter)
def iterSourceCode(paths):
"""
Iterate over all Python source files in C{paths}.
@param paths: A list of paths. Directories will be recursed into and
any .py files found will be yielded. Any non-directories will be
yielded as-is.
"""
for path in paths:
if os.path.isdir(path):
for dirpath, dirnames, filenames in os.walk(path):
for filename in filenames:
full_path = os.path.join(dirpath, filename)
if isPythonFile(full_path):
yield full_path
else:
yield path
def checkRecursive(paths, reporter):
"""
Recursively check all source files in C{paths}.
@param paths: A list of paths to Python source files and directories
containing Python source files.
@param reporter: A L{Reporter} where all of the warnings and errors
will be reported to.
@return: The number of warnings found.
"""
warnings = 0
for sourcePath in iterSourceCode(paths):
warnings += checkPath(sourcePath, reporter)
return warnings
def _exitOnSignal(sigName, message):
"""Handles a signal with sys.exit.
Some of these signals (SIGPIPE, for example) don't exist or are invalid on
Windows. So, ignore errors that might arise.
"""
import signal
try:
sigNumber = getattr(signal, sigName)
except AttributeError:
# the signal constants defined in the signal module are defined by
# whether the C library supports them or not. So, SIGPIPE might not
# even be defined.
return
def handler(sig, f):
sys.exit(message)
try:
signal.signal(sigNumber, handler)
except ValueError:
# It's also possible the signal is defined, but then it's invalid. In
# this case, signal.signal raises ValueError.
pass
def _get_version():
"""
Retrieve and format package version along with python version & OS used
"""
return ('%s Python %s on %s' %
(__version__, platform.python_version(), platform.system()))
def main(prog=None, args=None):
"""Entry point for the script "pyflakes"."""
import optparse
# Handle "Keyboard Interrupt" and "Broken pipe" gracefully
_exitOnSignal('SIGINT', '... stopped')
_exitOnSignal('SIGPIPE', 1)
parser = optparse.OptionParser(prog=prog, version=_get_version())
(__, args) = parser.parse_args(args=args)
reporter = modReporter._makeDefaultReporter()
if args:
warnings = checkRecursive(args, reporter)
else:
warnings = check(sys.stdin.read(), '<stdin>', reporter)
raise SystemExit(warnings > 0)
|
PyCQA/pyflakes | pyflakes/api.py | iterSourceCode | python | def iterSourceCode(paths):
for path in paths:
if os.path.isdir(path):
for dirpath, dirnames, filenames in os.walk(path):
for filename in filenames:
full_path = os.path.join(dirpath, filename)
if isPythonFile(full_path):
yield full_path
else:
yield path | Iterate over all Python source files in C{paths}.
@param paths: A list of paths. Directories will be recursed into and
any .py files found will be yielded. Any non-directories will be
yielded as-is. | train | https://github.com/PyCQA/pyflakes/blob/232cb1d27ee134bf96adc8f37e53589dc259b159/pyflakes/api.py#L125-L141 | [
"def isPythonFile(filename):\n \"\"\"Return True if filename points to a Python file.\"\"\"\n if filename.endswith('.py'):\n return True\n\n # Avoid obvious Emacs backup files\n if filename.endswith(\"~\"):\n return False\n\n max_bytes = 128\n\n try:\n with open(filename, 'rb') as f:\n text = f.read(max_bytes)\n if not text:\n return False\n except IOError:\n return False\n\n first_line = text.splitlines()[0]\n return PYTHON_SHEBANG_REGEX.match(first_line)\n"
] | """
API for the command-line I{pyflakes} tool.
"""
from __future__ import with_statement
import ast
import os
import platform
import re
import sys
from pyflakes import checker, __version__
from pyflakes import reporter as modReporter
__all__ = ['check', 'checkPath', 'checkRecursive', 'iterSourceCode', 'main']
PYTHON_SHEBANG_REGEX = re.compile(br'^#!.*\bpython[23w]?\b\s*$')
def check(codeString, filename, reporter=None):
"""
Check the Python source given by C{codeString} for flakes.
@param codeString: The Python source to check.
@type codeString: C{str}
@param filename: The name of the file the source came from, used to report
errors.
@type filename: C{str}
@param reporter: A L{Reporter} instance, where errors and warnings will be
reported.
@return: The number of warnings emitted.
@rtype: C{int}
"""
if reporter is None:
reporter = modReporter._makeDefaultReporter()
# First, compile into an AST and handle syntax errors.
try:
tree = ast.parse(codeString, filename=filename)
except SyntaxError:
value = sys.exc_info()[1]
msg = value.args[0]
(lineno, offset, text) = value.lineno, value.offset, value.text
if checker.PYPY:
if text is None:
lines = codeString.splitlines()
if len(lines) >= lineno:
text = lines[lineno - 1]
if sys.version_info >= (3, ) and isinstance(text, bytes):
try:
text = text.decode('ascii')
except UnicodeDecodeError:
text = None
offset -= 1
# If there's an encoding problem with the file, the text is None.
if text is None:
# Avoid using msg, since for the only known case, it contains a
# bogus message that claims the encoding the file declared was
# unknown.
reporter.unexpectedError(filename, 'problem decoding source')
else:
reporter.syntaxError(filename, msg, lineno, offset, text)
return 1
except Exception:
reporter.unexpectedError(filename, 'problem decoding source')
return 1
# Okay, it's syntactically valid. Now check it.
file_tokens = checker.make_tokens(codeString)
w = checker.Checker(tree, file_tokens=file_tokens, filename=filename)
w.messages.sort(key=lambda m: m.lineno)
for warning in w.messages:
reporter.flake(warning)
return len(w.messages)
def checkPath(filename, reporter=None):
"""
Check the given path, printing out any warnings detected.
@param reporter: A L{Reporter} instance, where errors and warnings will be
reported.
@return: the number of warnings printed
"""
if reporter is None:
reporter = modReporter._makeDefaultReporter()
try:
with open(filename, 'rb') as f:
codestr = f.read()
except IOError:
msg = sys.exc_info()[1]
reporter.unexpectedError(filename, msg.args[1])
return 1
return check(codestr, filename, reporter)
def isPythonFile(filename):
"""Return True if filename points to a Python file."""
if filename.endswith('.py'):
return True
# Avoid obvious Emacs backup files
if filename.endswith("~"):
return False
max_bytes = 128
try:
with open(filename, 'rb') as f:
text = f.read(max_bytes)
if not text:
return False
except IOError:
return False
first_line = text.splitlines()[0]
return PYTHON_SHEBANG_REGEX.match(first_line)
def checkRecursive(paths, reporter):
"""
Recursively check all source files in C{paths}.
@param paths: A list of paths to Python source files and directories
containing Python source files.
@param reporter: A L{Reporter} where all of the warnings and errors
will be reported to.
@return: The number of warnings found.
"""
warnings = 0
for sourcePath in iterSourceCode(paths):
warnings += checkPath(sourcePath, reporter)
return warnings
def _exitOnSignal(sigName, message):
"""Handles a signal with sys.exit.
Some of these signals (SIGPIPE, for example) don't exist or are invalid on
Windows. So, ignore errors that might arise.
"""
import signal
try:
sigNumber = getattr(signal, sigName)
except AttributeError:
# the signal constants defined in the signal module are defined by
# whether the C library supports them or not. So, SIGPIPE might not
# even be defined.
return
def handler(sig, f):
sys.exit(message)
try:
signal.signal(sigNumber, handler)
except ValueError:
# It's also possible the signal is defined, but then it's invalid. In
# this case, signal.signal raises ValueError.
pass
def _get_version():
"""
Retrieve and format package version along with python version & OS used
"""
return ('%s Python %s on %s' %
(__version__, platform.python_version(), platform.system()))
def main(prog=None, args=None):
"""Entry point for the script "pyflakes"."""
import optparse
# Handle "Keyboard Interrupt" and "Broken pipe" gracefully
_exitOnSignal('SIGINT', '... stopped')
_exitOnSignal('SIGPIPE', 1)
parser = optparse.OptionParser(prog=prog, version=_get_version())
(__, args) = parser.parse_args(args=args)
reporter = modReporter._makeDefaultReporter()
if args:
warnings = checkRecursive(args, reporter)
else:
warnings = check(sys.stdin.read(), '<stdin>', reporter)
raise SystemExit(warnings > 0)
|
PyCQA/pyflakes | pyflakes/api.py | checkRecursive | python | def checkRecursive(paths, reporter):
warnings = 0
for sourcePath in iterSourceCode(paths):
warnings += checkPath(sourcePath, reporter)
return warnings | Recursively check all source files in C{paths}.
@param paths: A list of paths to Python source files and directories
containing Python source files.
@param reporter: A L{Reporter} where all of the warnings and errors
will be reported to.
@return: The number of warnings found. | train | https://github.com/PyCQA/pyflakes/blob/232cb1d27ee134bf96adc8f37e53589dc259b159/pyflakes/api.py#L144-L157 | [
"def checkPath(filename, reporter=None):\n \"\"\"\n Check the given path, printing out any warnings detected.\n\n @param reporter: A L{Reporter} instance, where errors and warnings will be\n reported.\n\n @return: the number of warnings printed\n \"\"\"\n if reporter is None:\n reporter = modReporter._makeDefaultReporter()\n try:\n with open(filename, 'rb') as f:\n codestr = f.read()\n except IOError:\n msg = sys.exc_info()[1]\n reporter.unexpectedError(filename, msg.args[1])\n return 1\n return check(codestr, filename, reporter)\n",
"def iterSourceCode(paths):\n \"\"\"\n Iterate over all Python source files in C{paths}.\n\n @param paths: A list of paths. Directories will be recursed into and\n any .py files found will be yielded. Any non-directories will be\n yielded as-is.\n \"\"\"\n for path in paths:\n if os.path.isdir(path):\n for dirpath, dirnames, filenames in os.walk(path):\n for filename in filenames:\n full_path = os.path.join(dirpath, filename)\n if isPythonFile(full_path):\n yield full_path\n else:\n yield path\n"
] | """
API for the command-line I{pyflakes} tool.
"""
from __future__ import with_statement
import ast
import os
import platform
import re
import sys
from pyflakes import checker, __version__
from pyflakes import reporter as modReporter
__all__ = ['check', 'checkPath', 'checkRecursive', 'iterSourceCode', 'main']
PYTHON_SHEBANG_REGEX = re.compile(br'^#!.*\bpython[23w]?\b\s*$')
def check(codeString, filename, reporter=None):
"""
Check the Python source given by C{codeString} for flakes.
@param codeString: The Python source to check.
@type codeString: C{str}
@param filename: The name of the file the source came from, used to report
errors.
@type filename: C{str}
@param reporter: A L{Reporter} instance, where errors and warnings will be
reported.
@return: The number of warnings emitted.
@rtype: C{int}
"""
if reporter is None:
reporter = modReporter._makeDefaultReporter()
# First, compile into an AST and handle syntax errors.
try:
tree = ast.parse(codeString, filename=filename)
except SyntaxError:
value = sys.exc_info()[1]
msg = value.args[0]
(lineno, offset, text) = value.lineno, value.offset, value.text
if checker.PYPY:
if text is None:
lines = codeString.splitlines()
if len(lines) >= lineno:
text = lines[lineno - 1]
if sys.version_info >= (3, ) and isinstance(text, bytes):
try:
text = text.decode('ascii')
except UnicodeDecodeError:
text = None
offset -= 1
# If there's an encoding problem with the file, the text is None.
if text is None:
# Avoid using msg, since for the only known case, it contains a
# bogus message that claims the encoding the file declared was
# unknown.
reporter.unexpectedError(filename, 'problem decoding source')
else:
reporter.syntaxError(filename, msg, lineno, offset, text)
return 1
except Exception:
reporter.unexpectedError(filename, 'problem decoding source')
return 1
# Okay, it's syntactically valid. Now check it.
file_tokens = checker.make_tokens(codeString)
w = checker.Checker(tree, file_tokens=file_tokens, filename=filename)
w.messages.sort(key=lambda m: m.lineno)
for warning in w.messages:
reporter.flake(warning)
return len(w.messages)
def checkPath(filename, reporter=None):
"""
Check the given path, printing out any warnings detected.
@param reporter: A L{Reporter} instance, where errors and warnings will be
reported.
@return: the number of warnings printed
"""
if reporter is None:
reporter = modReporter._makeDefaultReporter()
try:
with open(filename, 'rb') as f:
codestr = f.read()
except IOError:
msg = sys.exc_info()[1]
reporter.unexpectedError(filename, msg.args[1])
return 1
return check(codestr, filename, reporter)
def isPythonFile(filename):
"""Return True if filename points to a Python file."""
if filename.endswith('.py'):
return True
# Avoid obvious Emacs backup files
if filename.endswith("~"):
return False
max_bytes = 128
try:
with open(filename, 'rb') as f:
text = f.read(max_bytes)
if not text:
return False
except IOError:
return False
first_line = text.splitlines()[0]
return PYTHON_SHEBANG_REGEX.match(first_line)
def iterSourceCode(paths):
"""
Iterate over all Python source files in C{paths}.
@param paths: A list of paths. Directories will be recursed into and
any .py files found will be yielded. Any non-directories will be
yielded as-is.
"""
for path in paths:
if os.path.isdir(path):
for dirpath, dirnames, filenames in os.walk(path):
for filename in filenames:
full_path = os.path.join(dirpath, filename)
if isPythonFile(full_path):
yield full_path
else:
yield path
def _exitOnSignal(sigName, message):
"""Handles a signal with sys.exit.
Some of these signals (SIGPIPE, for example) don't exist or are invalid on
Windows. So, ignore errors that might arise.
"""
import signal
try:
sigNumber = getattr(signal, sigName)
except AttributeError:
# the signal constants defined in the signal module are defined by
# whether the C library supports them or not. So, SIGPIPE might not
# even be defined.
return
def handler(sig, f):
sys.exit(message)
try:
signal.signal(sigNumber, handler)
except ValueError:
# It's also possible the signal is defined, but then it's invalid. In
# this case, signal.signal raises ValueError.
pass
def _get_version():
"""
Retrieve and format package version along with python version & OS used
"""
return ('%s Python %s on %s' %
(__version__, platform.python_version(), platform.system()))
def main(prog=None, args=None):
"""Entry point for the script "pyflakes"."""
import optparse
# Handle "Keyboard Interrupt" and "Broken pipe" gracefully
_exitOnSignal('SIGINT', '... stopped')
_exitOnSignal('SIGPIPE', 1)
parser = optparse.OptionParser(prog=prog, version=_get_version())
(__, args) = parser.parse_args(args=args)
reporter = modReporter._makeDefaultReporter()
if args:
warnings = checkRecursive(args, reporter)
else:
warnings = check(sys.stdin.read(), '<stdin>', reporter)
raise SystemExit(warnings > 0)
|
PyCQA/pyflakes | pyflakes/api.py | _exitOnSignal | python | def _exitOnSignal(sigName, message):
import signal
try:
sigNumber = getattr(signal, sigName)
except AttributeError:
# the signal constants defined in the signal module are defined by
# whether the C library supports them or not. So, SIGPIPE might not
# even be defined.
return
def handler(sig, f):
sys.exit(message)
try:
signal.signal(sigNumber, handler)
except ValueError:
# It's also possible the signal is defined, but then it's invalid. In
# this case, signal.signal raises ValueError.
pass | Handles a signal with sys.exit.
Some of these signals (SIGPIPE, for example) don't exist or are invalid on
Windows. So, ignore errors that might arise. | train | https://github.com/PyCQA/pyflakes/blob/232cb1d27ee134bf96adc8f37e53589dc259b159/pyflakes/api.py#L160-L184 | null | """
API for the command-line I{pyflakes} tool.
"""
from __future__ import with_statement
import ast
import os
import platform
import re
import sys
from pyflakes import checker, __version__
from pyflakes import reporter as modReporter
__all__ = ['check', 'checkPath', 'checkRecursive', 'iterSourceCode', 'main']
PYTHON_SHEBANG_REGEX = re.compile(br'^#!.*\bpython[23w]?\b\s*$')
def check(codeString, filename, reporter=None):
"""
Check the Python source given by C{codeString} for flakes.
@param codeString: The Python source to check.
@type codeString: C{str}
@param filename: The name of the file the source came from, used to report
errors.
@type filename: C{str}
@param reporter: A L{Reporter} instance, where errors and warnings will be
reported.
@return: The number of warnings emitted.
@rtype: C{int}
"""
if reporter is None:
reporter = modReporter._makeDefaultReporter()
# First, compile into an AST and handle syntax errors.
try:
tree = ast.parse(codeString, filename=filename)
except SyntaxError:
value = sys.exc_info()[1]
msg = value.args[0]
(lineno, offset, text) = value.lineno, value.offset, value.text
if checker.PYPY:
if text is None:
lines = codeString.splitlines()
if len(lines) >= lineno:
text = lines[lineno - 1]
if sys.version_info >= (3, ) and isinstance(text, bytes):
try:
text = text.decode('ascii')
except UnicodeDecodeError:
text = None
offset -= 1
# If there's an encoding problem with the file, the text is None.
if text is None:
# Avoid using msg, since for the only known case, it contains a
# bogus message that claims the encoding the file declared was
# unknown.
reporter.unexpectedError(filename, 'problem decoding source')
else:
reporter.syntaxError(filename, msg, lineno, offset, text)
return 1
except Exception:
reporter.unexpectedError(filename, 'problem decoding source')
return 1
# Okay, it's syntactically valid. Now check it.
file_tokens = checker.make_tokens(codeString)
w = checker.Checker(tree, file_tokens=file_tokens, filename=filename)
w.messages.sort(key=lambda m: m.lineno)
for warning in w.messages:
reporter.flake(warning)
return len(w.messages)
def checkPath(filename, reporter=None):
"""
Check the given path, printing out any warnings detected.
@param reporter: A L{Reporter} instance, where errors and warnings will be
reported.
@return: the number of warnings printed
"""
if reporter is None:
reporter = modReporter._makeDefaultReporter()
try:
with open(filename, 'rb') as f:
codestr = f.read()
except IOError:
msg = sys.exc_info()[1]
reporter.unexpectedError(filename, msg.args[1])
return 1
return check(codestr, filename, reporter)
def isPythonFile(filename):
"""Return True if filename points to a Python file."""
if filename.endswith('.py'):
return True
# Avoid obvious Emacs backup files
if filename.endswith("~"):
return False
max_bytes = 128
try:
with open(filename, 'rb') as f:
text = f.read(max_bytes)
if not text:
return False
except IOError:
return False
first_line = text.splitlines()[0]
return PYTHON_SHEBANG_REGEX.match(first_line)
def iterSourceCode(paths):
"""
Iterate over all Python source files in C{paths}.
@param paths: A list of paths. Directories will be recursed into and
any .py files found will be yielded. Any non-directories will be
yielded as-is.
"""
for path in paths:
if os.path.isdir(path):
for dirpath, dirnames, filenames in os.walk(path):
for filename in filenames:
full_path = os.path.join(dirpath, filename)
if isPythonFile(full_path):
yield full_path
else:
yield path
def checkRecursive(paths, reporter):
"""
Recursively check all source files in C{paths}.
@param paths: A list of paths to Python source files and directories
containing Python source files.
@param reporter: A L{Reporter} where all of the warnings and errors
will be reported to.
@return: The number of warnings found.
"""
warnings = 0
for sourcePath in iterSourceCode(paths):
warnings += checkPath(sourcePath, reporter)
return warnings
def _get_version():
"""
Retrieve and format package version along with python version & OS used
"""
return ('%s Python %s on %s' %
(__version__, platform.python_version(), platform.system()))
def main(prog=None, args=None):
"""Entry point for the script "pyflakes"."""
import optparse
# Handle "Keyboard Interrupt" and "Broken pipe" gracefully
_exitOnSignal('SIGINT', '... stopped')
_exitOnSignal('SIGPIPE', 1)
parser = optparse.OptionParser(prog=prog, version=_get_version())
(__, args) = parser.parse_args(args=args)
reporter = modReporter._makeDefaultReporter()
if args:
warnings = checkRecursive(args, reporter)
else:
warnings = check(sys.stdin.read(), '<stdin>', reporter)
raise SystemExit(warnings > 0)
|
nicodv/kmodes | kmodes/kmodes.py | init_huang | python | def init_huang(X, n_clusters, dissim, random_state):
n_attrs = X.shape[1]
centroids = np.empty((n_clusters, n_attrs), dtype='object')
# determine frequencies of attributes
for iattr in range(n_attrs):
freq = defaultdict(int)
for curattr in X[:, iattr]:
freq[curattr] += 1
# Sample centroids using the probabilities of attributes.
# (I assume that's what's meant in the Huang [1998] paper; it works,
# at least)
# Note: sampling using population in static list with as many choices
# as frequency counts. Since the counts are small integers,
# memory consumption is low.
choices = [chc for chc, wght in freq.items() for _ in range(wght)]
# So that we are consistent between Python versions,
# each with different dict ordering.
choices = sorted(choices)
centroids[:, iattr] = random_state.choice(choices, n_clusters)
# The previously chosen centroids could result in empty clusters,
# so set centroid to closest point in X.
for ik in range(n_clusters):
ndx = np.argsort(dissim(X, centroids[ik]))
# We want the centroid to be unique, if possible.
while np.all(X[ndx[0]] == centroids, axis=1).any() and ndx.shape[0] > 1:
ndx = np.delete(ndx, 0)
centroids[ik] = X[ndx[0]]
return centroids | Initialize centroids according to method by Huang [1997]. | train | https://github.com/nicodv/kmodes/blob/cdb19fe5448aba1bf501626694bb52e68eafab45/kmodes/kmodes.py#L21-L50 | null | """
K-modes clustering for categorical data
"""
# pylint: disable=unused-argument,attribute-defined-outside-init
from collections import defaultdict
import numpy as np
from joblib import Parallel, delayed
from scipy import sparse
from sklearn.base import BaseEstimator, ClusterMixin
from sklearn.utils import check_random_state
from sklearn.utils.validation import check_array
from .util import get_max_value_key, encode_features, get_unique_rows, \
decode_centroids, pandas_to_numpy
from .util.dissim import matching_dissim, ng_dissim
def init_cao(X, n_clusters, dissim):
"""Initialize centroids according to method by Cao et al. [2009].
Note: O(N * attr * n_clusters**2), so watch out with large n_clusters
"""
n_points, n_attrs = X.shape
centroids = np.empty((n_clusters, n_attrs), dtype='object')
# Method is based on determining density of points.
dens = np.zeros(n_points)
for iattr in range(n_attrs):
freq = defaultdict(int)
for val in X[:, iattr]:
freq[val] += 1
for ipoint in range(n_points):
dens[ipoint] += freq[X[ipoint, iattr]] / float(n_points) / float(n_attrs)
# Choose initial centroids based on distance and density.
centroids[0] = X[np.argmax(dens)]
if n_clusters > 1:
# For the remaining centroids, choose maximum dens * dissim to the
# (already assigned) centroid with the lowest dens * dissim.
for ik in range(1, n_clusters):
dd = np.empty((ik, n_points))
for ikk in range(ik):
dd[ikk] = dissim(X, centroids[ikk]) * dens
centroids[ik] = X[np.argmax(np.min(dd, axis=0))]
return centroids
def move_point_cat(point, ipoint, to_clust, from_clust, cl_attr_freq,
membship, centroids):
"""Move point between clusters, categorical attributes."""
membship[to_clust, ipoint] = 1
membship[from_clust, ipoint] = 0
# Update frequencies of attributes in cluster.
for iattr, curattr in enumerate(point):
to_attr_counts = cl_attr_freq[to_clust][iattr]
from_attr_counts = cl_attr_freq[from_clust][iattr]
# Increment the attribute count for the new "to" cluster
to_attr_counts[curattr] += 1
current_attribute_value_freq = to_attr_counts[curattr]
current_centroid_value = centroids[to_clust][iattr]
current_centroid_freq = to_attr_counts[current_centroid_value]
if current_centroid_freq < current_attribute_value_freq:
# We have incremented this value to the new mode. Update the centroid.
centroids[to_clust][iattr] = curattr
# Decrement the attribute count for the old "from" cluster
from_attr_counts[curattr] -= 1
old_centroid_value = centroids[from_clust][iattr]
if old_centroid_value == curattr:
# We have just removed a count from the old centroid value. We need to
# recalculate the centroid as it may no longer be the maximum
centroids[from_clust][iattr] = get_max_value_key(from_attr_counts)
return cl_attr_freq, membship, centroids
def _labels_cost(X, centroids, dissim, membship=None):
"""Calculate labels and cost function given a matrix of points and
a list of centroids for the k-modes algorithm.
"""
X = check_array(X)
n_points = X.shape[0]
cost = 0.
labels = np.empty(n_points, dtype=np.uint16)
for ipoint, curpoint in enumerate(X):
diss = dissim(centroids, curpoint, X=X, membship=membship)
clust = np.argmin(diss)
labels[ipoint] = clust
cost += diss[clust]
return labels, cost
def _k_modes_iter(X, centroids, cl_attr_freq, membship, dissim, random_state):
"""Single iteration of k-modes clustering algorithm"""
moves = 0
for ipoint, curpoint in enumerate(X):
clust = np.argmin(dissim(centroids, curpoint, X=X, membship=membship))
if membship[clust, ipoint]:
# Point is already in its right place.
continue
# Move point, and update old/new cluster frequencies and centroids.
moves += 1
old_clust = np.argwhere(membship[:, ipoint])[0][0]
cl_attr_freq, membship, centroids = move_point_cat(
curpoint, ipoint, clust, old_clust, cl_attr_freq, membship, centroids
)
# In case of an empty cluster, reinitialize with a random point
# from the largest cluster.
if not membship[old_clust, :].any():
from_clust = membship.sum(axis=1).argmax()
choices = [ii for ii, ch in enumerate(membship[from_clust, :]) if ch]
rindx = random_state.choice(choices)
cl_attr_freq, membship, centroids = move_point_cat(
X[rindx], rindx, old_clust, from_clust, cl_attr_freq, membship, centroids
)
return centroids, moves
def k_modes_single(X, n_clusters, n_points, n_attrs, max_iter, dissim, init, init_no,
verbose, random_state):
random_state = check_random_state(random_state)
# _____ INIT _____
if verbose:
print("Init: initializing centroids")
if isinstance(init, str) and init.lower() == 'huang':
centroids = init_huang(X, n_clusters, dissim, random_state)
elif isinstance(init, str) and init.lower() == 'cao':
centroids = init_cao(X, n_clusters, dissim)
elif isinstance(init, str) and init.lower() == 'random':
seeds = random_state.choice(range(n_points), n_clusters)
centroids = X[seeds]
elif hasattr(init, '__array__'):
# Make sure init is a 2D array.
if len(init.shape) == 1:
init = np.atleast_2d(init).T
assert init.shape[0] == n_clusters, \
"Wrong number of initial centroids in init ({}, should be {})." \
.format(init.shape[0], n_clusters)
assert init.shape[1] == n_attrs, \
"Wrong number of attributes in init ({}, should be {})." \
.format(init.shape[1], n_attrs)
centroids = np.asarray(init, dtype=np.uint16)
else:
raise NotImplementedError
if verbose:
print("Init: initializing clusters")
membship = np.zeros((n_clusters, n_points), dtype=np.uint8)
# cl_attr_freq is a list of lists with dictionaries that contain the
# frequencies of values per cluster and attribute.
cl_attr_freq = [[defaultdict(int) for _ in range(n_attrs)]
for _ in range(n_clusters)]
for ipoint, curpoint in enumerate(X):
# Initial assignment to clusters
clust = np.argmin(dissim(centroids, curpoint, X=X, membship=membship))
membship[clust, ipoint] = 1
# Count attribute values per cluster.
for iattr, curattr in enumerate(curpoint):
cl_attr_freq[clust][iattr][curattr] += 1
# Perform an initial centroid update.
for ik in range(n_clusters):
for iattr in range(n_attrs):
if sum(membship[ik]) == 0:
# Empty centroid, choose randomly
centroids[ik, iattr] = random_state.choice(X[:, iattr])
else:
centroids[ik, iattr] = get_max_value_key(cl_attr_freq[ik][iattr])
# _____ ITERATION _____
if verbose:
print("Starting iterations...")
itr = 0
labels = None
converged = False
cost = np.Inf
while itr <= max_iter and not converged:
itr += 1
centroids, moves = _k_modes_iter(
X,
centroids,
cl_attr_freq,
membship,
dissim,
random_state
)
# All points seen in this iteration
labels, ncost = _labels_cost(X, centroids, dissim, membship)
converged = (moves == 0) or (ncost >= cost)
cost = ncost
if verbose:
print("Run {}, iteration: {}/{}, moves: {}, cost: {}"
.format(init_no + 1, itr, max_iter, moves, cost))
return centroids, labels, cost, itr
def k_modes(X, n_clusters, max_iter, dissim, init, n_init, verbose, random_state, n_jobs):
"""k-modes algorithm"""
random_state = check_random_state(random_state)
if sparse.issparse(X):
raise TypeError("k-modes does not support sparse data.")
X = check_array(X, dtype=None)
# Convert the categorical values in X to integers for speed.
# Based on the unique values in X, we can make a mapping to achieve this.
X, enc_map = encode_features(X)
n_points, n_attrs = X.shape
assert n_clusters <= n_points, "Cannot have more clusters ({}) " \
"than data points ({}).".format(n_clusters, n_points)
# Are there more n_clusters than unique rows? Then set the unique
# rows as initial values and skip iteration.
unique = get_unique_rows(X)
n_unique = unique.shape[0]
if n_unique <= n_clusters:
max_iter = 0
n_init = 1
n_clusters = n_unique
init = unique
results = []
seeds = random_state.randint(np.iinfo(np.int32).max, size=n_init)
if n_jobs == 1:
for init_no in range(n_init):
results.append(k_modes_single(X, n_clusters, n_points, n_attrs, max_iter,
dissim, init, init_no, verbose, seeds[init_no]))
else:
results = Parallel(n_jobs=n_jobs, verbose=0)(
delayed(k_modes_single)(X, n_clusters, n_points, n_attrs, max_iter,
dissim, init, init_no, verbose, seed)
for init_no, seed in enumerate(seeds))
all_centroids, all_labels, all_costs, all_n_iters = zip(*results)
best = np.argmin(all_costs)
if n_init > 1 and verbose:
print("Best run was number {}".format(best + 1))
return all_centroids[best], enc_map, all_labels[best], \
all_costs[best], all_n_iters[best]
class KModes(BaseEstimator, ClusterMixin):
"""k-modes clustering algorithm for categorical data.
Parameters
-----------
n_clusters : int, optional, default: 8
The number of clusters to form as well as the number of
centroids to generate.
max_iter : int, default: 300
Maximum number of iterations of the k-modes algorithm for a
single run.
cat_dissim : func, default: matching_dissim
Dissimilarity function used by the k-modes algorithm for categorical variables.
Defaults to the matching dissimilarity function.
init : {'Huang', 'Cao', 'random' or an ndarray}, default: 'Cao'
Method for initialization:
'Huang': Method in Huang [1997, 1998]
'Cao': Method in Cao et al. [2009]
'random': choose 'n_clusters' observations (rows) at random from
data for the initial centroids.
If an ndarray is passed, it should be of shape (n_clusters, n_features)
and gives the initial centroids.
n_init : int, default: 10
Number of time the k-modes algorithm will be run with different
centroid seeds. The final results will be the best output of
n_init consecutive runs in terms of cost.
verbose : int, optional
Verbosity mode.
random_state : int, RandomState instance or None, optional, default: None
If int, random_state is the seed used by the random number generator;
If RandomState instance, random_state is the random number generator;
If None, the random number generator is the RandomState instance used
by `np.random`.
n_jobs : int, default: 1
The number of jobs to use for the computation. This works by computing
each of the n_init runs in parallel.
If -1 all CPUs are used. If 1 is given, no parallel computing code is
used at all, which is useful for debugging. For n_jobs below -1,
(n_cpus + 1 + n_jobs) are used. Thus for n_jobs = -2, all CPUs but one
are used.
Attributes
----------
cluster_centroids_ : array, [n_clusters, n_features]
Categories of cluster centroids
labels_ :
Labels of each point
cost_ : float
Clustering cost, defined as the sum distance of all points to
their respective cluster centroids.
n_iter_ : int
The number of iterations the algorithm ran for.
Notes
-----
See:
Huang, Z.: Extensions to the k-modes algorithm for clustering large
data sets with categorical values, Data Mining and Knowledge
Discovery 2(3), 1998.
"""
def __init__(self, n_clusters=8, max_iter=100, cat_dissim=matching_dissim,
init='Cao', n_init=1, verbose=0, random_state=None, n_jobs=1):
self.n_clusters = n_clusters
self.max_iter = max_iter
self.cat_dissim = cat_dissim
self.init = init
self.n_init = n_init
self.verbose = verbose
self.random_state = random_state
self.n_jobs = n_jobs
if ((isinstance(self.init, str) and self.init == 'Cao') or
hasattr(self.init, '__array__')) and self.n_init > 1:
if self.verbose:
print("Initialization method and algorithm are deterministic. "
"Setting n_init to 1.")
self.n_init = 1
def fit(self, X, y=None, **kwargs):
"""Compute k-modes clustering.
Parameters
----------
X : array-like, shape=[n_samples, n_features]
"""
X = pandas_to_numpy(X)
random_state = check_random_state(self.random_state)
self._enc_cluster_centroids, self._enc_map, self.labels_,\
self.cost_, self.n_iter_ = k_modes(X,
self.n_clusters,
self.max_iter,
self.cat_dissim,
self.init,
self.n_init,
self.verbose,
random_state,
self.n_jobs)
return self
def fit_predict(self, X, y=None, **kwargs):
"""Compute cluster centroids and predict cluster index for each sample.
Convenience method; equivalent to calling fit(X) followed by
predict(X).
"""
return self.fit(X, **kwargs).predict(X, **kwargs)
def predict(self, X, **kwargs):
"""Predict the closest cluster each sample in X belongs to.
Parameters
----------
X : array-like, shape = [n_samples, n_features]
New data to predict.
Returns
-------
labels : array, shape [n_samples,]
Index of the cluster each sample belongs to.
"""
assert hasattr(self, '_enc_cluster_centroids'), "Model not yet fitted."
if self.verbose and self.cat_dissim == ng_dissim:
print("Ng's dissimilarity measure was used to train this model, "
"but now that it is predicting the model will fall back to "
"using simple matching dissimilarity.")
X = pandas_to_numpy(X)
X = check_array(X, dtype=None)
X, _ = encode_features(X, enc_map=self._enc_map)
return _labels_cost(X, self._enc_cluster_centroids, self.cat_dissim)[0]
@property
def cluster_centroids_(self):
if hasattr(self, '_enc_cluster_centroids'):
return decode_centroids(self._enc_cluster_centroids, self._enc_map)
else:
raise AttributeError("'{}' object has no attribute 'cluster_centroids_' "
"because the model is not yet fitted.")
|
nicodv/kmodes | kmodes/kmodes.py | init_cao | python | def init_cao(X, n_clusters, dissim):
n_points, n_attrs = X.shape
centroids = np.empty((n_clusters, n_attrs), dtype='object')
# Method is based on determining density of points.
dens = np.zeros(n_points)
for iattr in range(n_attrs):
freq = defaultdict(int)
for val in X[:, iattr]:
freq[val] += 1
for ipoint in range(n_points):
dens[ipoint] += freq[X[ipoint, iattr]] / float(n_points) / float(n_attrs)
# Choose initial centroids based on distance and density.
centroids[0] = X[np.argmax(dens)]
if n_clusters > 1:
# For the remaining centroids, choose maximum dens * dissim to the
# (already assigned) centroid with the lowest dens * dissim.
for ik in range(1, n_clusters):
dd = np.empty((ik, n_points))
for ikk in range(ik):
dd[ikk] = dissim(X, centroids[ikk]) * dens
centroids[ik] = X[np.argmax(np.min(dd, axis=0))]
return centroids | Initialize centroids according to method by Cao et al. [2009].
Note: O(N * attr * n_clusters**2), so watch out with large n_clusters | train | https://github.com/nicodv/kmodes/blob/cdb19fe5448aba1bf501626694bb52e68eafab45/kmodes/kmodes.py#L53-L80 | null | """
K-modes clustering for categorical data
"""
# pylint: disable=unused-argument,attribute-defined-outside-init
from collections import defaultdict
import numpy as np
from joblib import Parallel, delayed
from scipy import sparse
from sklearn.base import BaseEstimator, ClusterMixin
from sklearn.utils import check_random_state
from sklearn.utils.validation import check_array
from .util import get_max_value_key, encode_features, get_unique_rows, \
decode_centroids, pandas_to_numpy
from .util.dissim import matching_dissim, ng_dissim
def init_huang(X, n_clusters, dissim, random_state):
"""Initialize centroids according to method by Huang [1997]."""
n_attrs = X.shape[1]
centroids = np.empty((n_clusters, n_attrs), dtype='object')
# determine frequencies of attributes
for iattr in range(n_attrs):
freq = defaultdict(int)
for curattr in X[:, iattr]:
freq[curattr] += 1
# Sample centroids using the probabilities of attributes.
# (I assume that's what's meant in the Huang [1998] paper; it works,
# at least)
# Note: sampling using population in static list with as many choices
# as frequency counts. Since the counts are small integers,
# memory consumption is low.
choices = [chc for chc, wght in freq.items() for _ in range(wght)]
# So that we are consistent between Python versions,
# each with different dict ordering.
choices = sorted(choices)
centroids[:, iattr] = random_state.choice(choices, n_clusters)
# The previously chosen centroids could result in empty clusters,
# so set centroid to closest point in X.
for ik in range(n_clusters):
ndx = np.argsort(dissim(X, centroids[ik]))
# We want the centroid to be unique, if possible.
while np.all(X[ndx[0]] == centroids, axis=1).any() and ndx.shape[0] > 1:
ndx = np.delete(ndx, 0)
centroids[ik] = X[ndx[0]]
return centroids
def move_point_cat(point, ipoint, to_clust, from_clust, cl_attr_freq,
membship, centroids):
"""Move point between clusters, categorical attributes."""
membship[to_clust, ipoint] = 1
membship[from_clust, ipoint] = 0
# Update frequencies of attributes in cluster.
for iattr, curattr in enumerate(point):
to_attr_counts = cl_attr_freq[to_clust][iattr]
from_attr_counts = cl_attr_freq[from_clust][iattr]
# Increment the attribute count for the new "to" cluster
to_attr_counts[curattr] += 1
current_attribute_value_freq = to_attr_counts[curattr]
current_centroid_value = centroids[to_clust][iattr]
current_centroid_freq = to_attr_counts[current_centroid_value]
if current_centroid_freq < current_attribute_value_freq:
# We have incremented this value to the new mode. Update the centroid.
centroids[to_clust][iattr] = curattr
# Decrement the attribute count for the old "from" cluster
from_attr_counts[curattr] -= 1
old_centroid_value = centroids[from_clust][iattr]
if old_centroid_value == curattr:
# We have just removed a count from the old centroid value. We need to
# recalculate the centroid as it may no longer be the maximum
centroids[from_clust][iattr] = get_max_value_key(from_attr_counts)
return cl_attr_freq, membship, centroids
def _labels_cost(X, centroids, dissim, membship=None):
"""Calculate labels and cost function given a matrix of points and
a list of centroids for the k-modes algorithm.
"""
X = check_array(X)
n_points = X.shape[0]
cost = 0.
labels = np.empty(n_points, dtype=np.uint16)
for ipoint, curpoint in enumerate(X):
diss = dissim(centroids, curpoint, X=X, membship=membship)
clust = np.argmin(diss)
labels[ipoint] = clust
cost += diss[clust]
return labels, cost
def _k_modes_iter(X, centroids, cl_attr_freq, membship, dissim, random_state):
"""Single iteration of k-modes clustering algorithm"""
moves = 0
for ipoint, curpoint in enumerate(X):
clust = np.argmin(dissim(centroids, curpoint, X=X, membship=membship))
if membship[clust, ipoint]:
# Point is already in its right place.
continue
# Move point, and update old/new cluster frequencies and centroids.
moves += 1
old_clust = np.argwhere(membship[:, ipoint])[0][0]
cl_attr_freq, membship, centroids = move_point_cat(
curpoint, ipoint, clust, old_clust, cl_attr_freq, membship, centroids
)
# In case of an empty cluster, reinitialize with a random point
# from the largest cluster.
if not membship[old_clust, :].any():
from_clust = membship.sum(axis=1).argmax()
choices = [ii for ii, ch in enumerate(membship[from_clust, :]) if ch]
rindx = random_state.choice(choices)
cl_attr_freq, membship, centroids = move_point_cat(
X[rindx], rindx, old_clust, from_clust, cl_attr_freq, membship, centroids
)
return centroids, moves
def k_modes_single(X, n_clusters, n_points, n_attrs, max_iter, dissim, init, init_no,
verbose, random_state):
random_state = check_random_state(random_state)
# _____ INIT _____
if verbose:
print("Init: initializing centroids")
if isinstance(init, str) and init.lower() == 'huang':
centroids = init_huang(X, n_clusters, dissim, random_state)
elif isinstance(init, str) and init.lower() == 'cao':
centroids = init_cao(X, n_clusters, dissim)
elif isinstance(init, str) and init.lower() == 'random':
seeds = random_state.choice(range(n_points), n_clusters)
centroids = X[seeds]
elif hasattr(init, '__array__'):
# Make sure init is a 2D array.
if len(init.shape) == 1:
init = np.atleast_2d(init).T
assert init.shape[0] == n_clusters, \
"Wrong number of initial centroids in init ({}, should be {})." \
.format(init.shape[0], n_clusters)
assert init.shape[1] == n_attrs, \
"Wrong number of attributes in init ({}, should be {})." \
.format(init.shape[1], n_attrs)
centroids = np.asarray(init, dtype=np.uint16)
else:
raise NotImplementedError
if verbose:
print("Init: initializing clusters")
membship = np.zeros((n_clusters, n_points), dtype=np.uint8)
# cl_attr_freq is a list of lists with dictionaries that contain the
# frequencies of values per cluster and attribute.
cl_attr_freq = [[defaultdict(int) for _ in range(n_attrs)]
for _ in range(n_clusters)]
for ipoint, curpoint in enumerate(X):
# Initial assignment to clusters
clust = np.argmin(dissim(centroids, curpoint, X=X, membship=membship))
membship[clust, ipoint] = 1
# Count attribute values per cluster.
for iattr, curattr in enumerate(curpoint):
cl_attr_freq[clust][iattr][curattr] += 1
# Perform an initial centroid update.
for ik in range(n_clusters):
for iattr in range(n_attrs):
if sum(membship[ik]) == 0:
# Empty centroid, choose randomly
centroids[ik, iattr] = random_state.choice(X[:, iattr])
else:
centroids[ik, iattr] = get_max_value_key(cl_attr_freq[ik][iattr])
# _____ ITERATION _____
if verbose:
print("Starting iterations...")
itr = 0
labels = None
converged = False
cost = np.Inf
while itr <= max_iter and not converged:
itr += 1
centroids, moves = _k_modes_iter(
X,
centroids,
cl_attr_freq,
membship,
dissim,
random_state
)
# All points seen in this iteration
labels, ncost = _labels_cost(X, centroids, dissim, membship)
converged = (moves == 0) or (ncost >= cost)
cost = ncost
if verbose:
print("Run {}, iteration: {}/{}, moves: {}, cost: {}"
.format(init_no + 1, itr, max_iter, moves, cost))
return centroids, labels, cost, itr
def k_modes(X, n_clusters, max_iter, dissim, init, n_init, verbose, random_state, n_jobs):
"""k-modes algorithm"""
random_state = check_random_state(random_state)
if sparse.issparse(X):
raise TypeError("k-modes does not support sparse data.")
X = check_array(X, dtype=None)
# Convert the categorical values in X to integers for speed.
# Based on the unique values in X, we can make a mapping to achieve this.
X, enc_map = encode_features(X)
n_points, n_attrs = X.shape
assert n_clusters <= n_points, "Cannot have more clusters ({}) " \
"than data points ({}).".format(n_clusters, n_points)
# Are there more n_clusters than unique rows? Then set the unique
# rows as initial values and skip iteration.
unique = get_unique_rows(X)
n_unique = unique.shape[0]
if n_unique <= n_clusters:
max_iter = 0
n_init = 1
n_clusters = n_unique
init = unique
results = []
seeds = random_state.randint(np.iinfo(np.int32).max, size=n_init)
if n_jobs == 1:
for init_no in range(n_init):
results.append(k_modes_single(X, n_clusters, n_points, n_attrs, max_iter,
dissim, init, init_no, verbose, seeds[init_no]))
else:
results = Parallel(n_jobs=n_jobs, verbose=0)(
delayed(k_modes_single)(X, n_clusters, n_points, n_attrs, max_iter,
dissim, init, init_no, verbose, seed)
for init_no, seed in enumerate(seeds))
all_centroids, all_labels, all_costs, all_n_iters = zip(*results)
best = np.argmin(all_costs)
if n_init > 1 and verbose:
print("Best run was number {}".format(best + 1))
return all_centroids[best], enc_map, all_labels[best], \
all_costs[best], all_n_iters[best]
class KModes(BaseEstimator, ClusterMixin):
"""k-modes clustering algorithm for categorical data.
Parameters
-----------
n_clusters : int, optional, default: 8
The number of clusters to form as well as the number of
centroids to generate.
max_iter : int, default: 300
Maximum number of iterations of the k-modes algorithm for a
single run.
cat_dissim : func, default: matching_dissim
Dissimilarity function used by the k-modes algorithm for categorical variables.
Defaults to the matching dissimilarity function.
init : {'Huang', 'Cao', 'random' or an ndarray}, default: 'Cao'
Method for initialization:
'Huang': Method in Huang [1997, 1998]
'Cao': Method in Cao et al. [2009]
'random': choose 'n_clusters' observations (rows) at random from
data for the initial centroids.
If an ndarray is passed, it should be of shape (n_clusters, n_features)
and gives the initial centroids.
n_init : int, default: 10
Number of time the k-modes algorithm will be run with different
centroid seeds. The final results will be the best output of
n_init consecutive runs in terms of cost.
verbose : int, optional
Verbosity mode.
random_state : int, RandomState instance or None, optional, default: None
If int, random_state is the seed used by the random number generator;
If RandomState instance, random_state is the random number generator;
If None, the random number generator is the RandomState instance used
by `np.random`.
n_jobs : int, default: 1
The number of jobs to use for the computation. This works by computing
each of the n_init runs in parallel.
If -1 all CPUs are used. If 1 is given, no parallel computing code is
used at all, which is useful for debugging. For n_jobs below -1,
(n_cpus + 1 + n_jobs) are used. Thus for n_jobs = -2, all CPUs but one
are used.
Attributes
----------
cluster_centroids_ : array, [n_clusters, n_features]
Categories of cluster centroids
labels_ :
Labels of each point
cost_ : float
Clustering cost, defined as the sum distance of all points to
their respective cluster centroids.
n_iter_ : int
The number of iterations the algorithm ran for.
Notes
-----
See:
Huang, Z.: Extensions to the k-modes algorithm for clustering large
data sets with categorical values, Data Mining and Knowledge
Discovery 2(3), 1998.
"""
def __init__(self, n_clusters=8, max_iter=100, cat_dissim=matching_dissim,
init='Cao', n_init=1, verbose=0, random_state=None, n_jobs=1):
self.n_clusters = n_clusters
self.max_iter = max_iter
self.cat_dissim = cat_dissim
self.init = init
self.n_init = n_init
self.verbose = verbose
self.random_state = random_state
self.n_jobs = n_jobs
if ((isinstance(self.init, str) and self.init == 'Cao') or
hasattr(self.init, '__array__')) and self.n_init > 1:
if self.verbose:
print("Initialization method and algorithm are deterministic. "
"Setting n_init to 1.")
self.n_init = 1
def fit(self, X, y=None, **kwargs):
"""Compute k-modes clustering.
Parameters
----------
X : array-like, shape=[n_samples, n_features]
"""
X = pandas_to_numpy(X)
random_state = check_random_state(self.random_state)
self._enc_cluster_centroids, self._enc_map, self.labels_,\
self.cost_, self.n_iter_ = k_modes(X,
self.n_clusters,
self.max_iter,
self.cat_dissim,
self.init,
self.n_init,
self.verbose,
random_state,
self.n_jobs)
return self
def fit_predict(self, X, y=None, **kwargs):
"""Compute cluster centroids and predict cluster index for each sample.
Convenience method; equivalent to calling fit(X) followed by
predict(X).
"""
return self.fit(X, **kwargs).predict(X, **kwargs)
def predict(self, X, **kwargs):
"""Predict the closest cluster each sample in X belongs to.
Parameters
----------
X : array-like, shape = [n_samples, n_features]
New data to predict.
Returns
-------
labels : array, shape [n_samples,]
Index of the cluster each sample belongs to.
"""
assert hasattr(self, '_enc_cluster_centroids'), "Model not yet fitted."
if self.verbose and self.cat_dissim == ng_dissim:
print("Ng's dissimilarity measure was used to train this model, "
"but now that it is predicting the model will fall back to "
"using simple matching dissimilarity.")
X = pandas_to_numpy(X)
X = check_array(X, dtype=None)
X, _ = encode_features(X, enc_map=self._enc_map)
return _labels_cost(X, self._enc_cluster_centroids, self.cat_dissim)[0]
@property
def cluster_centroids_(self):
if hasattr(self, '_enc_cluster_centroids'):
return decode_centroids(self._enc_cluster_centroids, self._enc_map)
else:
raise AttributeError("'{}' object has no attribute 'cluster_centroids_' "
"because the model is not yet fitted.")
|
nicodv/kmodes | kmodes/kmodes.py | move_point_cat | python | def move_point_cat(point, ipoint, to_clust, from_clust, cl_attr_freq,
membship, centroids):
membship[to_clust, ipoint] = 1
membship[from_clust, ipoint] = 0
# Update frequencies of attributes in cluster.
for iattr, curattr in enumerate(point):
to_attr_counts = cl_attr_freq[to_clust][iattr]
from_attr_counts = cl_attr_freq[from_clust][iattr]
# Increment the attribute count for the new "to" cluster
to_attr_counts[curattr] += 1
current_attribute_value_freq = to_attr_counts[curattr]
current_centroid_value = centroids[to_clust][iattr]
current_centroid_freq = to_attr_counts[current_centroid_value]
if current_centroid_freq < current_attribute_value_freq:
# We have incremented this value to the new mode. Update the centroid.
centroids[to_clust][iattr] = curattr
# Decrement the attribute count for the old "from" cluster
from_attr_counts[curattr] -= 1
old_centroid_value = centroids[from_clust][iattr]
if old_centroid_value == curattr:
# We have just removed a count from the old centroid value. We need to
# recalculate the centroid as it may no longer be the maximum
centroids[from_clust][iattr] = get_max_value_key(from_attr_counts)
return cl_attr_freq, membship, centroids | Move point between clusters, categorical attributes. | train | https://github.com/nicodv/kmodes/blob/cdb19fe5448aba1bf501626694bb52e68eafab45/kmodes/kmodes.py#L83-L112 | [
"def get_max_value_key(dic):\n \"\"\"Gets the key for the maximum value in a dict.\"\"\"\n v = np.array(list(dic.values()))\n k = np.array(list(dic.keys()))\n\n maxima = np.where(v == np.max(v))[0]\n if len(maxima) == 1:\n return k[maxima[0]]\n else:\n # In order to be consistent, always selects the minimum key\n # (guaranteed to be unique) when there are multiple maximum values.\n return k[maxima[np.argmin(k[maxima])]]\n"
] | """
K-modes clustering for categorical data
"""
# pylint: disable=unused-argument,attribute-defined-outside-init
from collections import defaultdict
import numpy as np
from joblib import Parallel, delayed
from scipy import sparse
from sklearn.base import BaseEstimator, ClusterMixin
from sklearn.utils import check_random_state
from sklearn.utils.validation import check_array
from .util import get_max_value_key, encode_features, get_unique_rows, \
decode_centroids, pandas_to_numpy
from .util.dissim import matching_dissim, ng_dissim
def init_huang(X, n_clusters, dissim, random_state):
"""Initialize centroids according to method by Huang [1997]."""
n_attrs = X.shape[1]
centroids = np.empty((n_clusters, n_attrs), dtype='object')
# determine frequencies of attributes
for iattr in range(n_attrs):
freq = defaultdict(int)
for curattr in X[:, iattr]:
freq[curattr] += 1
# Sample centroids using the probabilities of attributes.
# (I assume that's what's meant in the Huang [1998] paper; it works,
# at least)
# Note: sampling using population in static list with as many choices
# as frequency counts. Since the counts are small integers,
# memory consumption is low.
choices = [chc for chc, wght in freq.items() for _ in range(wght)]
# So that we are consistent between Python versions,
# each with different dict ordering.
choices = sorted(choices)
centroids[:, iattr] = random_state.choice(choices, n_clusters)
# The previously chosen centroids could result in empty clusters,
# so set centroid to closest point in X.
for ik in range(n_clusters):
ndx = np.argsort(dissim(X, centroids[ik]))
# We want the centroid to be unique, if possible.
while np.all(X[ndx[0]] == centroids, axis=1).any() and ndx.shape[0] > 1:
ndx = np.delete(ndx, 0)
centroids[ik] = X[ndx[0]]
return centroids
def init_cao(X, n_clusters, dissim):
"""Initialize centroids according to method by Cao et al. [2009].
Note: O(N * attr * n_clusters**2), so watch out with large n_clusters
"""
n_points, n_attrs = X.shape
centroids = np.empty((n_clusters, n_attrs), dtype='object')
# Method is based on determining density of points.
dens = np.zeros(n_points)
for iattr in range(n_attrs):
freq = defaultdict(int)
for val in X[:, iattr]:
freq[val] += 1
for ipoint in range(n_points):
dens[ipoint] += freq[X[ipoint, iattr]] / float(n_points) / float(n_attrs)
# Choose initial centroids based on distance and density.
centroids[0] = X[np.argmax(dens)]
if n_clusters > 1:
# For the remaining centroids, choose maximum dens * dissim to the
# (already assigned) centroid with the lowest dens * dissim.
for ik in range(1, n_clusters):
dd = np.empty((ik, n_points))
for ikk in range(ik):
dd[ikk] = dissim(X, centroids[ikk]) * dens
centroids[ik] = X[np.argmax(np.min(dd, axis=0))]
return centroids
def _labels_cost(X, centroids, dissim, membship=None):
"""Calculate labels and cost function given a matrix of points and
a list of centroids for the k-modes algorithm.
"""
X = check_array(X)
n_points = X.shape[0]
cost = 0.
labels = np.empty(n_points, dtype=np.uint16)
for ipoint, curpoint in enumerate(X):
diss = dissim(centroids, curpoint, X=X, membship=membship)
clust = np.argmin(diss)
labels[ipoint] = clust
cost += diss[clust]
return labels, cost
def _k_modes_iter(X, centroids, cl_attr_freq, membship, dissim, random_state):
"""Single iteration of k-modes clustering algorithm"""
moves = 0
for ipoint, curpoint in enumerate(X):
clust = np.argmin(dissim(centroids, curpoint, X=X, membship=membship))
if membship[clust, ipoint]:
# Point is already in its right place.
continue
# Move point, and update old/new cluster frequencies and centroids.
moves += 1
old_clust = np.argwhere(membship[:, ipoint])[0][0]
cl_attr_freq, membship, centroids = move_point_cat(
curpoint, ipoint, clust, old_clust, cl_attr_freq, membship, centroids
)
# In case of an empty cluster, reinitialize with a random point
# from the largest cluster.
if not membship[old_clust, :].any():
from_clust = membship.sum(axis=1).argmax()
choices = [ii for ii, ch in enumerate(membship[from_clust, :]) if ch]
rindx = random_state.choice(choices)
cl_attr_freq, membship, centroids = move_point_cat(
X[rindx], rindx, old_clust, from_clust, cl_attr_freq, membship, centroids
)
return centroids, moves
def k_modes_single(X, n_clusters, n_points, n_attrs, max_iter, dissim, init, init_no,
verbose, random_state):
random_state = check_random_state(random_state)
# _____ INIT _____
if verbose:
print("Init: initializing centroids")
if isinstance(init, str) and init.lower() == 'huang':
centroids = init_huang(X, n_clusters, dissim, random_state)
elif isinstance(init, str) and init.lower() == 'cao':
centroids = init_cao(X, n_clusters, dissim)
elif isinstance(init, str) and init.lower() == 'random':
seeds = random_state.choice(range(n_points), n_clusters)
centroids = X[seeds]
elif hasattr(init, '__array__'):
# Make sure init is a 2D array.
if len(init.shape) == 1:
init = np.atleast_2d(init).T
assert init.shape[0] == n_clusters, \
"Wrong number of initial centroids in init ({}, should be {})." \
.format(init.shape[0], n_clusters)
assert init.shape[1] == n_attrs, \
"Wrong number of attributes in init ({}, should be {})." \
.format(init.shape[1], n_attrs)
centroids = np.asarray(init, dtype=np.uint16)
else:
raise NotImplementedError
if verbose:
print("Init: initializing clusters")
membship = np.zeros((n_clusters, n_points), dtype=np.uint8)
# cl_attr_freq is a list of lists with dictionaries that contain the
# frequencies of values per cluster and attribute.
cl_attr_freq = [[defaultdict(int) for _ in range(n_attrs)]
for _ in range(n_clusters)]
for ipoint, curpoint in enumerate(X):
# Initial assignment to clusters
clust = np.argmin(dissim(centroids, curpoint, X=X, membship=membship))
membship[clust, ipoint] = 1
# Count attribute values per cluster.
for iattr, curattr in enumerate(curpoint):
cl_attr_freq[clust][iattr][curattr] += 1
# Perform an initial centroid update.
for ik in range(n_clusters):
for iattr in range(n_attrs):
if sum(membship[ik]) == 0:
# Empty centroid, choose randomly
centroids[ik, iattr] = random_state.choice(X[:, iattr])
else:
centroids[ik, iattr] = get_max_value_key(cl_attr_freq[ik][iattr])
# _____ ITERATION _____
if verbose:
print("Starting iterations...")
itr = 0
labels = None
converged = False
cost = np.Inf
while itr <= max_iter and not converged:
itr += 1
centroids, moves = _k_modes_iter(
X,
centroids,
cl_attr_freq,
membship,
dissim,
random_state
)
# All points seen in this iteration
labels, ncost = _labels_cost(X, centroids, dissim, membship)
converged = (moves == 0) or (ncost >= cost)
cost = ncost
if verbose:
print("Run {}, iteration: {}/{}, moves: {}, cost: {}"
.format(init_no + 1, itr, max_iter, moves, cost))
return centroids, labels, cost, itr
def k_modes(X, n_clusters, max_iter, dissim, init, n_init, verbose, random_state, n_jobs):
"""k-modes algorithm"""
random_state = check_random_state(random_state)
if sparse.issparse(X):
raise TypeError("k-modes does not support sparse data.")
X = check_array(X, dtype=None)
# Convert the categorical values in X to integers for speed.
# Based on the unique values in X, we can make a mapping to achieve this.
X, enc_map = encode_features(X)
n_points, n_attrs = X.shape
assert n_clusters <= n_points, "Cannot have more clusters ({}) " \
"than data points ({}).".format(n_clusters, n_points)
# Are there more n_clusters than unique rows? Then set the unique
# rows as initial values and skip iteration.
unique = get_unique_rows(X)
n_unique = unique.shape[0]
if n_unique <= n_clusters:
max_iter = 0
n_init = 1
n_clusters = n_unique
init = unique
results = []
seeds = random_state.randint(np.iinfo(np.int32).max, size=n_init)
if n_jobs == 1:
for init_no in range(n_init):
results.append(k_modes_single(X, n_clusters, n_points, n_attrs, max_iter,
dissim, init, init_no, verbose, seeds[init_no]))
else:
results = Parallel(n_jobs=n_jobs, verbose=0)(
delayed(k_modes_single)(X, n_clusters, n_points, n_attrs, max_iter,
dissim, init, init_no, verbose, seed)
for init_no, seed in enumerate(seeds))
all_centroids, all_labels, all_costs, all_n_iters = zip(*results)
best = np.argmin(all_costs)
if n_init > 1 and verbose:
print("Best run was number {}".format(best + 1))
return all_centroids[best], enc_map, all_labels[best], \
all_costs[best], all_n_iters[best]
class KModes(BaseEstimator, ClusterMixin):
"""k-modes clustering algorithm for categorical data.
Parameters
-----------
n_clusters : int, optional, default: 8
The number of clusters to form as well as the number of
centroids to generate.
max_iter : int, default: 300
Maximum number of iterations of the k-modes algorithm for a
single run.
cat_dissim : func, default: matching_dissim
Dissimilarity function used by the k-modes algorithm for categorical variables.
Defaults to the matching dissimilarity function.
init : {'Huang', 'Cao', 'random' or an ndarray}, default: 'Cao'
Method for initialization:
'Huang': Method in Huang [1997, 1998]
'Cao': Method in Cao et al. [2009]
'random': choose 'n_clusters' observations (rows) at random from
data for the initial centroids.
If an ndarray is passed, it should be of shape (n_clusters, n_features)
and gives the initial centroids.
n_init : int, default: 10
Number of time the k-modes algorithm will be run with different
centroid seeds. The final results will be the best output of
n_init consecutive runs in terms of cost.
verbose : int, optional
Verbosity mode.
random_state : int, RandomState instance or None, optional, default: None
If int, random_state is the seed used by the random number generator;
If RandomState instance, random_state is the random number generator;
If None, the random number generator is the RandomState instance used
by `np.random`.
n_jobs : int, default: 1
The number of jobs to use for the computation. This works by computing
each of the n_init runs in parallel.
If -1 all CPUs are used. If 1 is given, no parallel computing code is
used at all, which is useful for debugging. For n_jobs below -1,
(n_cpus + 1 + n_jobs) are used. Thus for n_jobs = -2, all CPUs but one
are used.
Attributes
----------
cluster_centroids_ : array, [n_clusters, n_features]
Categories of cluster centroids
labels_ :
Labels of each point
cost_ : float
Clustering cost, defined as the sum distance of all points to
their respective cluster centroids.
n_iter_ : int
The number of iterations the algorithm ran for.
Notes
-----
See:
Huang, Z.: Extensions to the k-modes algorithm for clustering large
data sets with categorical values, Data Mining and Knowledge
Discovery 2(3), 1998.
"""
def __init__(self, n_clusters=8, max_iter=100, cat_dissim=matching_dissim,
init='Cao', n_init=1, verbose=0, random_state=None, n_jobs=1):
self.n_clusters = n_clusters
self.max_iter = max_iter
self.cat_dissim = cat_dissim
self.init = init
self.n_init = n_init
self.verbose = verbose
self.random_state = random_state
self.n_jobs = n_jobs
if ((isinstance(self.init, str) and self.init == 'Cao') or
hasattr(self.init, '__array__')) and self.n_init > 1:
if self.verbose:
print("Initialization method and algorithm are deterministic. "
"Setting n_init to 1.")
self.n_init = 1
def fit(self, X, y=None, **kwargs):
"""Compute k-modes clustering.
Parameters
----------
X : array-like, shape=[n_samples, n_features]
"""
X = pandas_to_numpy(X)
random_state = check_random_state(self.random_state)
self._enc_cluster_centroids, self._enc_map, self.labels_,\
self.cost_, self.n_iter_ = k_modes(X,
self.n_clusters,
self.max_iter,
self.cat_dissim,
self.init,
self.n_init,
self.verbose,
random_state,
self.n_jobs)
return self
def fit_predict(self, X, y=None, **kwargs):
"""Compute cluster centroids and predict cluster index for each sample.
Convenience method; equivalent to calling fit(X) followed by
predict(X).
"""
return self.fit(X, **kwargs).predict(X, **kwargs)
def predict(self, X, **kwargs):
"""Predict the closest cluster each sample in X belongs to.
Parameters
----------
X : array-like, shape = [n_samples, n_features]
New data to predict.
Returns
-------
labels : array, shape [n_samples,]
Index of the cluster each sample belongs to.
"""
assert hasattr(self, '_enc_cluster_centroids'), "Model not yet fitted."
if self.verbose and self.cat_dissim == ng_dissim:
print("Ng's dissimilarity measure was used to train this model, "
"but now that it is predicting the model will fall back to "
"using simple matching dissimilarity.")
X = pandas_to_numpy(X)
X = check_array(X, dtype=None)
X, _ = encode_features(X, enc_map=self._enc_map)
return _labels_cost(X, self._enc_cluster_centroids, self.cat_dissim)[0]
@property
def cluster_centroids_(self):
if hasattr(self, '_enc_cluster_centroids'):
return decode_centroids(self._enc_cluster_centroids, self._enc_map)
else:
raise AttributeError("'{}' object has no attribute 'cluster_centroids_' "
"because the model is not yet fitted.")
|
nicodv/kmodes | kmodes/kmodes.py | _labels_cost | python | def _labels_cost(X, centroids, dissim, membship=None):
X = check_array(X)
n_points = X.shape[0]
cost = 0.
labels = np.empty(n_points, dtype=np.uint16)
for ipoint, curpoint in enumerate(X):
diss = dissim(centroids, curpoint, X=X, membship=membship)
clust = np.argmin(diss)
labels[ipoint] = clust
cost += diss[clust]
return labels, cost | Calculate labels and cost function given a matrix of points and
a list of centroids for the k-modes algorithm. | train | https://github.com/nicodv/kmodes/blob/cdb19fe5448aba1bf501626694bb52e68eafab45/kmodes/kmodes.py#L115-L131 | null | """
K-modes clustering for categorical data
"""
# pylint: disable=unused-argument,attribute-defined-outside-init
from collections import defaultdict
import numpy as np
from joblib import Parallel, delayed
from scipy import sparse
from sklearn.base import BaseEstimator, ClusterMixin
from sklearn.utils import check_random_state
from sklearn.utils.validation import check_array
from .util import get_max_value_key, encode_features, get_unique_rows, \
decode_centroids, pandas_to_numpy
from .util.dissim import matching_dissim, ng_dissim
def init_huang(X, n_clusters, dissim, random_state):
"""Initialize centroids according to method by Huang [1997]."""
n_attrs = X.shape[1]
centroids = np.empty((n_clusters, n_attrs), dtype='object')
# determine frequencies of attributes
for iattr in range(n_attrs):
freq = defaultdict(int)
for curattr in X[:, iattr]:
freq[curattr] += 1
# Sample centroids using the probabilities of attributes.
# (I assume that's what's meant in the Huang [1998] paper; it works,
# at least)
# Note: sampling using population in static list with as many choices
# as frequency counts. Since the counts are small integers,
# memory consumption is low.
choices = [chc for chc, wght in freq.items() for _ in range(wght)]
# So that we are consistent between Python versions,
# each with different dict ordering.
choices = sorted(choices)
centroids[:, iattr] = random_state.choice(choices, n_clusters)
# The previously chosen centroids could result in empty clusters,
# so set centroid to closest point in X.
for ik in range(n_clusters):
ndx = np.argsort(dissim(X, centroids[ik]))
# We want the centroid to be unique, if possible.
while np.all(X[ndx[0]] == centroids, axis=1).any() and ndx.shape[0] > 1:
ndx = np.delete(ndx, 0)
centroids[ik] = X[ndx[0]]
return centroids
def init_cao(X, n_clusters, dissim):
"""Initialize centroids according to method by Cao et al. [2009].
Note: O(N * attr * n_clusters**2), so watch out with large n_clusters
"""
n_points, n_attrs = X.shape
centroids = np.empty((n_clusters, n_attrs), dtype='object')
# Method is based on determining density of points.
dens = np.zeros(n_points)
for iattr in range(n_attrs):
freq = defaultdict(int)
for val in X[:, iattr]:
freq[val] += 1
for ipoint in range(n_points):
dens[ipoint] += freq[X[ipoint, iattr]] / float(n_points) / float(n_attrs)
# Choose initial centroids based on distance and density.
centroids[0] = X[np.argmax(dens)]
if n_clusters > 1:
# For the remaining centroids, choose maximum dens * dissim to the
# (already assigned) centroid with the lowest dens * dissim.
for ik in range(1, n_clusters):
dd = np.empty((ik, n_points))
for ikk in range(ik):
dd[ikk] = dissim(X, centroids[ikk]) * dens
centroids[ik] = X[np.argmax(np.min(dd, axis=0))]
return centroids
def move_point_cat(point, ipoint, to_clust, from_clust, cl_attr_freq,
membship, centroids):
"""Move point between clusters, categorical attributes."""
membship[to_clust, ipoint] = 1
membship[from_clust, ipoint] = 0
# Update frequencies of attributes in cluster.
for iattr, curattr in enumerate(point):
to_attr_counts = cl_attr_freq[to_clust][iattr]
from_attr_counts = cl_attr_freq[from_clust][iattr]
# Increment the attribute count for the new "to" cluster
to_attr_counts[curattr] += 1
current_attribute_value_freq = to_attr_counts[curattr]
current_centroid_value = centroids[to_clust][iattr]
current_centroid_freq = to_attr_counts[current_centroid_value]
if current_centroid_freq < current_attribute_value_freq:
# We have incremented this value to the new mode. Update the centroid.
centroids[to_clust][iattr] = curattr
# Decrement the attribute count for the old "from" cluster
from_attr_counts[curattr] -= 1
old_centroid_value = centroids[from_clust][iattr]
if old_centroid_value == curattr:
# We have just removed a count from the old centroid value. We need to
# recalculate the centroid as it may no longer be the maximum
centroids[from_clust][iattr] = get_max_value_key(from_attr_counts)
return cl_attr_freq, membship, centroids
def _k_modes_iter(X, centroids, cl_attr_freq, membship, dissim, random_state):
"""Single iteration of k-modes clustering algorithm"""
moves = 0
for ipoint, curpoint in enumerate(X):
clust = np.argmin(dissim(centroids, curpoint, X=X, membship=membship))
if membship[clust, ipoint]:
# Point is already in its right place.
continue
# Move point, and update old/new cluster frequencies and centroids.
moves += 1
old_clust = np.argwhere(membship[:, ipoint])[0][0]
cl_attr_freq, membship, centroids = move_point_cat(
curpoint, ipoint, clust, old_clust, cl_attr_freq, membship, centroids
)
# In case of an empty cluster, reinitialize with a random point
# from the largest cluster.
if not membship[old_clust, :].any():
from_clust = membship.sum(axis=1).argmax()
choices = [ii for ii, ch in enumerate(membship[from_clust, :]) if ch]
rindx = random_state.choice(choices)
cl_attr_freq, membship, centroids = move_point_cat(
X[rindx], rindx, old_clust, from_clust, cl_attr_freq, membship, centroids
)
return centroids, moves
def k_modes_single(X, n_clusters, n_points, n_attrs, max_iter, dissim, init, init_no,
verbose, random_state):
random_state = check_random_state(random_state)
# _____ INIT _____
if verbose:
print("Init: initializing centroids")
if isinstance(init, str) and init.lower() == 'huang':
centroids = init_huang(X, n_clusters, dissim, random_state)
elif isinstance(init, str) and init.lower() == 'cao':
centroids = init_cao(X, n_clusters, dissim)
elif isinstance(init, str) and init.lower() == 'random':
seeds = random_state.choice(range(n_points), n_clusters)
centroids = X[seeds]
elif hasattr(init, '__array__'):
# Make sure init is a 2D array.
if len(init.shape) == 1:
init = np.atleast_2d(init).T
assert init.shape[0] == n_clusters, \
"Wrong number of initial centroids in init ({}, should be {})." \
.format(init.shape[0], n_clusters)
assert init.shape[1] == n_attrs, \
"Wrong number of attributes in init ({}, should be {})." \
.format(init.shape[1], n_attrs)
centroids = np.asarray(init, dtype=np.uint16)
else:
raise NotImplementedError
if verbose:
print("Init: initializing clusters")
membship = np.zeros((n_clusters, n_points), dtype=np.uint8)
# cl_attr_freq is a list of lists with dictionaries that contain the
# frequencies of values per cluster and attribute.
cl_attr_freq = [[defaultdict(int) for _ in range(n_attrs)]
for _ in range(n_clusters)]
for ipoint, curpoint in enumerate(X):
# Initial assignment to clusters
clust = np.argmin(dissim(centroids, curpoint, X=X, membship=membship))
membship[clust, ipoint] = 1
# Count attribute values per cluster.
for iattr, curattr in enumerate(curpoint):
cl_attr_freq[clust][iattr][curattr] += 1
# Perform an initial centroid update.
for ik in range(n_clusters):
for iattr in range(n_attrs):
if sum(membship[ik]) == 0:
# Empty centroid, choose randomly
centroids[ik, iattr] = random_state.choice(X[:, iattr])
else:
centroids[ik, iattr] = get_max_value_key(cl_attr_freq[ik][iattr])
# _____ ITERATION _____
if verbose:
print("Starting iterations...")
itr = 0
labels = None
converged = False
cost = np.Inf
while itr <= max_iter and not converged:
itr += 1
centroids, moves = _k_modes_iter(
X,
centroids,
cl_attr_freq,
membship,
dissim,
random_state
)
# All points seen in this iteration
labels, ncost = _labels_cost(X, centroids, dissim, membship)
converged = (moves == 0) or (ncost >= cost)
cost = ncost
if verbose:
print("Run {}, iteration: {}/{}, moves: {}, cost: {}"
.format(init_no + 1, itr, max_iter, moves, cost))
return centroids, labels, cost, itr
def k_modes(X, n_clusters, max_iter, dissim, init, n_init, verbose, random_state, n_jobs):
"""k-modes algorithm"""
random_state = check_random_state(random_state)
if sparse.issparse(X):
raise TypeError("k-modes does not support sparse data.")
X = check_array(X, dtype=None)
# Convert the categorical values in X to integers for speed.
# Based on the unique values in X, we can make a mapping to achieve this.
X, enc_map = encode_features(X)
n_points, n_attrs = X.shape
assert n_clusters <= n_points, "Cannot have more clusters ({}) " \
"than data points ({}).".format(n_clusters, n_points)
# Are there more n_clusters than unique rows? Then set the unique
# rows as initial values and skip iteration.
unique = get_unique_rows(X)
n_unique = unique.shape[0]
if n_unique <= n_clusters:
max_iter = 0
n_init = 1
n_clusters = n_unique
init = unique
results = []
seeds = random_state.randint(np.iinfo(np.int32).max, size=n_init)
if n_jobs == 1:
for init_no in range(n_init):
results.append(k_modes_single(X, n_clusters, n_points, n_attrs, max_iter,
dissim, init, init_no, verbose, seeds[init_no]))
else:
results = Parallel(n_jobs=n_jobs, verbose=0)(
delayed(k_modes_single)(X, n_clusters, n_points, n_attrs, max_iter,
dissim, init, init_no, verbose, seed)
for init_no, seed in enumerate(seeds))
all_centroids, all_labels, all_costs, all_n_iters = zip(*results)
best = np.argmin(all_costs)
if n_init > 1 and verbose:
print("Best run was number {}".format(best + 1))
return all_centroids[best], enc_map, all_labels[best], \
all_costs[best], all_n_iters[best]
class KModes(BaseEstimator, ClusterMixin):
"""k-modes clustering algorithm for categorical data.
Parameters
-----------
n_clusters : int, optional, default: 8
The number of clusters to form as well as the number of
centroids to generate.
max_iter : int, default: 300
Maximum number of iterations of the k-modes algorithm for a
single run.
cat_dissim : func, default: matching_dissim
Dissimilarity function used by the k-modes algorithm for categorical variables.
Defaults to the matching dissimilarity function.
init : {'Huang', 'Cao', 'random' or an ndarray}, default: 'Cao'
Method for initialization:
'Huang': Method in Huang [1997, 1998]
'Cao': Method in Cao et al. [2009]
'random': choose 'n_clusters' observations (rows) at random from
data for the initial centroids.
If an ndarray is passed, it should be of shape (n_clusters, n_features)
and gives the initial centroids.
n_init : int, default: 10
Number of time the k-modes algorithm will be run with different
centroid seeds. The final results will be the best output of
n_init consecutive runs in terms of cost.
verbose : int, optional
Verbosity mode.
random_state : int, RandomState instance or None, optional, default: None
If int, random_state is the seed used by the random number generator;
If RandomState instance, random_state is the random number generator;
If None, the random number generator is the RandomState instance used
by `np.random`.
n_jobs : int, default: 1
The number of jobs to use for the computation. This works by computing
each of the n_init runs in parallel.
If -1 all CPUs are used. If 1 is given, no parallel computing code is
used at all, which is useful for debugging. For n_jobs below -1,
(n_cpus + 1 + n_jobs) are used. Thus for n_jobs = -2, all CPUs but one
are used.
Attributes
----------
cluster_centroids_ : array, [n_clusters, n_features]
Categories of cluster centroids
labels_ :
Labels of each point
cost_ : float
Clustering cost, defined as the sum distance of all points to
their respective cluster centroids.
n_iter_ : int
The number of iterations the algorithm ran for.
Notes
-----
See:
Huang, Z.: Extensions to the k-modes algorithm for clustering large
data sets with categorical values, Data Mining and Knowledge
Discovery 2(3), 1998.
"""
def __init__(self, n_clusters=8, max_iter=100, cat_dissim=matching_dissim,
init='Cao', n_init=1, verbose=0, random_state=None, n_jobs=1):
self.n_clusters = n_clusters
self.max_iter = max_iter
self.cat_dissim = cat_dissim
self.init = init
self.n_init = n_init
self.verbose = verbose
self.random_state = random_state
self.n_jobs = n_jobs
if ((isinstance(self.init, str) and self.init == 'Cao') or
hasattr(self.init, '__array__')) and self.n_init > 1:
if self.verbose:
print("Initialization method and algorithm are deterministic. "
"Setting n_init to 1.")
self.n_init = 1
def fit(self, X, y=None, **kwargs):
"""Compute k-modes clustering.
Parameters
----------
X : array-like, shape=[n_samples, n_features]
"""
X = pandas_to_numpy(X)
random_state = check_random_state(self.random_state)
self._enc_cluster_centroids, self._enc_map, self.labels_,\
self.cost_, self.n_iter_ = k_modes(X,
self.n_clusters,
self.max_iter,
self.cat_dissim,
self.init,
self.n_init,
self.verbose,
random_state,
self.n_jobs)
return self
def fit_predict(self, X, y=None, **kwargs):
"""Compute cluster centroids and predict cluster index for each sample.
Convenience method; equivalent to calling fit(X) followed by
predict(X).
"""
return self.fit(X, **kwargs).predict(X, **kwargs)
def predict(self, X, **kwargs):
"""Predict the closest cluster each sample in X belongs to.
Parameters
----------
X : array-like, shape = [n_samples, n_features]
New data to predict.
Returns
-------
labels : array, shape [n_samples,]
Index of the cluster each sample belongs to.
"""
assert hasattr(self, '_enc_cluster_centroids'), "Model not yet fitted."
if self.verbose and self.cat_dissim == ng_dissim:
print("Ng's dissimilarity measure was used to train this model, "
"but now that it is predicting the model will fall back to "
"using simple matching dissimilarity.")
X = pandas_to_numpy(X)
X = check_array(X, dtype=None)
X, _ = encode_features(X, enc_map=self._enc_map)
return _labels_cost(X, self._enc_cluster_centroids, self.cat_dissim)[0]
@property
def cluster_centroids_(self):
if hasattr(self, '_enc_cluster_centroids'):
return decode_centroids(self._enc_cluster_centroids, self._enc_map)
else:
raise AttributeError("'{}' object has no attribute 'cluster_centroids_' "
"because the model is not yet fitted.")
|
nicodv/kmodes | kmodes/kmodes.py | _k_modes_iter | python | def _k_modes_iter(X, centroids, cl_attr_freq, membship, dissim, random_state):
moves = 0
for ipoint, curpoint in enumerate(X):
clust = np.argmin(dissim(centroids, curpoint, X=X, membship=membship))
if membship[clust, ipoint]:
# Point is already in its right place.
continue
# Move point, and update old/new cluster frequencies and centroids.
moves += 1
old_clust = np.argwhere(membship[:, ipoint])[0][0]
cl_attr_freq, membship, centroids = move_point_cat(
curpoint, ipoint, clust, old_clust, cl_attr_freq, membship, centroids
)
# In case of an empty cluster, reinitialize with a random point
# from the largest cluster.
if not membship[old_clust, :].any():
from_clust = membship.sum(axis=1).argmax()
choices = [ii for ii, ch in enumerate(membship[from_clust, :]) if ch]
rindx = random_state.choice(choices)
cl_attr_freq, membship, centroids = move_point_cat(
X[rindx], rindx, old_clust, from_clust, cl_attr_freq, membship, centroids
)
return centroids, moves | Single iteration of k-modes clustering algorithm | train | https://github.com/nicodv/kmodes/blob/cdb19fe5448aba1bf501626694bb52e68eafab45/kmodes/kmodes.py#L134-L162 | null | """
K-modes clustering for categorical data
"""
# pylint: disable=unused-argument,attribute-defined-outside-init
from collections import defaultdict
import numpy as np
from joblib import Parallel, delayed
from scipy import sparse
from sklearn.base import BaseEstimator, ClusterMixin
from sklearn.utils import check_random_state
from sklearn.utils.validation import check_array
from .util import get_max_value_key, encode_features, get_unique_rows, \
decode_centroids, pandas_to_numpy
from .util.dissim import matching_dissim, ng_dissim
def init_huang(X, n_clusters, dissim, random_state):
"""Initialize centroids according to method by Huang [1997]."""
n_attrs = X.shape[1]
centroids = np.empty((n_clusters, n_attrs), dtype='object')
# determine frequencies of attributes
for iattr in range(n_attrs):
freq = defaultdict(int)
for curattr in X[:, iattr]:
freq[curattr] += 1
# Sample centroids using the probabilities of attributes.
# (I assume that's what's meant in the Huang [1998] paper; it works,
# at least)
# Note: sampling using population in static list with as many choices
# as frequency counts. Since the counts are small integers,
# memory consumption is low.
choices = [chc for chc, wght in freq.items() for _ in range(wght)]
# So that we are consistent between Python versions,
# each with different dict ordering.
choices = sorted(choices)
centroids[:, iattr] = random_state.choice(choices, n_clusters)
# The previously chosen centroids could result in empty clusters,
# so set centroid to closest point in X.
for ik in range(n_clusters):
ndx = np.argsort(dissim(X, centroids[ik]))
# We want the centroid to be unique, if possible.
while np.all(X[ndx[0]] == centroids, axis=1).any() and ndx.shape[0] > 1:
ndx = np.delete(ndx, 0)
centroids[ik] = X[ndx[0]]
return centroids
def init_cao(X, n_clusters, dissim):
"""Initialize centroids according to method by Cao et al. [2009].
Note: O(N * attr * n_clusters**2), so watch out with large n_clusters
"""
n_points, n_attrs = X.shape
centroids = np.empty((n_clusters, n_attrs), dtype='object')
# Method is based on determining density of points.
dens = np.zeros(n_points)
for iattr in range(n_attrs):
freq = defaultdict(int)
for val in X[:, iattr]:
freq[val] += 1
for ipoint in range(n_points):
dens[ipoint] += freq[X[ipoint, iattr]] / float(n_points) / float(n_attrs)
# Choose initial centroids based on distance and density.
centroids[0] = X[np.argmax(dens)]
if n_clusters > 1:
# For the remaining centroids, choose maximum dens * dissim to the
# (already assigned) centroid with the lowest dens * dissim.
for ik in range(1, n_clusters):
dd = np.empty((ik, n_points))
for ikk in range(ik):
dd[ikk] = dissim(X, centroids[ikk]) * dens
centroids[ik] = X[np.argmax(np.min(dd, axis=0))]
return centroids
def move_point_cat(point, ipoint, to_clust, from_clust, cl_attr_freq,
membship, centroids):
"""Move point between clusters, categorical attributes."""
membship[to_clust, ipoint] = 1
membship[from_clust, ipoint] = 0
# Update frequencies of attributes in cluster.
for iattr, curattr in enumerate(point):
to_attr_counts = cl_attr_freq[to_clust][iattr]
from_attr_counts = cl_attr_freq[from_clust][iattr]
# Increment the attribute count for the new "to" cluster
to_attr_counts[curattr] += 1
current_attribute_value_freq = to_attr_counts[curattr]
current_centroid_value = centroids[to_clust][iattr]
current_centroid_freq = to_attr_counts[current_centroid_value]
if current_centroid_freq < current_attribute_value_freq:
# We have incremented this value to the new mode. Update the centroid.
centroids[to_clust][iattr] = curattr
# Decrement the attribute count for the old "from" cluster
from_attr_counts[curattr] -= 1
old_centroid_value = centroids[from_clust][iattr]
if old_centroid_value == curattr:
# We have just removed a count from the old centroid value. We need to
# recalculate the centroid as it may no longer be the maximum
centroids[from_clust][iattr] = get_max_value_key(from_attr_counts)
return cl_attr_freq, membship, centroids
def _labels_cost(X, centroids, dissim, membship=None):
"""Calculate labels and cost function given a matrix of points and
a list of centroids for the k-modes algorithm.
"""
X = check_array(X)
n_points = X.shape[0]
cost = 0.
labels = np.empty(n_points, dtype=np.uint16)
for ipoint, curpoint in enumerate(X):
diss = dissim(centroids, curpoint, X=X, membship=membship)
clust = np.argmin(diss)
labels[ipoint] = clust
cost += diss[clust]
return labels, cost
def k_modes_single(X, n_clusters, n_points, n_attrs, max_iter, dissim, init, init_no,
verbose, random_state):
random_state = check_random_state(random_state)
# _____ INIT _____
if verbose:
print("Init: initializing centroids")
if isinstance(init, str) and init.lower() == 'huang':
centroids = init_huang(X, n_clusters, dissim, random_state)
elif isinstance(init, str) and init.lower() == 'cao':
centroids = init_cao(X, n_clusters, dissim)
elif isinstance(init, str) and init.lower() == 'random':
seeds = random_state.choice(range(n_points), n_clusters)
centroids = X[seeds]
elif hasattr(init, '__array__'):
# Make sure init is a 2D array.
if len(init.shape) == 1:
init = np.atleast_2d(init).T
assert init.shape[0] == n_clusters, \
"Wrong number of initial centroids in init ({}, should be {})." \
.format(init.shape[0], n_clusters)
assert init.shape[1] == n_attrs, \
"Wrong number of attributes in init ({}, should be {})." \
.format(init.shape[1], n_attrs)
centroids = np.asarray(init, dtype=np.uint16)
else:
raise NotImplementedError
if verbose:
print("Init: initializing clusters")
membship = np.zeros((n_clusters, n_points), dtype=np.uint8)
# cl_attr_freq is a list of lists with dictionaries that contain the
# frequencies of values per cluster and attribute.
cl_attr_freq = [[defaultdict(int) for _ in range(n_attrs)]
for _ in range(n_clusters)]
for ipoint, curpoint in enumerate(X):
# Initial assignment to clusters
clust = np.argmin(dissim(centroids, curpoint, X=X, membship=membship))
membship[clust, ipoint] = 1
# Count attribute values per cluster.
for iattr, curattr in enumerate(curpoint):
cl_attr_freq[clust][iattr][curattr] += 1
# Perform an initial centroid update.
for ik in range(n_clusters):
for iattr in range(n_attrs):
if sum(membship[ik]) == 0:
# Empty centroid, choose randomly
centroids[ik, iattr] = random_state.choice(X[:, iattr])
else:
centroids[ik, iattr] = get_max_value_key(cl_attr_freq[ik][iattr])
# _____ ITERATION _____
if verbose:
print("Starting iterations...")
itr = 0
labels = None
converged = False
cost = np.Inf
while itr <= max_iter and not converged:
itr += 1
centroids, moves = _k_modes_iter(
X,
centroids,
cl_attr_freq,
membship,
dissim,
random_state
)
# All points seen in this iteration
labels, ncost = _labels_cost(X, centroids, dissim, membship)
converged = (moves == 0) or (ncost >= cost)
cost = ncost
if verbose:
print("Run {}, iteration: {}/{}, moves: {}, cost: {}"
.format(init_no + 1, itr, max_iter, moves, cost))
return centroids, labels, cost, itr
def k_modes(X, n_clusters, max_iter, dissim, init, n_init, verbose, random_state, n_jobs):
"""k-modes algorithm"""
random_state = check_random_state(random_state)
if sparse.issparse(X):
raise TypeError("k-modes does not support sparse data.")
X = check_array(X, dtype=None)
# Convert the categorical values in X to integers for speed.
# Based on the unique values in X, we can make a mapping to achieve this.
X, enc_map = encode_features(X)
n_points, n_attrs = X.shape
assert n_clusters <= n_points, "Cannot have more clusters ({}) " \
"than data points ({}).".format(n_clusters, n_points)
# Are there more n_clusters than unique rows? Then set the unique
# rows as initial values and skip iteration.
unique = get_unique_rows(X)
n_unique = unique.shape[0]
if n_unique <= n_clusters:
max_iter = 0
n_init = 1
n_clusters = n_unique
init = unique
results = []
seeds = random_state.randint(np.iinfo(np.int32).max, size=n_init)
if n_jobs == 1:
for init_no in range(n_init):
results.append(k_modes_single(X, n_clusters, n_points, n_attrs, max_iter,
dissim, init, init_no, verbose, seeds[init_no]))
else:
results = Parallel(n_jobs=n_jobs, verbose=0)(
delayed(k_modes_single)(X, n_clusters, n_points, n_attrs, max_iter,
dissim, init, init_no, verbose, seed)
for init_no, seed in enumerate(seeds))
all_centroids, all_labels, all_costs, all_n_iters = zip(*results)
best = np.argmin(all_costs)
if n_init > 1 and verbose:
print("Best run was number {}".format(best + 1))
return all_centroids[best], enc_map, all_labels[best], \
all_costs[best], all_n_iters[best]
class KModes(BaseEstimator, ClusterMixin):
"""k-modes clustering algorithm for categorical data.
Parameters
-----------
n_clusters : int, optional, default: 8
The number of clusters to form as well as the number of
centroids to generate.
max_iter : int, default: 300
Maximum number of iterations of the k-modes algorithm for a
single run.
cat_dissim : func, default: matching_dissim
Dissimilarity function used by the k-modes algorithm for categorical variables.
Defaults to the matching dissimilarity function.
init : {'Huang', 'Cao', 'random' or an ndarray}, default: 'Cao'
Method for initialization:
'Huang': Method in Huang [1997, 1998]
'Cao': Method in Cao et al. [2009]
'random': choose 'n_clusters' observations (rows) at random from
data for the initial centroids.
If an ndarray is passed, it should be of shape (n_clusters, n_features)
and gives the initial centroids.
n_init : int, default: 10
Number of time the k-modes algorithm will be run with different
centroid seeds. The final results will be the best output of
n_init consecutive runs in terms of cost.
verbose : int, optional
Verbosity mode.
random_state : int, RandomState instance or None, optional, default: None
If int, random_state is the seed used by the random number generator;
If RandomState instance, random_state is the random number generator;
If None, the random number generator is the RandomState instance used
by `np.random`.
n_jobs : int, default: 1
The number of jobs to use for the computation. This works by computing
each of the n_init runs in parallel.
If -1 all CPUs are used. If 1 is given, no parallel computing code is
used at all, which is useful for debugging. For n_jobs below -1,
(n_cpus + 1 + n_jobs) are used. Thus for n_jobs = -2, all CPUs but one
are used.
Attributes
----------
cluster_centroids_ : array, [n_clusters, n_features]
Categories of cluster centroids
labels_ :
Labels of each point
cost_ : float
Clustering cost, defined as the sum distance of all points to
their respective cluster centroids.
n_iter_ : int
The number of iterations the algorithm ran for.
Notes
-----
See:
Huang, Z.: Extensions to the k-modes algorithm for clustering large
data sets with categorical values, Data Mining and Knowledge
Discovery 2(3), 1998.
"""
def __init__(self, n_clusters=8, max_iter=100, cat_dissim=matching_dissim,
init='Cao', n_init=1, verbose=0, random_state=None, n_jobs=1):
self.n_clusters = n_clusters
self.max_iter = max_iter
self.cat_dissim = cat_dissim
self.init = init
self.n_init = n_init
self.verbose = verbose
self.random_state = random_state
self.n_jobs = n_jobs
if ((isinstance(self.init, str) and self.init == 'Cao') or
hasattr(self.init, '__array__')) and self.n_init > 1:
if self.verbose:
print("Initialization method and algorithm are deterministic. "
"Setting n_init to 1.")
self.n_init = 1
def fit(self, X, y=None, **kwargs):
"""Compute k-modes clustering.
Parameters
----------
X : array-like, shape=[n_samples, n_features]
"""
X = pandas_to_numpy(X)
random_state = check_random_state(self.random_state)
self._enc_cluster_centroids, self._enc_map, self.labels_,\
self.cost_, self.n_iter_ = k_modes(X,
self.n_clusters,
self.max_iter,
self.cat_dissim,
self.init,
self.n_init,
self.verbose,
random_state,
self.n_jobs)
return self
def fit_predict(self, X, y=None, **kwargs):
"""Compute cluster centroids and predict cluster index for each sample.
Convenience method; equivalent to calling fit(X) followed by
predict(X).
"""
return self.fit(X, **kwargs).predict(X, **kwargs)
def predict(self, X, **kwargs):
"""Predict the closest cluster each sample in X belongs to.
Parameters
----------
X : array-like, shape = [n_samples, n_features]
New data to predict.
Returns
-------
labels : array, shape [n_samples,]
Index of the cluster each sample belongs to.
"""
assert hasattr(self, '_enc_cluster_centroids'), "Model not yet fitted."
if self.verbose and self.cat_dissim == ng_dissim:
print("Ng's dissimilarity measure was used to train this model, "
"but now that it is predicting the model will fall back to "
"using simple matching dissimilarity.")
X = pandas_to_numpy(X)
X = check_array(X, dtype=None)
X, _ = encode_features(X, enc_map=self._enc_map)
return _labels_cost(X, self._enc_cluster_centroids, self.cat_dissim)[0]
@property
def cluster_centroids_(self):
if hasattr(self, '_enc_cluster_centroids'):
return decode_centroids(self._enc_cluster_centroids, self._enc_map)
else:
raise AttributeError("'{}' object has no attribute 'cluster_centroids_' "
"because the model is not yet fitted.")
|
nicodv/kmodes | kmodes/kmodes.py | k_modes | python | def k_modes(X, n_clusters, max_iter, dissim, init, n_init, verbose, random_state, n_jobs):
random_state = check_random_state(random_state)
if sparse.issparse(X):
raise TypeError("k-modes does not support sparse data.")
X = check_array(X, dtype=None)
# Convert the categorical values in X to integers for speed.
# Based on the unique values in X, we can make a mapping to achieve this.
X, enc_map = encode_features(X)
n_points, n_attrs = X.shape
assert n_clusters <= n_points, "Cannot have more clusters ({}) " \
"than data points ({}).".format(n_clusters, n_points)
# Are there more n_clusters than unique rows? Then set the unique
# rows as initial values and skip iteration.
unique = get_unique_rows(X)
n_unique = unique.shape[0]
if n_unique <= n_clusters:
max_iter = 0
n_init = 1
n_clusters = n_unique
init = unique
results = []
seeds = random_state.randint(np.iinfo(np.int32).max, size=n_init)
if n_jobs == 1:
for init_no in range(n_init):
results.append(k_modes_single(X, n_clusters, n_points, n_attrs, max_iter,
dissim, init, init_no, verbose, seeds[init_no]))
else:
results = Parallel(n_jobs=n_jobs, verbose=0)(
delayed(k_modes_single)(X, n_clusters, n_points, n_attrs, max_iter,
dissim, init, init_no, verbose, seed)
for init_no, seed in enumerate(seeds))
all_centroids, all_labels, all_costs, all_n_iters = zip(*results)
best = np.argmin(all_costs)
if n_init > 1 and verbose:
print("Best run was number {}".format(best + 1))
return all_centroids[best], enc_map, all_labels[best], \
all_costs[best], all_n_iters[best] | k-modes algorithm | train | https://github.com/nicodv/kmodes/blob/cdb19fe5448aba1bf501626694bb52e68eafab45/kmodes/kmodes.py#L243-L287 | [
"def encode_features(X, enc_map=None):\n \"\"\"Converts categorical values in each column of X to integers in the range\n [0, n_unique_values_in_column - 1], if X is not already of integer type.\n\n If mapping is not provided, it is calculated based on the values in X.\n\n Unknown values during prediction get a value of -1. np.NaNs are ignored\n during encoding, and get treated as unknowns during prediction.\n \"\"\"\n if enc_map is None:\n fit = True\n # We will calculate enc_map, so initialize the list of column mappings.\n enc_map = []\n else:\n fit = False\n\n Xenc = np.zeros(X.shape).astype('int')\n for ii in range(X.shape[1]):\n if fit:\n col_enc = {val: jj for jj, val in enumerate(np.unique(X[:, ii]))\n if not (isinstance(val, float) and np.isnan(val))}\n enc_map.append(col_enc)\n # Unknown categories (including np.NaNs) all get a value of -1.\n Xenc[:, ii] = np.array([enc_map[ii].get(x, -1) for x in X[:, ii]])\n\n return Xenc, enc_map\n",
"def get_unique_rows(a):\n \"\"\"Gets the unique rows in a numpy array.\"\"\"\n return np.vstack(list({tuple(row) for row in a}))\n",
"def k_modes_single(X, n_clusters, n_points, n_attrs, max_iter, dissim, init, init_no,\n verbose, random_state):\n random_state = check_random_state(random_state)\n # _____ INIT _____\n if verbose:\n print(\"Init: initializing centroids\")\n if isinstance(init, str) and init.lower() == 'huang':\n centroids = init_huang(X, n_clusters, dissim, random_state)\n elif isinstance(init, str) and init.lower() == 'cao':\n centroids = init_cao(X, n_clusters, dissim)\n elif isinstance(init, str) and init.lower() == 'random':\n seeds = random_state.choice(range(n_points), n_clusters)\n centroids = X[seeds]\n elif hasattr(init, '__array__'):\n # Make sure init is a 2D array.\n if len(init.shape) == 1:\n init = np.atleast_2d(init).T\n assert init.shape[0] == n_clusters, \\\n \"Wrong number of initial centroids in init ({}, should be {}).\" \\\n .format(init.shape[0], n_clusters)\n assert init.shape[1] == n_attrs, \\\n \"Wrong number of attributes in init ({}, should be {}).\" \\\n .format(init.shape[1], n_attrs)\n centroids = np.asarray(init, dtype=np.uint16)\n else:\n raise NotImplementedError\n\n if verbose:\n print(\"Init: initializing clusters\")\n membship = np.zeros((n_clusters, n_points), dtype=np.uint8)\n # cl_attr_freq is a list of lists with dictionaries that contain the\n # frequencies of values per cluster and attribute.\n cl_attr_freq = [[defaultdict(int) for _ in range(n_attrs)]\n for _ in range(n_clusters)]\n for ipoint, curpoint in enumerate(X):\n # Initial assignment to clusters\n clust = np.argmin(dissim(centroids, curpoint, X=X, membship=membship))\n membship[clust, ipoint] = 1\n # Count attribute values per cluster.\n for iattr, curattr in enumerate(curpoint):\n cl_attr_freq[clust][iattr][curattr] += 1\n # Perform an initial centroid update.\n for ik in range(n_clusters):\n for iattr in range(n_attrs):\n if sum(membship[ik]) == 0:\n # Empty centroid, choose randomly\n centroids[ik, iattr] = random_state.choice(X[:, iattr])\n else:\n centroids[ik, iattr] = get_max_value_key(cl_attr_freq[ik][iattr])\n\n # _____ ITERATION _____\n if verbose:\n print(\"Starting iterations...\")\n itr = 0\n labels = None\n converged = False\n cost = np.Inf\n while itr <= max_iter and not converged:\n itr += 1\n centroids, moves = _k_modes_iter(\n X,\n centroids,\n cl_attr_freq,\n membship,\n dissim,\n random_state\n )\n # All points seen in this iteration\n labels, ncost = _labels_cost(X, centroids, dissim, membship)\n converged = (moves == 0) or (ncost >= cost)\n cost = ncost\n if verbose:\n print(\"Run {}, iteration: {}/{}, moves: {}, cost: {}\"\n .format(init_no + 1, itr, max_iter, moves, cost))\n\n return centroids, labels, cost, itr\n"
] | """
K-modes clustering for categorical data
"""
# pylint: disable=unused-argument,attribute-defined-outside-init
from collections import defaultdict
import numpy as np
from joblib import Parallel, delayed
from scipy import sparse
from sklearn.base import BaseEstimator, ClusterMixin
from sklearn.utils import check_random_state
from sklearn.utils.validation import check_array
from .util import get_max_value_key, encode_features, get_unique_rows, \
decode_centroids, pandas_to_numpy
from .util.dissim import matching_dissim, ng_dissim
def init_huang(X, n_clusters, dissim, random_state):
"""Initialize centroids according to method by Huang [1997]."""
n_attrs = X.shape[1]
centroids = np.empty((n_clusters, n_attrs), dtype='object')
# determine frequencies of attributes
for iattr in range(n_attrs):
freq = defaultdict(int)
for curattr in X[:, iattr]:
freq[curattr] += 1
# Sample centroids using the probabilities of attributes.
# (I assume that's what's meant in the Huang [1998] paper; it works,
# at least)
# Note: sampling using population in static list with as many choices
# as frequency counts. Since the counts are small integers,
# memory consumption is low.
choices = [chc for chc, wght in freq.items() for _ in range(wght)]
# So that we are consistent between Python versions,
# each with different dict ordering.
choices = sorted(choices)
centroids[:, iattr] = random_state.choice(choices, n_clusters)
# The previously chosen centroids could result in empty clusters,
# so set centroid to closest point in X.
for ik in range(n_clusters):
ndx = np.argsort(dissim(X, centroids[ik]))
# We want the centroid to be unique, if possible.
while np.all(X[ndx[0]] == centroids, axis=1).any() and ndx.shape[0] > 1:
ndx = np.delete(ndx, 0)
centroids[ik] = X[ndx[0]]
return centroids
def init_cao(X, n_clusters, dissim):
"""Initialize centroids according to method by Cao et al. [2009].
Note: O(N * attr * n_clusters**2), so watch out with large n_clusters
"""
n_points, n_attrs = X.shape
centroids = np.empty((n_clusters, n_attrs), dtype='object')
# Method is based on determining density of points.
dens = np.zeros(n_points)
for iattr in range(n_attrs):
freq = defaultdict(int)
for val in X[:, iattr]:
freq[val] += 1
for ipoint in range(n_points):
dens[ipoint] += freq[X[ipoint, iattr]] / float(n_points) / float(n_attrs)
# Choose initial centroids based on distance and density.
centroids[0] = X[np.argmax(dens)]
if n_clusters > 1:
# For the remaining centroids, choose maximum dens * dissim to the
# (already assigned) centroid with the lowest dens * dissim.
for ik in range(1, n_clusters):
dd = np.empty((ik, n_points))
for ikk in range(ik):
dd[ikk] = dissim(X, centroids[ikk]) * dens
centroids[ik] = X[np.argmax(np.min(dd, axis=0))]
return centroids
def move_point_cat(point, ipoint, to_clust, from_clust, cl_attr_freq,
membship, centroids):
"""Move point between clusters, categorical attributes."""
membship[to_clust, ipoint] = 1
membship[from_clust, ipoint] = 0
# Update frequencies of attributes in cluster.
for iattr, curattr in enumerate(point):
to_attr_counts = cl_attr_freq[to_clust][iattr]
from_attr_counts = cl_attr_freq[from_clust][iattr]
# Increment the attribute count for the new "to" cluster
to_attr_counts[curattr] += 1
current_attribute_value_freq = to_attr_counts[curattr]
current_centroid_value = centroids[to_clust][iattr]
current_centroid_freq = to_attr_counts[current_centroid_value]
if current_centroid_freq < current_attribute_value_freq:
# We have incremented this value to the new mode. Update the centroid.
centroids[to_clust][iattr] = curattr
# Decrement the attribute count for the old "from" cluster
from_attr_counts[curattr] -= 1
old_centroid_value = centroids[from_clust][iattr]
if old_centroid_value == curattr:
# We have just removed a count from the old centroid value. We need to
# recalculate the centroid as it may no longer be the maximum
centroids[from_clust][iattr] = get_max_value_key(from_attr_counts)
return cl_attr_freq, membship, centroids
def _labels_cost(X, centroids, dissim, membship=None):
"""Calculate labels and cost function given a matrix of points and
a list of centroids for the k-modes algorithm.
"""
X = check_array(X)
n_points = X.shape[0]
cost = 0.
labels = np.empty(n_points, dtype=np.uint16)
for ipoint, curpoint in enumerate(X):
diss = dissim(centroids, curpoint, X=X, membship=membship)
clust = np.argmin(diss)
labels[ipoint] = clust
cost += diss[clust]
return labels, cost
def _k_modes_iter(X, centroids, cl_attr_freq, membship, dissim, random_state):
"""Single iteration of k-modes clustering algorithm"""
moves = 0
for ipoint, curpoint in enumerate(X):
clust = np.argmin(dissim(centroids, curpoint, X=X, membship=membship))
if membship[clust, ipoint]:
# Point is already in its right place.
continue
# Move point, and update old/new cluster frequencies and centroids.
moves += 1
old_clust = np.argwhere(membship[:, ipoint])[0][0]
cl_attr_freq, membship, centroids = move_point_cat(
curpoint, ipoint, clust, old_clust, cl_attr_freq, membship, centroids
)
# In case of an empty cluster, reinitialize with a random point
# from the largest cluster.
if not membship[old_clust, :].any():
from_clust = membship.sum(axis=1).argmax()
choices = [ii for ii, ch in enumerate(membship[from_clust, :]) if ch]
rindx = random_state.choice(choices)
cl_attr_freq, membship, centroids = move_point_cat(
X[rindx], rindx, old_clust, from_clust, cl_attr_freq, membship, centroids
)
return centroids, moves
def k_modes_single(X, n_clusters, n_points, n_attrs, max_iter, dissim, init, init_no,
verbose, random_state):
random_state = check_random_state(random_state)
# _____ INIT _____
if verbose:
print("Init: initializing centroids")
if isinstance(init, str) and init.lower() == 'huang':
centroids = init_huang(X, n_clusters, dissim, random_state)
elif isinstance(init, str) and init.lower() == 'cao':
centroids = init_cao(X, n_clusters, dissim)
elif isinstance(init, str) and init.lower() == 'random':
seeds = random_state.choice(range(n_points), n_clusters)
centroids = X[seeds]
elif hasattr(init, '__array__'):
# Make sure init is a 2D array.
if len(init.shape) == 1:
init = np.atleast_2d(init).T
assert init.shape[0] == n_clusters, \
"Wrong number of initial centroids in init ({}, should be {})." \
.format(init.shape[0], n_clusters)
assert init.shape[1] == n_attrs, \
"Wrong number of attributes in init ({}, should be {})." \
.format(init.shape[1], n_attrs)
centroids = np.asarray(init, dtype=np.uint16)
else:
raise NotImplementedError
if verbose:
print("Init: initializing clusters")
membship = np.zeros((n_clusters, n_points), dtype=np.uint8)
# cl_attr_freq is a list of lists with dictionaries that contain the
# frequencies of values per cluster and attribute.
cl_attr_freq = [[defaultdict(int) for _ in range(n_attrs)]
for _ in range(n_clusters)]
for ipoint, curpoint in enumerate(X):
# Initial assignment to clusters
clust = np.argmin(dissim(centroids, curpoint, X=X, membship=membship))
membship[clust, ipoint] = 1
# Count attribute values per cluster.
for iattr, curattr in enumerate(curpoint):
cl_attr_freq[clust][iattr][curattr] += 1
# Perform an initial centroid update.
for ik in range(n_clusters):
for iattr in range(n_attrs):
if sum(membship[ik]) == 0:
# Empty centroid, choose randomly
centroids[ik, iattr] = random_state.choice(X[:, iattr])
else:
centroids[ik, iattr] = get_max_value_key(cl_attr_freq[ik][iattr])
# _____ ITERATION _____
if verbose:
print("Starting iterations...")
itr = 0
labels = None
converged = False
cost = np.Inf
while itr <= max_iter and not converged:
itr += 1
centroids, moves = _k_modes_iter(
X,
centroids,
cl_attr_freq,
membship,
dissim,
random_state
)
# All points seen in this iteration
labels, ncost = _labels_cost(X, centroids, dissim, membship)
converged = (moves == 0) or (ncost >= cost)
cost = ncost
if verbose:
print("Run {}, iteration: {}/{}, moves: {}, cost: {}"
.format(init_no + 1, itr, max_iter, moves, cost))
return centroids, labels, cost, itr
class KModes(BaseEstimator, ClusterMixin):
"""k-modes clustering algorithm for categorical data.
Parameters
-----------
n_clusters : int, optional, default: 8
The number of clusters to form as well as the number of
centroids to generate.
max_iter : int, default: 300
Maximum number of iterations of the k-modes algorithm for a
single run.
cat_dissim : func, default: matching_dissim
Dissimilarity function used by the k-modes algorithm for categorical variables.
Defaults to the matching dissimilarity function.
init : {'Huang', 'Cao', 'random' or an ndarray}, default: 'Cao'
Method for initialization:
'Huang': Method in Huang [1997, 1998]
'Cao': Method in Cao et al. [2009]
'random': choose 'n_clusters' observations (rows) at random from
data for the initial centroids.
If an ndarray is passed, it should be of shape (n_clusters, n_features)
and gives the initial centroids.
n_init : int, default: 10
Number of time the k-modes algorithm will be run with different
centroid seeds. The final results will be the best output of
n_init consecutive runs in terms of cost.
verbose : int, optional
Verbosity mode.
random_state : int, RandomState instance or None, optional, default: None
If int, random_state is the seed used by the random number generator;
If RandomState instance, random_state is the random number generator;
If None, the random number generator is the RandomState instance used
by `np.random`.
n_jobs : int, default: 1
The number of jobs to use for the computation. This works by computing
each of the n_init runs in parallel.
If -1 all CPUs are used. If 1 is given, no parallel computing code is
used at all, which is useful for debugging. For n_jobs below -1,
(n_cpus + 1 + n_jobs) are used. Thus for n_jobs = -2, all CPUs but one
are used.
Attributes
----------
cluster_centroids_ : array, [n_clusters, n_features]
Categories of cluster centroids
labels_ :
Labels of each point
cost_ : float
Clustering cost, defined as the sum distance of all points to
their respective cluster centroids.
n_iter_ : int
The number of iterations the algorithm ran for.
Notes
-----
See:
Huang, Z.: Extensions to the k-modes algorithm for clustering large
data sets with categorical values, Data Mining and Knowledge
Discovery 2(3), 1998.
"""
def __init__(self, n_clusters=8, max_iter=100, cat_dissim=matching_dissim,
init='Cao', n_init=1, verbose=0, random_state=None, n_jobs=1):
self.n_clusters = n_clusters
self.max_iter = max_iter
self.cat_dissim = cat_dissim
self.init = init
self.n_init = n_init
self.verbose = verbose
self.random_state = random_state
self.n_jobs = n_jobs
if ((isinstance(self.init, str) and self.init == 'Cao') or
hasattr(self.init, '__array__')) and self.n_init > 1:
if self.verbose:
print("Initialization method and algorithm are deterministic. "
"Setting n_init to 1.")
self.n_init = 1
def fit(self, X, y=None, **kwargs):
"""Compute k-modes clustering.
Parameters
----------
X : array-like, shape=[n_samples, n_features]
"""
X = pandas_to_numpy(X)
random_state = check_random_state(self.random_state)
self._enc_cluster_centroids, self._enc_map, self.labels_,\
self.cost_, self.n_iter_ = k_modes(X,
self.n_clusters,
self.max_iter,
self.cat_dissim,
self.init,
self.n_init,
self.verbose,
random_state,
self.n_jobs)
return self
def fit_predict(self, X, y=None, **kwargs):
"""Compute cluster centroids and predict cluster index for each sample.
Convenience method; equivalent to calling fit(X) followed by
predict(X).
"""
return self.fit(X, **kwargs).predict(X, **kwargs)
def predict(self, X, **kwargs):
"""Predict the closest cluster each sample in X belongs to.
Parameters
----------
X : array-like, shape = [n_samples, n_features]
New data to predict.
Returns
-------
labels : array, shape [n_samples,]
Index of the cluster each sample belongs to.
"""
assert hasattr(self, '_enc_cluster_centroids'), "Model not yet fitted."
if self.verbose and self.cat_dissim == ng_dissim:
print("Ng's dissimilarity measure was used to train this model, "
"but now that it is predicting the model will fall back to "
"using simple matching dissimilarity.")
X = pandas_to_numpy(X)
X = check_array(X, dtype=None)
X, _ = encode_features(X, enc_map=self._enc_map)
return _labels_cost(X, self._enc_cluster_centroids, self.cat_dissim)[0]
@property
def cluster_centroids_(self):
if hasattr(self, '_enc_cluster_centroids'):
return decode_centroids(self._enc_cluster_centroids, self._enc_map)
else:
raise AttributeError("'{}' object has no attribute 'cluster_centroids_' "
"because the model is not yet fitted.")
|
nicodv/kmodes | kmodes/kmodes.py | KModes.fit | python | def fit(self, X, y=None, **kwargs):
X = pandas_to_numpy(X)
random_state = check_random_state(self.random_state)
self._enc_cluster_centroids, self._enc_map, self.labels_,\
self.cost_, self.n_iter_ = k_modes(X,
self.n_clusters,
self.max_iter,
self.cat_dissim,
self.init,
self.n_init,
self.verbose,
random_state,
self.n_jobs)
return self | Compute k-modes clustering.
Parameters
----------
X : array-like, shape=[n_samples, n_features] | train | https://github.com/nicodv/kmodes/blob/cdb19fe5448aba1bf501626694bb52e68eafab45/kmodes/kmodes.py#L381-L401 | [
"def pandas_to_numpy(x):\n return x.values if 'pandas' in str(x.__class__) else x\n",
"def k_modes(X, n_clusters, max_iter, dissim, init, n_init, verbose, random_state, n_jobs):\n \"\"\"k-modes algorithm\"\"\"\n random_state = check_random_state(random_state)\n if sparse.issparse(X):\n raise TypeError(\"k-modes does not support sparse data.\")\n\n X = check_array(X, dtype=None)\n\n # Convert the categorical values in X to integers for speed.\n # Based on the unique values in X, we can make a mapping to achieve this.\n X, enc_map = encode_features(X)\n\n n_points, n_attrs = X.shape\n assert n_clusters <= n_points, \"Cannot have more clusters ({}) \" \\\n \"than data points ({}).\".format(n_clusters, n_points)\n\n # Are there more n_clusters than unique rows? Then set the unique\n # rows as initial values and skip iteration.\n unique = get_unique_rows(X)\n n_unique = unique.shape[0]\n if n_unique <= n_clusters:\n max_iter = 0\n n_init = 1\n n_clusters = n_unique\n init = unique\n\n results = []\n seeds = random_state.randint(np.iinfo(np.int32).max, size=n_init)\n if n_jobs == 1:\n for init_no in range(n_init):\n results.append(k_modes_single(X, n_clusters, n_points, n_attrs, max_iter,\n dissim, init, init_no, verbose, seeds[init_no]))\n else:\n results = Parallel(n_jobs=n_jobs, verbose=0)(\n delayed(k_modes_single)(X, n_clusters, n_points, n_attrs, max_iter,\n dissim, init, init_no, verbose, seed)\n for init_no, seed in enumerate(seeds))\n all_centroids, all_labels, all_costs, all_n_iters = zip(*results)\n\n best = np.argmin(all_costs)\n if n_init > 1 and verbose:\n print(\"Best run was number {}\".format(best + 1))\n\n return all_centroids[best], enc_map, all_labels[best], \\\n all_costs[best], all_n_iters[best]\n"
] | class KModes(BaseEstimator, ClusterMixin):
"""k-modes clustering algorithm for categorical data.
Parameters
-----------
n_clusters : int, optional, default: 8
The number of clusters to form as well as the number of
centroids to generate.
max_iter : int, default: 300
Maximum number of iterations of the k-modes algorithm for a
single run.
cat_dissim : func, default: matching_dissim
Dissimilarity function used by the k-modes algorithm for categorical variables.
Defaults to the matching dissimilarity function.
init : {'Huang', 'Cao', 'random' or an ndarray}, default: 'Cao'
Method for initialization:
'Huang': Method in Huang [1997, 1998]
'Cao': Method in Cao et al. [2009]
'random': choose 'n_clusters' observations (rows) at random from
data for the initial centroids.
If an ndarray is passed, it should be of shape (n_clusters, n_features)
and gives the initial centroids.
n_init : int, default: 10
Number of time the k-modes algorithm will be run with different
centroid seeds. The final results will be the best output of
n_init consecutive runs in terms of cost.
verbose : int, optional
Verbosity mode.
random_state : int, RandomState instance or None, optional, default: None
If int, random_state is the seed used by the random number generator;
If RandomState instance, random_state is the random number generator;
If None, the random number generator is the RandomState instance used
by `np.random`.
n_jobs : int, default: 1
The number of jobs to use for the computation. This works by computing
each of the n_init runs in parallel.
If -1 all CPUs are used. If 1 is given, no parallel computing code is
used at all, which is useful for debugging. For n_jobs below -1,
(n_cpus + 1 + n_jobs) are used. Thus for n_jobs = -2, all CPUs but one
are used.
Attributes
----------
cluster_centroids_ : array, [n_clusters, n_features]
Categories of cluster centroids
labels_ :
Labels of each point
cost_ : float
Clustering cost, defined as the sum distance of all points to
their respective cluster centroids.
n_iter_ : int
The number of iterations the algorithm ran for.
Notes
-----
See:
Huang, Z.: Extensions to the k-modes algorithm for clustering large
data sets with categorical values, Data Mining and Knowledge
Discovery 2(3), 1998.
"""
def __init__(self, n_clusters=8, max_iter=100, cat_dissim=matching_dissim,
init='Cao', n_init=1, verbose=0, random_state=None, n_jobs=1):
self.n_clusters = n_clusters
self.max_iter = max_iter
self.cat_dissim = cat_dissim
self.init = init
self.n_init = n_init
self.verbose = verbose
self.random_state = random_state
self.n_jobs = n_jobs
if ((isinstance(self.init, str) and self.init == 'Cao') or
hasattr(self.init, '__array__')) and self.n_init > 1:
if self.verbose:
print("Initialization method and algorithm are deterministic. "
"Setting n_init to 1.")
self.n_init = 1
def fit_predict(self, X, y=None, **kwargs):
"""Compute cluster centroids and predict cluster index for each sample.
Convenience method; equivalent to calling fit(X) followed by
predict(X).
"""
return self.fit(X, **kwargs).predict(X, **kwargs)
def predict(self, X, **kwargs):
"""Predict the closest cluster each sample in X belongs to.
Parameters
----------
X : array-like, shape = [n_samples, n_features]
New data to predict.
Returns
-------
labels : array, shape [n_samples,]
Index of the cluster each sample belongs to.
"""
assert hasattr(self, '_enc_cluster_centroids'), "Model not yet fitted."
if self.verbose and self.cat_dissim == ng_dissim:
print("Ng's dissimilarity measure was used to train this model, "
"but now that it is predicting the model will fall back to "
"using simple matching dissimilarity.")
X = pandas_to_numpy(X)
X = check_array(X, dtype=None)
X, _ = encode_features(X, enc_map=self._enc_map)
return _labels_cost(X, self._enc_cluster_centroids, self.cat_dissim)[0]
@property
def cluster_centroids_(self):
if hasattr(self, '_enc_cluster_centroids'):
return decode_centroids(self._enc_cluster_centroids, self._enc_map)
else:
raise AttributeError("'{}' object has no attribute 'cluster_centroids_' "
"because the model is not yet fitted.")
|
nicodv/kmodes | kmodes/kmodes.py | KModes.fit_predict | python | def fit_predict(self, X, y=None, **kwargs):
return self.fit(X, **kwargs).predict(X, **kwargs) | Compute cluster centroids and predict cluster index for each sample.
Convenience method; equivalent to calling fit(X) followed by
predict(X). | train | https://github.com/nicodv/kmodes/blob/cdb19fe5448aba1bf501626694bb52e68eafab45/kmodes/kmodes.py#L403-L409 | null | class KModes(BaseEstimator, ClusterMixin):
"""k-modes clustering algorithm for categorical data.
Parameters
-----------
n_clusters : int, optional, default: 8
The number of clusters to form as well as the number of
centroids to generate.
max_iter : int, default: 300
Maximum number of iterations of the k-modes algorithm for a
single run.
cat_dissim : func, default: matching_dissim
Dissimilarity function used by the k-modes algorithm for categorical variables.
Defaults to the matching dissimilarity function.
init : {'Huang', 'Cao', 'random' or an ndarray}, default: 'Cao'
Method for initialization:
'Huang': Method in Huang [1997, 1998]
'Cao': Method in Cao et al. [2009]
'random': choose 'n_clusters' observations (rows) at random from
data for the initial centroids.
If an ndarray is passed, it should be of shape (n_clusters, n_features)
and gives the initial centroids.
n_init : int, default: 10
Number of time the k-modes algorithm will be run with different
centroid seeds. The final results will be the best output of
n_init consecutive runs in terms of cost.
verbose : int, optional
Verbosity mode.
random_state : int, RandomState instance or None, optional, default: None
If int, random_state is the seed used by the random number generator;
If RandomState instance, random_state is the random number generator;
If None, the random number generator is the RandomState instance used
by `np.random`.
n_jobs : int, default: 1
The number of jobs to use for the computation. This works by computing
each of the n_init runs in parallel.
If -1 all CPUs are used. If 1 is given, no parallel computing code is
used at all, which is useful for debugging. For n_jobs below -1,
(n_cpus + 1 + n_jobs) are used. Thus for n_jobs = -2, all CPUs but one
are used.
Attributes
----------
cluster_centroids_ : array, [n_clusters, n_features]
Categories of cluster centroids
labels_ :
Labels of each point
cost_ : float
Clustering cost, defined as the sum distance of all points to
their respective cluster centroids.
n_iter_ : int
The number of iterations the algorithm ran for.
Notes
-----
See:
Huang, Z.: Extensions to the k-modes algorithm for clustering large
data sets with categorical values, Data Mining and Knowledge
Discovery 2(3), 1998.
"""
def __init__(self, n_clusters=8, max_iter=100, cat_dissim=matching_dissim,
init='Cao', n_init=1, verbose=0, random_state=None, n_jobs=1):
self.n_clusters = n_clusters
self.max_iter = max_iter
self.cat_dissim = cat_dissim
self.init = init
self.n_init = n_init
self.verbose = verbose
self.random_state = random_state
self.n_jobs = n_jobs
if ((isinstance(self.init, str) and self.init == 'Cao') or
hasattr(self.init, '__array__')) and self.n_init > 1:
if self.verbose:
print("Initialization method and algorithm are deterministic. "
"Setting n_init to 1.")
self.n_init = 1
def fit(self, X, y=None, **kwargs):
"""Compute k-modes clustering.
Parameters
----------
X : array-like, shape=[n_samples, n_features]
"""
X = pandas_to_numpy(X)
random_state = check_random_state(self.random_state)
self._enc_cluster_centroids, self._enc_map, self.labels_,\
self.cost_, self.n_iter_ = k_modes(X,
self.n_clusters,
self.max_iter,
self.cat_dissim,
self.init,
self.n_init,
self.verbose,
random_state,
self.n_jobs)
return self
def predict(self, X, **kwargs):
"""Predict the closest cluster each sample in X belongs to.
Parameters
----------
X : array-like, shape = [n_samples, n_features]
New data to predict.
Returns
-------
labels : array, shape [n_samples,]
Index of the cluster each sample belongs to.
"""
assert hasattr(self, '_enc_cluster_centroids'), "Model not yet fitted."
if self.verbose and self.cat_dissim == ng_dissim:
print("Ng's dissimilarity measure was used to train this model, "
"but now that it is predicting the model will fall back to "
"using simple matching dissimilarity.")
X = pandas_to_numpy(X)
X = check_array(X, dtype=None)
X, _ = encode_features(X, enc_map=self._enc_map)
return _labels_cost(X, self._enc_cluster_centroids, self.cat_dissim)[0]
@property
def cluster_centroids_(self):
if hasattr(self, '_enc_cluster_centroids'):
return decode_centroids(self._enc_cluster_centroids, self._enc_map)
else:
raise AttributeError("'{}' object has no attribute 'cluster_centroids_' "
"because the model is not yet fitted.")
|
nicodv/kmodes | kmodes/kmodes.py | KModes.predict | python | def predict(self, X, **kwargs):
assert hasattr(self, '_enc_cluster_centroids'), "Model not yet fitted."
if self.verbose and self.cat_dissim == ng_dissim:
print("Ng's dissimilarity measure was used to train this model, "
"but now that it is predicting the model will fall back to "
"using simple matching dissimilarity.")
X = pandas_to_numpy(X)
X = check_array(X, dtype=None)
X, _ = encode_features(X, enc_map=self._enc_map)
return _labels_cost(X, self._enc_cluster_centroids, self.cat_dissim)[0] | Predict the closest cluster each sample in X belongs to.
Parameters
----------
X : array-like, shape = [n_samples, n_features]
New data to predict.
Returns
-------
labels : array, shape [n_samples,]
Index of the cluster each sample belongs to. | train | https://github.com/nicodv/kmodes/blob/cdb19fe5448aba1bf501626694bb52e68eafab45/kmodes/kmodes.py#L411-L435 | [
"def pandas_to_numpy(x):\n return x.values if 'pandas' in str(x.__class__) else x\n",
"def encode_features(X, enc_map=None):\n \"\"\"Converts categorical values in each column of X to integers in the range\n [0, n_unique_values_in_column - 1], if X is not already of integer type.\n\n If mapping is not provided, it is calculated based on the values in X.\n\n Unknown values during prediction get a value of -1. np.NaNs are ignored\n during encoding, and get treated as unknowns during prediction.\n \"\"\"\n if enc_map is None:\n fit = True\n # We will calculate enc_map, so initialize the list of column mappings.\n enc_map = []\n else:\n fit = False\n\n Xenc = np.zeros(X.shape).astype('int')\n for ii in range(X.shape[1]):\n if fit:\n col_enc = {val: jj for jj, val in enumerate(np.unique(X[:, ii]))\n if not (isinstance(val, float) and np.isnan(val))}\n enc_map.append(col_enc)\n # Unknown categories (including np.NaNs) all get a value of -1.\n Xenc[:, ii] = np.array([enc_map[ii].get(x, -1) for x in X[:, ii]])\n\n return Xenc, enc_map\n",
"def _labels_cost(X, centroids, dissim, membship=None):\n \"\"\"Calculate labels and cost function given a matrix of points and\n a list of centroids for the k-modes algorithm.\n \"\"\"\n\n X = check_array(X)\n\n n_points = X.shape[0]\n cost = 0.\n labels = np.empty(n_points, dtype=np.uint16)\n for ipoint, curpoint in enumerate(X):\n diss = dissim(centroids, curpoint, X=X, membship=membship)\n clust = np.argmin(diss)\n labels[ipoint] = clust\n cost += diss[clust]\n\n return labels, cost\n"
] | class KModes(BaseEstimator, ClusterMixin):
"""k-modes clustering algorithm for categorical data.
Parameters
-----------
n_clusters : int, optional, default: 8
The number of clusters to form as well as the number of
centroids to generate.
max_iter : int, default: 300
Maximum number of iterations of the k-modes algorithm for a
single run.
cat_dissim : func, default: matching_dissim
Dissimilarity function used by the k-modes algorithm for categorical variables.
Defaults to the matching dissimilarity function.
init : {'Huang', 'Cao', 'random' or an ndarray}, default: 'Cao'
Method for initialization:
'Huang': Method in Huang [1997, 1998]
'Cao': Method in Cao et al. [2009]
'random': choose 'n_clusters' observations (rows) at random from
data for the initial centroids.
If an ndarray is passed, it should be of shape (n_clusters, n_features)
and gives the initial centroids.
n_init : int, default: 10
Number of time the k-modes algorithm will be run with different
centroid seeds. The final results will be the best output of
n_init consecutive runs in terms of cost.
verbose : int, optional
Verbosity mode.
random_state : int, RandomState instance or None, optional, default: None
If int, random_state is the seed used by the random number generator;
If RandomState instance, random_state is the random number generator;
If None, the random number generator is the RandomState instance used
by `np.random`.
n_jobs : int, default: 1
The number of jobs to use for the computation. This works by computing
each of the n_init runs in parallel.
If -1 all CPUs are used. If 1 is given, no parallel computing code is
used at all, which is useful for debugging. For n_jobs below -1,
(n_cpus + 1 + n_jobs) are used. Thus for n_jobs = -2, all CPUs but one
are used.
Attributes
----------
cluster_centroids_ : array, [n_clusters, n_features]
Categories of cluster centroids
labels_ :
Labels of each point
cost_ : float
Clustering cost, defined as the sum distance of all points to
their respective cluster centroids.
n_iter_ : int
The number of iterations the algorithm ran for.
Notes
-----
See:
Huang, Z.: Extensions to the k-modes algorithm for clustering large
data sets with categorical values, Data Mining and Knowledge
Discovery 2(3), 1998.
"""
def __init__(self, n_clusters=8, max_iter=100, cat_dissim=matching_dissim,
init='Cao', n_init=1, verbose=0, random_state=None, n_jobs=1):
self.n_clusters = n_clusters
self.max_iter = max_iter
self.cat_dissim = cat_dissim
self.init = init
self.n_init = n_init
self.verbose = verbose
self.random_state = random_state
self.n_jobs = n_jobs
if ((isinstance(self.init, str) and self.init == 'Cao') or
hasattr(self.init, '__array__')) and self.n_init > 1:
if self.verbose:
print("Initialization method and algorithm are deterministic. "
"Setting n_init to 1.")
self.n_init = 1
def fit(self, X, y=None, **kwargs):
"""Compute k-modes clustering.
Parameters
----------
X : array-like, shape=[n_samples, n_features]
"""
X = pandas_to_numpy(X)
random_state = check_random_state(self.random_state)
self._enc_cluster_centroids, self._enc_map, self.labels_,\
self.cost_, self.n_iter_ = k_modes(X,
self.n_clusters,
self.max_iter,
self.cat_dissim,
self.init,
self.n_init,
self.verbose,
random_state,
self.n_jobs)
return self
def fit_predict(self, X, y=None, **kwargs):
"""Compute cluster centroids and predict cluster index for each sample.
Convenience method; equivalent to calling fit(X) followed by
predict(X).
"""
return self.fit(X, **kwargs).predict(X, **kwargs)
@property
def cluster_centroids_(self):
if hasattr(self, '_enc_cluster_centroids'):
return decode_centroids(self._enc_cluster_centroids, self._enc_map)
else:
raise AttributeError("'{}' object has no attribute 'cluster_centroids_' "
"because the model is not yet fitted.")
|
nicodv/kmodes | kmodes/util/__init__.py | get_max_value_key | python | def get_max_value_key(dic):
v = np.array(list(dic.values()))
k = np.array(list(dic.keys()))
maxima = np.where(v == np.max(v))[0]
if len(maxima) == 1:
return k[maxima[0]]
else:
# In order to be consistent, always selects the minimum key
# (guaranteed to be unique) when there are multiple maximum values.
return k[maxima[np.argmin(k[maxima])]] | Gets the key for the maximum value in a dict. | train | https://github.com/nicodv/kmodes/blob/cdb19fe5448aba1bf501626694bb52e68eafab45/kmodes/util/__init__.py#L12-L23 | null | """
Generic utilities for clustering
"""
import numpy as np
def pandas_to_numpy(x):
return x.values if 'pandas' in str(x.__class__) else x
def encode_features(X, enc_map=None):
"""Converts categorical values in each column of X to integers in the range
[0, n_unique_values_in_column - 1], if X is not already of integer type.
If mapping is not provided, it is calculated based on the values in X.
Unknown values during prediction get a value of -1. np.NaNs are ignored
during encoding, and get treated as unknowns during prediction.
"""
if enc_map is None:
fit = True
# We will calculate enc_map, so initialize the list of column mappings.
enc_map = []
else:
fit = False
Xenc = np.zeros(X.shape).astype('int')
for ii in range(X.shape[1]):
if fit:
col_enc = {val: jj for jj, val in enumerate(np.unique(X[:, ii]))
if not (isinstance(val, float) and np.isnan(val))}
enc_map.append(col_enc)
# Unknown categories (including np.NaNs) all get a value of -1.
Xenc[:, ii] = np.array([enc_map[ii].get(x, -1) for x in X[:, ii]])
return Xenc, enc_map
def decode_centroids(encoded, mapping):
"""Decodes the encoded centroids array back to the original data
labels using a list of mappings.
"""
decoded = []
for ii in range(encoded.shape[1]):
# Invert the mapping so that we can decode.
inv_mapping = {v: k for k, v in mapping[ii].items()}
decoded.append(np.vectorize(inv_mapping.__getitem__)(encoded[:, ii]))
return np.atleast_2d(np.array(decoded)).T
def get_unique_rows(a):
"""Gets the unique rows in a numpy array."""
return np.vstack(list({tuple(row) for row in a}))
|
nicodv/kmodes | kmodes/util/__init__.py | encode_features | python | def encode_features(X, enc_map=None):
if enc_map is None:
fit = True
# We will calculate enc_map, so initialize the list of column mappings.
enc_map = []
else:
fit = False
Xenc = np.zeros(X.shape).astype('int')
for ii in range(X.shape[1]):
if fit:
col_enc = {val: jj for jj, val in enumerate(np.unique(X[:, ii]))
if not (isinstance(val, float) and np.isnan(val))}
enc_map.append(col_enc)
# Unknown categories (including np.NaNs) all get a value of -1.
Xenc[:, ii] = np.array([enc_map[ii].get(x, -1) for x in X[:, ii]])
return Xenc, enc_map | Converts categorical values in each column of X to integers in the range
[0, n_unique_values_in_column - 1], if X is not already of integer type.
If mapping is not provided, it is calculated based on the values in X.
Unknown values during prediction get a value of -1. np.NaNs are ignored
during encoding, and get treated as unknowns during prediction. | train | https://github.com/nicodv/kmodes/blob/cdb19fe5448aba1bf501626694bb52e68eafab45/kmodes/util/__init__.py#L26-L51 | null | """
Generic utilities for clustering
"""
import numpy as np
def pandas_to_numpy(x):
return x.values if 'pandas' in str(x.__class__) else x
def get_max_value_key(dic):
"""Gets the key for the maximum value in a dict."""
v = np.array(list(dic.values()))
k = np.array(list(dic.keys()))
maxima = np.where(v == np.max(v))[0]
if len(maxima) == 1:
return k[maxima[0]]
else:
# In order to be consistent, always selects the minimum key
# (guaranteed to be unique) when there are multiple maximum values.
return k[maxima[np.argmin(k[maxima])]]
def decode_centroids(encoded, mapping):
"""Decodes the encoded centroids array back to the original data
labels using a list of mappings.
"""
decoded = []
for ii in range(encoded.shape[1]):
# Invert the mapping so that we can decode.
inv_mapping = {v: k for k, v in mapping[ii].items()}
decoded.append(np.vectorize(inv_mapping.__getitem__)(encoded[:, ii]))
return np.atleast_2d(np.array(decoded)).T
def get_unique_rows(a):
"""Gets the unique rows in a numpy array."""
return np.vstack(list({tuple(row) for row in a}))
|
nicodv/kmodes | kmodes/util/__init__.py | decode_centroids | python | def decode_centroids(encoded, mapping):
decoded = []
for ii in range(encoded.shape[1]):
# Invert the mapping so that we can decode.
inv_mapping = {v: k for k, v in mapping[ii].items()}
decoded.append(np.vectorize(inv_mapping.__getitem__)(encoded[:, ii]))
return np.atleast_2d(np.array(decoded)).T | Decodes the encoded centroids array back to the original data
labels using a list of mappings. | train | https://github.com/nicodv/kmodes/blob/cdb19fe5448aba1bf501626694bb52e68eafab45/kmodes/util/__init__.py#L54-L63 | null | """
Generic utilities for clustering
"""
import numpy as np
def pandas_to_numpy(x):
return x.values if 'pandas' in str(x.__class__) else x
def get_max_value_key(dic):
"""Gets the key for the maximum value in a dict."""
v = np.array(list(dic.values()))
k = np.array(list(dic.keys()))
maxima = np.where(v == np.max(v))[0]
if len(maxima) == 1:
return k[maxima[0]]
else:
# In order to be consistent, always selects the minimum key
# (guaranteed to be unique) when there are multiple maximum values.
return k[maxima[np.argmin(k[maxima])]]
def encode_features(X, enc_map=None):
"""Converts categorical values in each column of X to integers in the range
[0, n_unique_values_in_column - 1], if X is not already of integer type.
If mapping is not provided, it is calculated based on the values in X.
Unknown values during prediction get a value of -1. np.NaNs are ignored
during encoding, and get treated as unknowns during prediction.
"""
if enc_map is None:
fit = True
# We will calculate enc_map, so initialize the list of column mappings.
enc_map = []
else:
fit = False
Xenc = np.zeros(X.shape).astype('int')
for ii in range(X.shape[1]):
if fit:
col_enc = {val: jj for jj, val in enumerate(np.unique(X[:, ii]))
if not (isinstance(val, float) and np.isnan(val))}
enc_map.append(col_enc)
# Unknown categories (including np.NaNs) all get a value of -1.
Xenc[:, ii] = np.array([enc_map[ii].get(x, -1) for x in X[:, ii]])
return Xenc, enc_map
def get_unique_rows(a):
"""Gets the unique rows in a numpy array."""
return np.vstack(list({tuple(row) for row in a}))
|
nicodv/kmodes | kmodes/kprototypes.py | move_point_num | python | def move_point_num(point, to_clust, from_clust, cl_attr_sum, cl_memb_sum):
# Update sum of attributes in cluster.
for iattr, curattr in enumerate(point):
cl_attr_sum[to_clust][iattr] += curattr
cl_attr_sum[from_clust][iattr] -= curattr
# Update sums of memberships in cluster
cl_memb_sum[to_clust] += 1
cl_memb_sum[from_clust] -= 1
return cl_attr_sum, cl_memb_sum | Move point between clusters, numerical attributes. | train | https://github.com/nicodv/kmodes/blob/cdb19fe5448aba1bf501626694bb52e68eafab45/kmodes/kprototypes.py#L28-L37 | null | """
K-prototypes clustering for mixed categorical and numerical data
"""
# pylint: disable=super-on-old-class,unused-argument,attribute-defined-outside-init
from collections import defaultdict
import numpy as np
from joblib import Parallel, delayed
from scipy import sparse
from sklearn.utils import check_random_state
from sklearn.utils.validation import check_array
from . import kmodes
from .util import get_max_value_key, encode_features, get_unique_rows, \
decode_centroids, pandas_to_numpy
from .util.dissim import matching_dissim, euclidean_dissim
# Number of tries we give the initialization methods to find non-empty
# clusters before we switch to random initialization.
MAX_INIT_TRIES = 20
# Number of tries we give the initialization before we raise an
# initialization error.
RAISE_INIT_TRIES = 100
def _split_num_cat(X, categorical):
"""Extract numerical and categorical columns.
Convert to numpy arrays, if needed.
:param X: Feature matrix
:param categorical: Indices of categorical columns
"""
Xnum = np.asanyarray(X[:, [ii for ii in range(X.shape[1])
if ii not in categorical]]).astype(np.float64)
Xcat = np.asanyarray(X[:, categorical])
return Xnum, Xcat
def _labels_cost(Xnum, Xcat, centroids, num_dissim, cat_dissim, gamma, membship=None):
"""Calculate labels and cost function given a matrix of points and
a list of centroids for the k-prototypes algorithm.
"""
n_points = Xnum.shape[0]
Xnum = check_array(Xnum)
cost = 0.
labels = np.empty(n_points, dtype=np.uint16)
for ipoint in range(n_points):
# Numerical cost = sum of Euclidean distances
num_costs = num_dissim(centroids[0], Xnum[ipoint])
cat_costs = cat_dissim(centroids[1], Xcat[ipoint], X=Xcat, membship=membship)
# Gamma relates the categorical cost to the numerical cost.
tot_costs = num_costs + gamma * cat_costs
clust = np.argmin(tot_costs)
labels[ipoint] = clust
cost += tot_costs[clust]
return labels, cost
def _k_prototypes_iter(Xnum, Xcat, centroids, cl_attr_sum, cl_memb_sum, cl_attr_freq,
membship, num_dissim, cat_dissim, gamma, random_state):
"""Single iteration of the k-prototypes algorithm"""
moves = 0
for ipoint in range(Xnum.shape[0]):
clust = np.argmin(
num_dissim(centroids[0], Xnum[ipoint]) +
gamma * cat_dissim(centroids[1], Xcat[ipoint], X=Xcat, membship=membship)
)
if membship[clust, ipoint]:
# Point is already in its right place.
continue
# Move point, and update old/new cluster frequencies and centroids.
moves += 1
old_clust = np.argwhere(membship[:, ipoint])[0][0]
# Note that membship gets updated by kmodes.move_point_cat.
# move_point_num only updates things specific to the k-means part.
cl_attr_sum, cl_memb_sum = move_point_num(
Xnum[ipoint], clust, old_clust, cl_attr_sum, cl_memb_sum
)
cl_attr_freq, membship, centroids[1] = kmodes.move_point_cat(
Xcat[ipoint], ipoint, clust, old_clust,
cl_attr_freq, membship, centroids[1]
)
# Update old and new centroids for numerical attributes using
# the means and sums of all values
for iattr in range(len(Xnum[ipoint])):
for curc in (clust, old_clust):
if cl_memb_sum[curc]:
centroids[0][curc, iattr] = cl_attr_sum[curc, iattr] / cl_memb_sum[curc]
else:
centroids[0][curc, iattr] = 0.
# In case of an empty cluster, reinitialize with a random point
# from largest cluster.
if not cl_memb_sum[old_clust]:
from_clust = membship.sum(axis=1).argmax()
choices = [ii for ii, ch in enumerate(membship[from_clust, :]) if ch]
rindx = random_state.choice(choices)
cl_attr_sum, cl_memb_sum = move_point_num(
Xnum[rindx], old_clust, from_clust, cl_attr_sum, cl_memb_sum
)
cl_attr_freq, membship, centroids[1] = kmodes.move_point_cat(
Xcat[rindx], rindx, old_clust, from_clust,
cl_attr_freq, membship, centroids[1]
)
return centroids, moves
def k_prototypes_single(Xnum, Xcat, nnumattrs, ncatattrs, n_clusters, n_points,
max_iter, num_dissim, cat_dissim, gamma, init, init_no,
verbose, random_state):
# For numerical part of initialization, we don't have a guarantee
# that there is not an empty cluster, so we need to retry until
# there is none.
random_state = check_random_state(random_state)
init_tries = 0
while True:
init_tries += 1
# _____ INIT _____
if verbose:
print("Init: initializing centroids")
if isinstance(init, str) and init.lower() == 'huang':
centroids = kmodes.init_huang(Xcat, n_clusters, cat_dissim, random_state)
elif isinstance(init, str) and init.lower() == 'cao':
centroids = kmodes.init_cao(Xcat, n_clusters, cat_dissim)
elif isinstance(init, str) and init.lower() == 'random':
seeds = random_state.choice(range(n_points), n_clusters)
centroids = Xcat[seeds]
elif isinstance(init, list):
# Make sure inits are 2D arrays.
init = [np.atleast_2d(cur_init).T if len(cur_init.shape) == 1
else cur_init
for cur_init in init]
assert init[0].shape[0] == n_clusters, \
"Wrong number of initial numerical centroids in init " \
"({}, should be {}).".format(init[0].shape[0], n_clusters)
assert init[0].shape[1] == nnumattrs, \
"Wrong number of numerical attributes in init ({}, should be {})." \
.format(init[0].shape[1], nnumattrs)
assert init[1].shape[0] == n_clusters, \
"Wrong number of initial categorical centroids in init ({}, " \
"should be {}).".format(init[1].shape[0], n_clusters)
assert init[1].shape[1] == ncatattrs, \
"Wrong number of categorical attributes in init ({}, should be {})." \
.format(init[1].shape[1], ncatattrs)
centroids = [np.asarray(init[0], dtype=np.float64),
np.asarray(init[1], dtype=np.uint16)]
else:
raise NotImplementedError("Initialization method not supported.")
if not isinstance(init, list):
# Numerical is initialized by drawing from normal distribution,
# categorical following the k-modes methods.
meanx = np.mean(Xnum, axis=0)
stdx = np.std(Xnum, axis=0)
centroids = [
meanx + random_state.randn(n_clusters, nnumattrs) * stdx,
centroids
]
if verbose:
print("Init: initializing clusters")
membship = np.zeros((n_clusters, n_points), dtype=np.uint8)
# Keep track of the sum of attribute values per cluster so that we
# can do k-means on the numerical attributes.
cl_attr_sum = np.zeros((n_clusters, nnumattrs), dtype=np.float64)
# Same for the membership sum per cluster
cl_memb_sum = np.zeros(n_clusters, dtype=int)
# cl_attr_freq is a list of lists with dictionaries that contain
# the frequencies of values per cluster and attribute.
cl_attr_freq = [[defaultdict(int) for _ in range(ncatattrs)]
for _ in range(n_clusters)]
for ipoint in range(n_points):
# Initial assignment to clusters
clust = np.argmin(
num_dissim(centroids[0], Xnum[ipoint]) + gamma *
cat_dissim(centroids[1], Xcat[ipoint], X=Xcat, membship=membship)
)
membship[clust, ipoint] = 1
cl_memb_sum[clust] += 1
# Count attribute values per cluster.
for iattr, curattr in enumerate(Xnum[ipoint]):
cl_attr_sum[clust, iattr] += curattr
for iattr, curattr in enumerate(Xcat[ipoint]):
cl_attr_freq[clust][iattr][curattr] += 1
# If no empty clusters, then consider initialization finalized.
if membship.sum(axis=1).min() > 0:
break
if init_tries == MAX_INIT_TRIES:
# Could not get rid of empty clusters. Randomly
# initialize instead.
init = 'random'
elif init_tries == RAISE_INIT_TRIES:
raise ValueError(
"Clustering algorithm could not initialize. "
"Consider assigning the initial clusters manually."
)
# Perform an initial centroid update.
for ik in range(n_clusters):
for iattr in range(nnumattrs):
centroids[0][ik, iattr] = cl_attr_sum[ik, iattr] / cl_memb_sum[ik]
for iattr in range(ncatattrs):
centroids[1][ik, iattr] = get_max_value_key(cl_attr_freq[ik][iattr])
# _____ ITERATION _____
if verbose:
print("Starting iterations...")
itr = 0
labels = None
converged = False
cost = np.Inf
while itr <= max_iter and not converged:
itr += 1
centroids, moves = _k_prototypes_iter(Xnum, Xcat, centroids,
cl_attr_sum, cl_memb_sum, cl_attr_freq,
membship, num_dissim, cat_dissim, gamma,
random_state)
# All points seen in this iteration
labels, ncost = _labels_cost(Xnum, Xcat, centroids,
num_dissim, cat_dissim, gamma, membship)
converged = (moves == 0) or (ncost >= cost)
cost = ncost
if verbose:
print("Run: {}, iteration: {}/{}, moves: {}, ncost: {}"
.format(init_no + 1, itr, max_iter, moves, ncost))
return centroids, labels, cost, itr
def k_prototypes(X, categorical, n_clusters, max_iter, num_dissim, cat_dissim,
gamma, init, n_init, verbose, random_state, n_jobs):
"""k-prototypes algorithm"""
random_state = check_random_state(random_state)
if sparse.issparse(X):
raise TypeError("k-prototypes does not support sparse data.")
if categorical is None or not categorical:
raise NotImplementedError(
"No categorical data selected, effectively doing k-means. "
"Present a list of categorical columns, or use scikit-learn's "
"KMeans instead."
)
if isinstance(categorical, int):
categorical = [categorical]
assert len(categorical) != X.shape[1], \
"All columns are categorical, use k-modes instead of k-prototypes."
assert max(categorical) < X.shape[1], \
"Categorical index larger than number of columns."
ncatattrs = len(categorical)
nnumattrs = X.shape[1] - ncatattrs
n_points = X.shape[0]
assert n_clusters <= n_points, "Cannot have more clusters ({}) " \
"than data points ({}).".format(n_clusters, n_points)
Xnum, Xcat = _split_num_cat(X, categorical)
Xnum, Xcat = check_array(Xnum), check_array(Xcat, dtype=None)
# Convert the categorical values in Xcat to integers for speed.
# Based on the unique values in Xcat, we can make a mapping to achieve this.
Xcat, enc_map = encode_features(Xcat)
# Are there more n_clusters than unique rows? Then set the unique
# rows as initial values and skip iteration.
unique = get_unique_rows(X)
n_unique = unique.shape[0]
if n_unique <= n_clusters:
max_iter = 0
n_init = 1
n_clusters = n_unique
init = list(_split_num_cat(unique, categorical))
init[1], _ = encode_features(init[1], enc_map)
# Estimate a good value for gamma, which determines the weighing of
# categorical values in clusters (see Huang [1997]).
if gamma is None:
gamma = 0.5 * Xnum.std()
results = []
seeds = random_state.randint(np.iinfo(np.int32).max, size=n_init)
if n_jobs == 1:
for init_no in range(n_init):
results.append(k_prototypes_single(Xnum, Xcat, nnumattrs, ncatattrs,
n_clusters, n_points, max_iter,
num_dissim, cat_dissim, gamma,
init, init_no, verbose, seeds[init_no]))
else:
results = Parallel(n_jobs=n_jobs, verbose=0)(
delayed(k_prototypes_single)(Xnum, Xcat, nnumattrs, ncatattrs,
n_clusters, n_points, max_iter,
num_dissim, cat_dissim, gamma,
init, init_no, verbose, seed)
for init_no, seed in enumerate(seeds))
all_centroids, all_labels, all_costs, all_n_iters = zip(*results)
best = np.argmin(all_costs)
if n_init > 1 and verbose:
print("Best run was number {}".format(best + 1))
# Note: return gamma in case it was automatically determined.
return all_centroids[best], enc_map, all_labels[best], \
all_costs[best], all_n_iters[best], gamma
class KPrototypes(kmodes.KModes):
"""k-protoypes clustering algorithm for mixed numerical/categorical data.
Parameters
-----------
n_clusters : int, optional, default: 8
The number of clusters to form as well as the number of
centroids to generate.
max_iter : int, default: 300
Maximum number of iterations of the k-modes algorithm for a
single run.
num_dissim : func, default: euclidian_dissim
Dissimilarity function used by the algorithm for numerical variables.
Defaults to the Euclidian dissimilarity function.
cat_dissim : func, default: matching_dissim
Dissimilarity function used by the kmodes algorithm for categorical variables.
Defaults to the matching dissimilarity function.
n_init : int, default: 10
Number of time the k-modes algorithm will be run with different
centroid seeds. The final results will be the best output of
n_init consecutive runs in terms of cost.
init : {'Huang', 'Cao', 'random' or a list of ndarrays}, default: 'Cao'
Method for initialization:
'Huang': Method in Huang [1997, 1998]
'Cao': Method in Cao et al. [2009]
'random': choose 'n_clusters' observations (rows) at random from
data for the initial centroids.
If a list of ndarrays is passed, it should be of length 2, with
shapes (n_clusters, n_features) for numerical and categorical
data respectively. These are the initial centroids.
gamma : float, default: None
Weighing factor that determines relative importance of numerical vs.
categorical attributes (see discussion in Huang [1997]). By default,
automatically calculated from data.
verbose : integer, optional
Verbosity mode.
random_state : int, RandomState instance or None, optional, default: None
If int, random_state is the seed used by the random number generator;
If RandomState instance, random_state is the random number generator;
If None, the random number generator is the RandomState instance used
by `np.random`.
n_jobs : int, default: 1
The number of jobs to use for the computation. This works by computing
each of the n_init runs in parallel.
If -1 all CPUs are used. If 1 is given, no parallel computing code is
used at all, which is useful for debugging. For n_jobs below -1,
(n_cpus + 1 + n_jobs) are used. Thus for n_jobs = -2, all CPUs but one
are used.
Attributes
----------
cluster_centroids_ : array, [n_clusters, n_features]
Categories of cluster centroids
labels_ :
Labels of each point
cost_ : float
Clustering cost, defined as the sum distance of all points to
their respective cluster centroids.
n_iter_ : int
The number of iterations the algorithm ran for.
gamma : float
The (potentially calculated) weighing factor.
Notes
-----
See:
Huang, Z.: Extensions to the k-modes algorithm for clustering large
data sets with categorical values, Data Mining and Knowledge
Discovery 2(3), 1998.
"""
def __init__(self, n_clusters=8, max_iter=100, num_dissim=euclidean_dissim,
cat_dissim=matching_dissim, init='Huang', n_init=10, gamma=None,
verbose=0, random_state=None, n_jobs=1):
super(KPrototypes, self).__init__(n_clusters, max_iter, cat_dissim, init,
verbose=verbose, random_state=random_state,
n_jobs=n_jobs)
self.num_dissim = num_dissim
self.gamma = gamma
self.n_init = n_init
if isinstance(self.init, list) and self.n_init > 1:
if self.verbose:
print("Initialization method is deterministic. "
"Setting n_init to 1.")
self.n_init = 1
def fit(self, X, y=None, categorical=None):
"""Compute k-prototypes clustering.
Parameters
----------
X : array-like, shape=[n_samples, n_features]
categorical : Index of columns that contain categorical data
"""
if categorical is not None:
assert isinstance(categorical, (int, list, tuple)), "The 'categorical' \
argument needs to be an integer with the index of the categorical \
column in your data, or a list or tuple of several of them, \
but it is a {}.".format(type(categorical))
X = pandas_to_numpy(X)
random_state = check_random_state(self.random_state)
# If self.gamma is None, gamma will be automatically determined from
# the data. The function below returns its value.
self._enc_cluster_centroids, self._enc_map, self.labels_, self.cost_,\
self.n_iter_, self.gamma = k_prototypes(X,
categorical,
self.n_clusters,
self.max_iter,
self.num_dissim,
self.cat_dissim,
self.gamma,
self.init,
self.n_init,
self.verbose,
random_state,
self.n_jobs)
return self
def predict(self, X, categorical=None):
"""Predict the closest cluster each sample in X belongs to.
Parameters
----------
X : array-like, shape = [n_samples, n_features]
New data to predict.
categorical : Indices of columns that contain categorical data
Returns
-------
labels : array, shape [n_samples,]
Index of the cluster each sample belongs to.
"""
assert hasattr(self, '_enc_cluster_centroids'), "Model not yet fitted."
if categorical is not None:
assert isinstance(categorical, (int, list, tuple)), "The 'categorical' \
argument needs to be an integer with the index of the categorical \
column in your data, or a list or tuple of several of them, \
but it is a {}.".format(type(categorical))
X = pandas_to_numpy(X)
Xnum, Xcat = _split_num_cat(X, categorical)
Xnum, Xcat = check_array(Xnum), check_array(Xcat, dtype=None)
Xcat, _ = encode_features(Xcat, enc_map=self._enc_map)
return _labels_cost(Xnum, Xcat, self._enc_cluster_centroids,
self.num_dissim, self.cat_dissim, self.gamma)[0]
@property
def cluster_centroids_(self):
if hasattr(self, '_enc_cluster_centroids'):
return [
self._enc_cluster_centroids[0],
decode_centroids(self._enc_cluster_centroids[1], self._enc_map)
]
else:
raise AttributeError("'{}' object has no attribute 'cluster_centroids_' "
"because the model is not yet fitted.")
|
nicodv/kmodes | kmodes/kprototypes.py | _split_num_cat | python | def _split_num_cat(X, categorical):
Xnum = np.asanyarray(X[:, [ii for ii in range(X.shape[1])
if ii not in categorical]]).astype(np.float64)
Xcat = np.asanyarray(X[:, categorical])
return Xnum, Xcat | Extract numerical and categorical columns.
Convert to numpy arrays, if needed.
:param X: Feature matrix
:param categorical: Indices of categorical columns | train | https://github.com/nicodv/kmodes/blob/cdb19fe5448aba1bf501626694bb52e68eafab45/kmodes/kprototypes.py#L40-L50 | null | """
K-prototypes clustering for mixed categorical and numerical data
"""
# pylint: disable=super-on-old-class,unused-argument,attribute-defined-outside-init
from collections import defaultdict
import numpy as np
from joblib import Parallel, delayed
from scipy import sparse
from sklearn.utils import check_random_state
from sklearn.utils.validation import check_array
from . import kmodes
from .util import get_max_value_key, encode_features, get_unique_rows, \
decode_centroids, pandas_to_numpy
from .util.dissim import matching_dissim, euclidean_dissim
# Number of tries we give the initialization methods to find non-empty
# clusters before we switch to random initialization.
MAX_INIT_TRIES = 20
# Number of tries we give the initialization before we raise an
# initialization error.
RAISE_INIT_TRIES = 100
def move_point_num(point, to_clust, from_clust, cl_attr_sum, cl_memb_sum):
"""Move point between clusters, numerical attributes."""
# Update sum of attributes in cluster.
for iattr, curattr in enumerate(point):
cl_attr_sum[to_clust][iattr] += curattr
cl_attr_sum[from_clust][iattr] -= curattr
# Update sums of memberships in cluster
cl_memb_sum[to_clust] += 1
cl_memb_sum[from_clust] -= 1
return cl_attr_sum, cl_memb_sum
def _labels_cost(Xnum, Xcat, centroids, num_dissim, cat_dissim, gamma, membship=None):
"""Calculate labels and cost function given a matrix of points and
a list of centroids for the k-prototypes algorithm.
"""
n_points = Xnum.shape[0]
Xnum = check_array(Xnum)
cost = 0.
labels = np.empty(n_points, dtype=np.uint16)
for ipoint in range(n_points):
# Numerical cost = sum of Euclidean distances
num_costs = num_dissim(centroids[0], Xnum[ipoint])
cat_costs = cat_dissim(centroids[1], Xcat[ipoint], X=Xcat, membship=membship)
# Gamma relates the categorical cost to the numerical cost.
tot_costs = num_costs + gamma * cat_costs
clust = np.argmin(tot_costs)
labels[ipoint] = clust
cost += tot_costs[clust]
return labels, cost
def _k_prototypes_iter(Xnum, Xcat, centroids, cl_attr_sum, cl_memb_sum, cl_attr_freq,
membship, num_dissim, cat_dissim, gamma, random_state):
"""Single iteration of the k-prototypes algorithm"""
moves = 0
for ipoint in range(Xnum.shape[0]):
clust = np.argmin(
num_dissim(centroids[0], Xnum[ipoint]) +
gamma * cat_dissim(centroids[1], Xcat[ipoint], X=Xcat, membship=membship)
)
if membship[clust, ipoint]:
# Point is already in its right place.
continue
# Move point, and update old/new cluster frequencies and centroids.
moves += 1
old_clust = np.argwhere(membship[:, ipoint])[0][0]
# Note that membship gets updated by kmodes.move_point_cat.
# move_point_num only updates things specific to the k-means part.
cl_attr_sum, cl_memb_sum = move_point_num(
Xnum[ipoint], clust, old_clust, cl_attr_sum, cl_memb_sum
)
cl_attr_freq, membship, centroids[1] = kmodes.move_point_cat(
Xcat[ipoint], ipoint, clust, old_clust,
cl_attr_freq, membship, centroids[1]
)
# Update old and new centroids for numerical attributes using
# the means and sums of all values
for iattr in range(len(Xnum[ipoint])):
for curc in (clust, old_clust):
if cl_memb_sum[curc]:
centroids[0][curc, iattr] = cl_attr_sum[curc, iattr] / cl_memb_sum[curc]
else:
centroids[0][curc, iattr] = 0.
# In case of an empty cluster, reinitialize with a random point
# from largest cluster.
if not cl_memb_sum[old_clust]:
from_clust = membship.sum(axis=1).argmax()
choices = [ii for ii, ch in enumerate(membship[from_clust, :]) if ch]
rindx = random_state.choice(choices)
cl_attr_sum, cl_memb_sum = move_point_num(
Xnum[rindx], old_clust, from_clust, cl_attr_sum, cl_memb_sum
)
cl_attr_freq, membship, centroids[1] = kmodes.move_point_cat(
Xcat[rindx], rindx, old_clust, from_clust,
cl_attr_freq, membship, centroids[1]
)
return centroids, moves
def k_prototypes_single(Xnum, Xcat, nnumattrs, ncatattrs, n_clusters, n_points,
max_iter, num_dissim, cat_dissim, gamma, init, init_no,
verbose, random_state):
# For numerical part of initialization, we don't have a guarantee
# that there is not an empty cluster, so we need to retry until
# there is none.
random_state = check_random_state(random_state)
init_tries = 0
while True:
init_tries += 1
# _____ INIT _____
if verbose:
print("Init: initializing centroids")
if isinstance(init, str) and init.lower() == 'huang':
centroids = kmodes.init_huang(Xcat, n_clusters, cat_dissim, random_state)
elif isinstance(init, str) and init.lower() == 'cao':
centroids = kmodes.init_cao(Xcat, n_clusters, cat_dissim)
elif isinstance(init, str) and init.lower() == 'random':
seeds = random_state.choice(range(n_points), n_clusters)
centroids = Xcat[seeds]
elif isinstance(init, list):
# Make sure inits are 2D arrays.
init = [np.atleast_2d(cur_init).T if len(cur_init.shape) == 1
else cur_init
for cur_init in init]
assert init[0].shape[0] == n_clusters, \
"Wrong number of initial numerical centroids in init " \
"({}, should be {}).".format(init[0].shape[0], n_clusters)
assert init[0].shape[1] == nnumattrs, \
"Wrong number of numerical attributes in init ({}, should be {})." \
.format(init[0].shape[1], nnumattrs)
assert init[1].shape[0] == n_clusters, \
"Wrong number of initial categorical centroids in init ({}, " \
"should be {}).".format(init[1].shape[0], n_clusters)
assert init[1].shape[1] == ncatattrs, \
"Wrong number of categorical attributes in init ({}, should be {})." \
.format(init[1].shape[1], ncatattrs)
centroids = [np.asarray(init[0], dtype=np.float64),
np.asarray(init[1], dtype=np.uint16)]
else:
raise NotImplementedError("Initialization method not supported.")
if not isinstance(init, list):
# Numerical is initialized by drawing from normal distribution,
# categorical following the k-modes methods.
meanx = np.mean(Xnum, axis=0)
stdx = np.std(Xnum, axis=0)
centroids = [
meanx + random_state.randn(n_clusters, nnumattrs) * stdx,
centroids
]
if verbose:
print("Init: initializing clusters")
membship = np.zeros((n_clusters, n_points), dtype=np.uint8)
# Keep track of the sum of attribute values per cluster so that we
# can do k-means on the numerical attributes.
cl_attr_sum = np.zeros((n_clusters, nnumattrs), dtype=np.float64)
# Same for the membership sum per cluster
cl_memb_sum = np.zeros(n_clusters, dtype=int)
# cl_attr_freq is a list of lists with dictionaries that contain
# the frequencies of values per cluster and attribute.
cl_attr_freq = [[defaultdict(int) for _ in range(ncatattrs)]
for _ in range(n_clusters)]
for ipoint in range(n_points):
# Initial assignment to clusters
clust = np.argmin(
num_dissim(centroids[0], Xnum[ipoint]) + gamma *
cat_dissim(centroids[1], Xcat[ipoint], X=Xcat, membship=membship)
)
membship[clust, ipoint] = 1
cl_memb_sum[clust] += 1
# Count attribute values per cluster.
for iattr, curattr in enumerate(Xnum[ipoint]):
cl_attr_sum[clust, iattr] += curattr
for iattr, curattr in enumerate(Xcat[ipoint]):
cl_attr_freq[clust][iattr][curattr] += 1
# If no empty clusters, then consider initialization finalized.
if membship.sum(axis=1).min() > 0:
break
if init_tries == MAX_INIT_TRIES:
# Could not get rid of empty clusters. Randomly
# initialize instead.
init = 'random'
elif init_tries == RAISE_INIT_TRIES:
raise ValueError(
"Clustering algorithm could not initialize. "
"Consider assigning the initial clusters manually."
)
# Perform an initial centroid update.
for ik in range(n_clusters):
for iattr in range(nnumattrs):
centroids[0][ik, iattr] = cl_attr_sum[ik, iattr] / cl_memb_sum[ik]
for iattr in range(ncatattrs):
centroids[1][ik, iattr] = get_max_value_key(cl_attr_freq[ik][iattr])
# _____ ITERATION _____
if verbose:
print("Starting iterations...")
itr = 0
labels = None
converged = False
cost = np.Inf
while itr <= max_iter and not converged:
itr += 1
centroids, moves = _k_prototypes_iter(Xnum, Xcat, centroids,
cl_attr_sum, cl_memb_sum, cl_attr_freq,
membship, num_dissim, cat_dissim, gamma,
random_state)
# All points seen in this iteration
labels, ncost = _labels_cost(Xnum, Xcat, centroids,
num_dissim, cat_dissim, gamma, membship)
converged = (moves == 0) or (ncost >= cost)
cost = ncost
if verbose:
print("Run: {}, iteration: {}/{}, moves: {}, ncost: {}"
.format(init_no + 1, itr, max_iter, moves, ncost))
return centroids, labels, cost, itr
def k_prototypes(X, categorical, n_clusters, max_iter, num_dissim, cat_dissim,
gamma, init, n_init, verbose, random_state, n_jobs):
"""k-prototypes algorithm"""
random_state = check_random_state(random_state)
if sparse.issparse(X):
raise TypeError("k-prototypes does not support sparse data.")
if categorical is None or not categorical:
raise NotImplementedError(
"No categorical data selected, effectively doing k-means. "
"Present a list of categorical columns, or use scikit-learn's "
"KMeans instead."
)
if isinstance(categorical, int):
categorical = [categorical]
assert len(categorical) != X.shape[1], \
"All columns are categorical, use k-modes instead of k-prototypes."
assert max(categorical) < X.shape[1], \
"Categorical index larger than number of columns."
ncatattrs = len(categorical)
nnumattrs = X.shape[1] - ncatattrs
n_points = X.shape[0]
assert n_clusters <= n_points, "Cannot have more clusters ({}) " \
"than data points ({}).".format(n_clusters, n_points)
Xnum, Xcat = _split_num_cat(X, categorical)
Xnum, Xcat = check_array(Xnum), check_array(Xcat, dtype=None)
# Convert the categorical values in Xcat to integers for speed.
# Based on the unique values in Xcat, we can make a mapping to achieve this.
Xcat, enc_map = encode_features(Xcat)
# Are there more n_clusters than unique rows? Then set the unique
# rows as initial values and skip iteration.
unique = get_unique_rows(X)
n_unique = unique.shape[0]
if n_unique <= n_clusters:
max_iter = 0
n_init = 1
n_clusters = n_unique
init = list(_split_num_cat(unique, categorical))
init[1], _ = encode_features(init[1], enc_map)
# Estimate a good value for gamma, which determines the weighing of
# categorical values in clusters (see Huang [1997]).
if gamma is None:
gamma = 0.5 * Xnum.std()
results = []
seeds = random_state.randint(np.iinfo(np.int32).max, size=n_init)
if n_jobs == 1:
for init_no in range(n_init):
results.append(k_prototypes_single(Xnum, Xcat, nnumattrs, ncatattrs,
n_clusters, n_points, max_iter,
num_dissim, cat_dissim, gamma,
init, init_no, verbose, seeds[init_no]))
else:
results = Parallel(n_jobs=n_jobs, verbose=0)(
delayed(k_prototypes_single)(Xnum, Xcat, nnumattrs, ncatattrs,
n_clusters, n_points, max_iter,
num_dissim, cat_dissim, gamma,
init, init_no, verbose, seed)
for init_no, seed in enumerate(seeds))
all_centroids, all_labels, all_costs, all_n_iters = zip(*results)
best = np.argmin(all_costs)
if n_init > 1 and verbose:
print("Best run was number {}".format(best + 1))
# Note: return gamma in case it was automatically determined.
return all_centroids[best], enc_map, all_labels[best], \
all_costs[best], all_n_iters[best], gamma
class KPrototypes(kmodes.KModes):
"""k-protoypes clustering algorithm for mixed numerical/categorical data.
Parameters
-----------
n_clusters : int, optional, default: 8
The number of clusters to form as well as the number of
centroids to generate.
max_iter : int, default: 300
Maximum number of iterations of the k-modes algorithm for a
single run.
num_dissim : func, default: euclidian_dissim
Dissimilarity function used by the algorithm for numerical variables.
Defaults to the Euclidian dissimilarity function.
cat_dissim : func, default: matching_dissim
Dissimilarity function used by the kmodes algorithm for categorical variables.
Defaults to the matching dissimilarity function.
n_init : int, default: 10
Number of time the k-modes algorithm will be run with different
centroid seeds. The final results will be the best output of
n_init consecutive runs in terms of cost.
init : {'Huang', 'Cao', 'random' or a list of ndarrays}, default: 'Cao'
Method for initialization:
'Huang': Method in Huang [1997, 1998]
'Cao': Method in Cao et al. [2009]
'random': choose 'n_clusters' observations (rows) at random from
data for the initial centroids.
If a list of ndarrays is passed, it should be of length 2, with
shapes (n_clusters, n_features) for numerical and categorical
data respectively. These are the initial centroids.
gamma : float, default: None
Weighing factor that determines relative importance of numerical vs.
categorical attributes (see discussion in Huang [1997]). By default,
automatically calculated from data.
verbose : integer, optional
Verbosity mode.
random_state : int, RandomState instance or None, optional, default: None
If int, random_state is the seed used by the random number generator;
If RandomState instance, random_state is the random number generator;
If None, the random number generator is the RandomState instance used
by `np.random`.
n_jobs : int, default: 1
The number of jobs to use for the computation. This works by computing
each of the n_init runs in parallel.
If -1 all CPUs are used. If 1 is given, no parallel computing code is
used at all, which is useful for debugging. For n_jobs below -1,
(n_cpus + 1 + n_jobs) are used. Thus for n_jobs = -2, all CPUs but one
are used.
Attributes
----------
cluster_centroids_ : array, [n_clusters, n_features]
Categories of cluster centroids
labels_ :
Labels of each point
cost_ : float
Clustering cost, defined as the sum distance of all points to
their respective cluster centroids.
n_iter_ : int
The number of iterations the algorithm ran for.
gamma : float
The (potentially calculated) weighing factor.
Notes
-----
See:
Huang, Z.: Extensions to the k-modes algorithm for clustering large
data sets with categorical values, Data Mining and Knowledge
Discovery 2(3), 1998.
"""
def __init__(self, n_clusters=8, max_iter=100, num_dissim=euclidean_dissim,
cat_dissim=matching_dissim, init='Huang', n_init=10, gamma=None,
verbose=0, random_state=None, n_jobs=1):
super(KPrototypes, self).__init__(n_clusters, max_iter, cat_dissim, init,
verbose=verbose, random_state=random_state,
n_jobs=n_jobs)
self.num_dissim = num_dissim
self.gamma = gamma
self.n_init = n_init
if isinstance(self.init, list) and self.n_init > 1:
if self.verbose:
print("Initialization method is deterministic. "
"Setting n_init to 1.")
self.n_init = 1
def fit(self, X, y=None, categorical=None):
"""Compute k-prototypes clustering.
Parameters
----------
X : array-like, shape=[n_samples, n_features]
categorical : Index of columns that contain categorical data
"""
if categorical is not None:
assert isinstance(categorical, (int, list, tuple)), "The 'categorical' \
argument needs to be an integer with the index of the categorical \
column in your data, or a list or tuple of several of them, \
but it is a {}.".format(type(categorical))
X = pandas_to_numpy(X)
random_state = check_random_state(self.random_state)
# If self.gamma is None, gamma will be automatically determined from
# the data. The function below returns its value.
self._enc_cluster_centroids, self._enc_map, self.labels_, self.cost_,\
self.n_iter_, self.gamma = k_prototypes(X,
categorical,
self.n_clusters,
self.max_iter,
self.num_dissim,
self.cat_dissim,
self.gamma,
self.init,
self.n_init,
self.verbose,
random_state,
self.n_jobs)
return self
def predict(self, X, categorical=None):
"""Predict the closest cluster each sample in X belongs to.
Parameters
----------
X : array-like, shape = [n_samples, n_features]
New data to predict.
categorical : Indices of columns that contain categorical data
Returns
-------
labels : array, shape [n_samples,]
Index of the cluster each sample belongs to.
"""
assert hasattr(self, '_enc_cluster_centroids'), "Model not yet fitted."
if categorical is not None:
assert isinstance(categorical, (int, list, tuple)), "The 'categorical' \
argument needs to be an integer with the index of the categorical \
column in your data, or a list or tuple of several of them, \
but it is a {}.".format(type(categorical))
X = pandas_to_numpy(X)
Xnum, Xcat = _split_num_cat(X, categorical)
Xnum, Xcat = check_array(Xnum), check_array(Xcat, dtype=None)
Xcat, _ = encode_features(Xcat, enc_map=self._enc_map)
return _labels_cost(Xnum, Xcat, self._enc_cluster_centroids,
self.num_dissim, self.cat_dissim, self.gamma)[0]
@property
def cluster_centroids_(self):
if hasattr(self, '_enc_cluster_centroids'):
return [
self._enc_cluster_centroids[0],
decode_centroids(self._enc_cluster_centroids[1], self._enc_map)
]
else:
raise AttributeError("'{}' object has no attribute 'cluster_centroids_' "
"because the model is not yet fitted.")
|
nicodv/kmodes | kmodes/kprototypes.py | _labels_cost | python | def _labels_cost(Xnum, Xcat, centroids, num_dissim, cat_dissim, gamma, membship=None):
n_points = Xnum.shape[0]
Xnum = check_array(Xnum)
cost = 0.
labels = np.empty(n_points, dtype=np.uint16)
for ipoint in range(n_points):
# Numerical cost = sum of Euclidean distances
num_costs = num_dissim(centroids[0], Xnum[ipoint])
cat_costs = cat_dissim(centroids[1], Xcat[ipoint], X=Xcat, membship=membship)
# Gamma relates the categorical cost to the numerical cost.
tot_costs = num_costs + gamma * cat_costs
clust = np.argmin(tot_costs)
labels[ipoint] = clust
cost += tot_costs[clust]
return labels, cost | Calculate labels and cost function given a matrix of points and
a list of centroids for the k-prototypes algorithm. | train | https://github.com/nicodv/kmodes/blob/cdb19fe5448aba1bf501626694bb52e68eafab45/kmodes/kprototypes.py#L53-L73 | null | """
K-prototypes clustering for mixed categorical and numerical data
"""
# pylint: disable=super-on-old-class,unused-argument,attribute-defined-outside-init
from collections import defaultdict
import numpy as np
from joblib import Parallel, delayed
from scipy import sparse
from sklearn.utils import check_random_state
from sklearn.utils.validation import check_array
from . import kmodes
from .util import get_max_value_key, encode_features, get_unique_rows, \
decode_centroids, pandas_to_numpy
from .util.dissim import matching_dissim, euclidean_dissim
# Number of tries we give the initialization methods to find non-empty
# clusters before we switch to random initialization.
MAX_INIT_TRIES = 20
# Number of tries we give the initialization before we raise an
# initialization error.
RAISE_INIT_TRIES = 100
def move_point_num(point, to_clust, from_clust, cl_attr_sum, cl_memb_sum):
"""Move point between clusters, numerical attributes."""
# Update sum of attributes in cluster.
for iattr, curattr in enumerate(point):
cl_attr_sum[to_clust][iattr] += curattr
cl_attr_sum[from_clust][iattr] -= curattr
# Update sums of memberships in cluster
cl_memb_sum[to_clust] += 1
cl_memb_sum[from_clust] -= 1
return cl_attr_sum, cl_memb_sum
def _split_num_cat(X, categorical):
"""Extract numerical and categorical columns.
Convert to numpy arrays, if needed.
:param X: Feature matrix
:param categorical: Indices of categorical columns
"""
Xnum = np.asanyarray(X[:, [ii for ii in range(X.shape[1])
if ii not in categorical]]).astype(np.float64)
Xcat = np.asanyarray(X[:, categorical])
return Xnum, Xcat
def _k_prototypes_iter(Xnum, Xcat, centroids, cl_attr_sum, cl_memb_sum, cl_attr_freq,
membship, num_dissim, cat_dissim, gamma, random_state):
"""Single iteration of the k-prototypes algorithm"""
moves = 0
for ipoint in range(Xnum.shape[0]):
clust = np.argmin(
num_dissim(centroids[0], Xnum[ipoint]) +
gamma * cat_dissim(centroids[1], Xcat[ipoint], X=Xcat, membship=membship)
)
if membship[clust, ipoint]:
# Point is already in its right place.
continue
# Move point, and update old/new cluster frequencies and centroids.
moves += 1
old_clust = np.argwhere(membship[:, ipoint])[0][0]
# Note that membship gets updated by kmodes.move_point_cat.
# move_point_num only updates things specific to the k-means part.
cl_attr_sum, cl_memb_sum = move_point_num(
Xnum[ipoint], clust, old_clust, cl_attr_sum, cl_memb_sum
)
cl_attr_freq, membship, centroids[1] = kmodes.move_point_cat(
Xcat[ipoint], ipoint, clust, old_clust,
cl_attr_freq, membship, centroids[1]
)
# Update old and new centroids for numerical attributes using
# the means and sums of all values
for iattr in range(len(Xnum[ipoint])):
for curc in (clust, old_clust):
if cl_memb_sum[curc]:
centroids[0][curc, iattr] = cl_attr_sum[curc, iattr] / cl_memb_sum[curc]
else:
centroids[0][curc, iattr] = 0.
# In case of an empty cluster, reinitialize with a random point
# from largest cluster.
if not cl_memb_sum[old_clust]:
from_clust = membship.sum(axis=1).argmax()
choices = [ii for ii, ch in enumerate(membship[from_clust, :]) if ch]
rindx = random_state.choice(choices)
cl_attr_sum, cl_memb_sum = move_point_num(
Xnum[rindx], old_clust, from_clust, cl_attr_sum, cl_memb_sum
)
cl_attr_freq, membship, centroids[1] = kmodes.move_point_cat(
Xcat[rindx], rindx, old_clust, from_clust,
cl_attr_freq, membship, centroids[1]
)
return centroids, moves
def k_prototypes_single(Xnum, Xcat, nnumattrs, ncatattrs, n_clusters, n_points,
max_iter, num_dissim, cat_dissim, gamma, init, init_no,
verbose, random_state):
# For numerical part of initialization, we don't have a guarantee
# that there is not an empty cluster, so we need to retry until
# there is none.
random_state = check_random_state(random_state)
init_tries = 0
while True:
init_tries += 1
# _____ INIT _____
if verbose:
print("Init: initializing centroids")
if isinstance(init, str) and init.lower() == 'huang':
centroids = kmodes.init_huang(Xcat, n_clusters, cat_dissim, random_state)
elif isinstance(init, str) and init.lower() == 'cao':
centroids = kmodes.init_cao(Xcat, n_clusters, cat_dissim)
elif isinstance(init, str) and init.lower() == 'random':
seeds = random_state.choice(range(n_points), n_clusters)
centroids = Xcat[seeds]
elif isinstance(init, list):
# Make sure inits are 2D arrays.
init = [np.atleast_2d(cur_init).T if len(cur_init.shape) == 1
else cur_init
for cur_init in init]
assert init[0].shape[0] == n_clusters, \
"Wrong number of initial numerical centroids in init " \
"({}, should be {}).".format(init[0].shape[0], n_clusters)
assert init[0].shape[1] == nnumattrs, \
"Wrong number of numerical attributes in init ({}, should be {})." \
.format(init[0].shape[1], nnumattrs)
assert init[1].shape[0] == n_clusters, \
"Wrong number of initial categorical centroids in init ({}, " \
"should be {}).".format(init[1].shape[0], n_clusters)
assert init[1].shape[1] == ncatattrs, \
"Wrong number of categorical attributes in init ({}, should be {})." \
.format(init[1].shape[1], ncatattrs)
centroids = [np.asarray(init[0], dtype=np.float64),
np.asarray(init[1], dtype=np.uint16)]
else:
raise NotImplementedError("Initialization method not supported.")
if not isinstance(init, list):
# Numerical is initialized by drawing from normal distribution,
# categorical following the k-modes methods.
meanx = np.mean(Xnum, axis=0)
stdx = np.std(Xnum, axis=0)
centroids = [
meanx + random_state.randn(n_clusters, nnumattrs) * stdx,
centroids
]
if verbose:
print("Init: initializing clusters")
membship = np.zeros((n_clusters, n_points), dtype=np.uint8)
# Keep track of the sum of attribute values per cluster so that we
# can do k-means on the numerical attributes.
cl_attr_sum = np.zeros((n_clusters, nnumattrs), dtype=np.float64)
# Same for the membership sum per cluster
cl_memb_sum = np.zeros(n_clusters, dtype=int)
# cl_attr_freq is a list of lists with dictionaries that contain
# the frequencies of values per cluster and attribute.
cl_attr_freq = [[defaultdict(int) for _ in range(ncatattrs)]
for _ in range(n_clusters)]
for ipoint in range(n_points):
# Initial assignment to clusters
clust = np.argmin(
num_dissim(centroids[0], Xnum[ipoint]) + gamma *
cat_dissim(centroids[1], Xcat[ipoint], X=Xcat, membship=membship)
)
membship[clust, ipoint] = 1
cl_memb_sum[clust] += 1
# Count attribute values per cluster.
for iattr, curattr in enumerate(Xnum[ipoint]):
cl_attr_sum[clust, iattr] += curattr
for iattr, curattr in enumerate(Xcat[ipoint]):
cl_attr_freq[clust][iattr][curattr] += 1
# If no empty clusters, then consider initialization finalized.
if membship.sum(axis=1).min() > 0:
break
if init_tries == MAX_INIT_TRIES:
# Could not get rid of empty clusters. Randomly
# initialize instead.
init = 'random'
elif init_tries == RAISE_INIT_TRIES:
raise ValueError(
"Clustering algorithm could not initialize. "
"Consider assigning the initial clusters manually."
)
# Perform an initial centroid update.
for ik in range(n_clusters):
for iattr in range(nnumattrs):
centroids[0][ik, iattr] = cl_attr_sum[ik, iattr] / cl_memb_sum[ik]
for iattr in range(ncatattrs):
centroids[1][ik, iattr] = get_max_value_key(cl_attr_freq[ik][iattr])
# _____ ITERATION _____
if verbose:
print("Starting iterations...")
itr = 0
labels = None
converged = False
cost = np.Inf
while itr <= max_iter and not converged:
itr += 1
centroids, moves = _k_prototypes_iter(Xnum, Xcat, centroids,
cl_attr_sum, cl_memb_sum, cl_attr_freq,
membship, num_dissim, cat_dissim, gamma,
random_state)
# All points seen in this iteration
labels, ncost = _labels_cost(Xnum, Xcat, centroids,
num_dissim, cat_dissim, gamma, membship)
converged = (moves == 0) or (ncost >= cost)
cost = ncost
if verbose:
print("Run: {}, iteration: {}/{}, moves: {}, ncost: {}"
.format(init_no + 1, itr, max_iter, moves, ncost))
return centroids, labels, cost, itr
def k_prototypes(X, categorical, n_clusters, max_iter, num_dissim, cat_dissim,
gamma, init, n_init, verbose, random_state, n_jobs):
"""k-prototypes algorithm"""
random_state = check_random_state(random_state)
if sparse.issparse(X):
raise TypeError("k-prototypes does not support sparse data.")
if categorical is None or not categorical:
raise NotImplementedError(
"No categorical data selected, effectively doing k-means. "
"Present a list of categorical columns, or use scikit-learn's "
"KMeans instead."
)
if isinstance(categorical, int):
categorical = [categorical]
assert len(categorical) != X.shape[1], \
"All columns are categorical, use k-modes instead of k-prototypes."
assert max(categorical) < X.shape[1], \
"Categorical index larger than number of columns."
ncatattrs = len(categorical)
nnumattrs = X.shape[1] - ncatattrs
n_points = X.shape[0]
assert n_clusters <= n_points, "Cannot have more clusters ({}) " \
"than data points ({}).".format(n_clusters, n_points)
Xnum, Xcat = _split_num_cat(X, categorical)
Xnum, Xcat = check_array(Xnum), check_array(Xcat, dtype=None)
# Convert the categorical values in Xcat to integers for speed.
# Based on the unique values in Xcat, we can make a mapping to achieve this.
Xcat, enc_map = encode_features(Xcat)
# Are there more n_clusters than unique rows? Then set the unique
# rows as initial values and skip iteration.
unique = get_unique_rows(X)
n_unique = unique.shape[0]
if n_unique <= n_clusters:
max_iter = 0
n_init = 1
n_clusters = n_unique
init = list(_split_num_cat(unique, categorical))
init[1], _ = encode_features(init[1], enc_map)
# Estimate a good value for gamma, which determines the weighing of
# categorical values in clusters (see Huang [1997]).
if gamma is None:
gamma = 0.5 * Xnum.std()
results = []
seeds = random_state.randint(np.iinfo(np.int32).max, size=n_init)
if n_jobs == 1:
for init_no in range(n_init):
results.append(k_prototypes_single(Xnum, Xcat, nnumattrs, ncatattrs,
n_clusters, n_points, max_iter,
num_dissim, cat_dissim, gamma,
init, init_no, verbose, seeds[init_no]))
else:
results = Parallel(n_jobs=n_jobs, verbose=0)(
delayed(k_prototypes_single)(Xnum, Xcat, nnumattrs, ncatattrs,
n_clusters, n_points, max_iter,
num_dissim, cat_dissim, gamma,
init, init_no, verbose, seed)
for init_no, seed in enumerate(seeds))
all_centroids, all_labels, all_costs, all_n_iters = zip(*results)
best = np.argmin(all_costs)
if n_init > 1 and verbose:
print("Best run was number {}".format(best + 1))
# Note: return gamma in case it was automatically determined.
return all_centroids[best], enc_map, all_labels[best], \
all_costs[best], all_n_iters[best], gamma
class KPrototypes(kmodes.KModes):
"""k-protoypes clustering algorithm for mixed numerical/categorical data.
Parameters
-----------
n_clusters : int, optional, default: 8
The number of clusters to form as well as the number of
centroids to generate.
max_iter : int, default: 300
Maximum number of iterations of the k-modes algorithm for a
single run.
num_dissim : func, default: euclidian_dissim
Dissimilarity function used by the algorithm for numerical variables.
Defaults to the Euclidian dissimilarity function.
cat_dissim : func, default: matching_dissim
Dissimilarity function used by the kmodes algorithm for categorical variables.
Defaults to the matching dissimilarity function.
n_init : int, default: 10
Number of time the k-modes algorithm will be run with different
centroid seeds. The final results will be the best output of
n_init consecutive runs in terms of cost.
init : {'Huang', 'Cao', 'random' or a list of ndarrays}, default: 'Cao'
Method for initialization:
'Huang': Method in Huang [1997, 1998]
'Cao': Method in Cao et al. [2009]
'random': choose 'n_clusters' observations (rows) at random from
data for the initial centroids.
If a list of ndarrays is passed, it should be of length 2, with
shapes (n_clusters, n_features) for numerical and categorical
data respectively. These are the initial centroids.
gamma : float, default: None
Weighing factor that determines relative importance of numerical vs.
categorical attributes (see discussion in Huang [1997]). By default,
automatically calculated from data.
verbose : integer, optional
Verbosity mode.
random_state : int, RandomState instance or None, optional, default: None
If int, random_state is the seed used by the random number generator;
If RandomState instance, random_state is the random number generator;
If None, the random number generator is the RandomState instance used
by `np.random`.
n_jobs : int, default: 1
The number of jobs to use for the computation. This works by computing
each of the n_init runs in parallel.
If -1 all CPUs are used. If 1 is given, no parallel computing code is
used at all, which is useful for debugging. For n_jobs below -1,
(n_cpus + 1 + n_jobs) are used. Thus for n_jobs = -2, all CPUs but one
are used.
Attributes
----------
cluster_centroids_ : array, [n_clusters, n_features]
Categories of cluster centroids
labels_ :
Labels of each point
cost_ : float
Clustering cost, defined as the sum distance of all points to
their respective cluster centroids.
n_iter_ : int
The number of iterations the algorithm ran for.
gamma : float
The (potentially calculated) weighing factor.
Notes
-----
See:
Huang, Z.: Extensions to the k-modes algorithm for clustering large
data sets with categorical values, Data Mining and Knowledge
Discovery 2(3), 1998.
"""
def __init__(self, n_clusters=8, max_iter=100, num_dissim=euclidean_dissim,
cat_dissim=matching_dissim, init='Huang', n_init=10, gamma=None,
verbose=0, random_state=None, n_jobs=1):
super(KPrototypes, self).__init__(n_clusters, max_iter, cat_dissim, init,
verbose=verbose, random_state=random_state,
n_jobs=n_jobs)
self.num_dissim = num_dissim
self.gamma = gamma
self.n_init = n_init
if isinstance(self.init, list) and self.n_init > 1:
if self.verbose:
print("Initialization method is deterministic. "
"Setting n_init to 1.")
self.n_init = 1
def fit(self, X, y=None, categorical=None):
"""Compute k-prototypes clustering.
Parameters
----------
X : array-like, shape=[n_samples, n_features]
categorical : Index of columns that contain categorical data
"""
if categorical is not None:
assert isinstance(categorical, (int, list, tuple)), "The 'categorical' \
argument needs to be an integer with the index of the categorical \
column in your data, or a list or tuple of several of them, \
but it is a {}.".format(type(categorical))
X = pandas_to_numpy(X)
random_state = check_random_state(self.random_state)
# If self.gamma is None, gamma will be automatically determined from
# the data. The function below returns its value.
self._enc_cluster_centroids, self._enc_map, self.labels_, self.cost_,\
self.n_iter_, self.gamma = k_prototypes(X,
categorical,
self.n_clusters,
self.max_iter,
self.num_dissim,
self.cat_dissim,
self.gamma,
self.init,
self.n_init,
self.verbose,
random_state,
self.n_jobs)
return self
def predict(self, X, categorical=None):
"""Predict the closest cluster each sample in X belongs to.
Parameters
----------
X : array-like, shape = [n_samples, n_features]
New data to predict.
categorical : Indices of columns that contain categorical data
Returns
-------
labels : array, shape [n_samples,]
Index of the cluster each sample belongs to.
"""
assert hasattr(self, '_enc_cluster_centroids'), "Model not yet fitted."
if categorical is not None:
assert isinstance(categorical, (int, list, tuple)), "The 'categorical' \
argument needs to be an integer with the index of the categorical \
column in your data, or a list or tuple of several of them, \
but it is a {}.".format(type(categorical))
X = pandas_to_numpy(X)
Xnum, Xcat = _split_num_cat(X, categorical)
Xnum, Xcat = check_array(Xnum), check_array(Xcat, dtype=None)
Xcat, _ = encode_features(Xcat, enc_map=self._enc_map)
return _labels_cost(Xnum, Xcat, self._enc_cluster_centroids,
self.num_dissim, self.cat_dissim, self.gamma)[0]
@property
def cluster_centroids_(self):
if hasattr(self, '_enc_cluster_centroids'):
return [
self._enc_cluster_centroids[0],
decode_centroids(self._enc_cluster_centroids[1], self._enc_map)
]
else:
raise AttributeError("'{}' object has no attribute 'cluster_centroids_' "
"because the model is not yet fitted.")
|
nicodv/kmodes | kmodes/kprototypes.py | _k_prototypes_iter | python | def _k_prototypes_iter(Xnum, Xcat, centroids, cl_attr_sum, cl_memb_sum, cl_attr_freq,
membship, num_dissim, cat_dissim, gamma, random_state):
moves = 0
for ipoint in range(Xnum.shape[0]):
clust = np.argmin(
num_dissim(centroids[0], Xnum[ipoint]) +
gamma * cat_dissim(centroids[1], Xcat[ipoint], X=Xcat, membship=membship)
)
if membship[clust, ipoint]:
# Point is already in its right place.
continue
# Move point, and update old/new cluster frequencies and centroids.
moves += 1
old_clust = np.argwhere(membship[:, ipoint])[0][0]
# Note that membship gets updated by kmodes.move_point_cat.
# move_point_num only updates things specific to the k-means part.
cl_attr_sum, cl_memb_sum = move_point_num(
Xnum[ipoint], clust, old_clust, cl_attr_sum, cl_memb_sum
)
cl_attr_freq, membship, centroids[1] = kmodes.move_point_cat(
Xcat[ipoint], ipoint, clust, old_clust,
cl_attr_freq, membship, centroids[1]
)
# Update old and new centroids for numerical attributes using
# the means and sums of all values
for iattr in range(len(Xnum[ipoint])):
for curc in (clust, old_clust):
if cl_memb_sum[curc]:
centroids[0][curc, iattr] = cl_attr_sum[curc, iattr] / cl_memb_sum[curc]
else:
centroids[0][curc, iattr] = 0.
# In case of an empty cluster, reinitialize with a random point
# from largest cluster.
if not cl_memb_sum[old_clust]:
from_clust = membship.sum(axis=1).argmax()
choices = [ii for ii, ch in enumerate(membship[from_clust, :]) if ch]
rindx = random_state.choice(choices)
cl_attr_sum, cl_memb_sum = move_point_num(
Xnum[rindx], old_clust, from_clust, cl_attr_sum, cl_memb_sum
)
cl_attr_freq, membship, centroids[1] = kmodes.move_point_cat(
Xcat[rindx], rindx, old_clust, from_clust,
cl_attr_freq, membship, centroids[1]
)
return centroids, moves | Single iteration of the k-prototypes algorithm | train | https://github.com/nicodv/kmodes/blob/cdb19fe5448aba1bf501626694bb52e68eafab45/kmodes/kprototypes.py#L76-L127 | null | """
K-prototypes clustering for mixed categorical and numerical data
"""
# pylint: disable=super-on-old-class,unused-argument,attribute-defined-outside-init
from collections import defaultdict
import numpy as np
from joblib import Parallel, delayed
from scipy import sparse
from sklearn.utils import check_random_state
from sklearn.utils.validation import check_array
from . import kmodes
from .util import get_max_value_key, encode_features, get_unique_rows, \
decode_centroids, pandas_to_numpy
from .util.dissim import matching_dissim, euclidean_dissim
# Number of tries we give the initialization methods to find non-empty
# clusters before we switch to random initialization.
MAX_INIT_TRIES = 20
# Number of tries we give the initialization before we raise an
# initialization error.
RAISE_INIT_TRIES = 100
def move_point_num(point, to_clust, from_clust, cl_attr_sum, cl_memb_sum):
"""Move point between clusters, numerical attributes."""
# Update sum of attributes in cluster.
for iattr, curattr in enumerate(point):
cl_attr_sum[to_clust][iattr] += curattr
cl_attr_sum[from_clust][iattr] -= curattr
# Update sums of memberships in cluster
cl_memb_sum[to_clust] += 1
cl_memb_sum[from_clust] -= 1
return cl_attr_sum, cl_memb_sum
def _split_num_cat(X, categorical):
"""Extract numerical and categorical columns.
Convert to numpy arrays, if needed.
:param X: Feature matrix
:param categorical: Indices of categorical columns
"""
Xnum = np.asanyarray(X[:, [ii for ii in range(X.shape[1])
if ii not in categorical]]).astype(np.float64)
Xcat = np.asanyarray(X[:, categorical])
return Xnum, Xcat
def _labels_cost(Xnum, Xcat, centroids, num_dissim, cat_dissim, gamma, membship=None):
"""Calculate labels and cost function given a matrix of points and
a list of centroids for the k-prototypes algorithm.
"""
n_points = Xnum.shape[0]
Xnum = check_array(Xnum)
cost = 0.
labels = np.empty(n_points, dtype=np.uint16)
for ipoint in range(n_points):
# Numerical cost = sum of Euclidean distances
num_costs = num_dissim(centroids[0], Xnum[ipoint])
cat_costs = cat_dissim(centroids[1], Xcat[ipoint], X=Xcat, membship=membship)
# Gamma relates the categorical cost to the numerical cost.
tot_costs = num_costs + gamma * cat_costs
clust = np.argmin(tot_costs)
labels[ipoint] = clust
cost += tot_costs[clust]
return labels, cost
def k_prototypes_single(Xnum, Xcat, nnumattrs, ncatattrs, n_clusters, n_points,
max_iter, num_dissim, cat_dissim, gamma, init, init_no,
verbose, random_state):
# For numerical part of initialization, we don't have a guarantee
# that there is not an empty cluster, so we need to retry until
# there is none.
random_state = check_random_state(random_state)
init_tries = 0
while True:
init_tries += 1
# _____ INIT _____
if verbose:
print("Init: initializing centroids")
if isinstance(init, str) and init.lower() == 'huang':
centroids = kmodes.init_huang(Xcat, n_clusters, cat_dissim, random_state)
elif isinstance(init, str) and init.lower() == 'cao':
centroids = kmodes.init_cao(Xcat, n_clusters, cat_dissim)
elif isinstance(init, str) and init.lower() == 'random':
seeds = random_state.choice(range(n_points), n_clusters)
centroids = Xcat[seeds]
elif isinstance(init, list):
# Make sure inits are 2D arrays.
init = [np.atleast_2d(cur_init).T if len(cur_init.shape) == 1
else cur_init
for cur_init in init]
assert init[0].shape[0] == n_clusters, \
"Wrong number of initial numerical centroids in init " \
"({}, should be {}).".format(init[0].shape[0], n_clusters)
assert init[0].shape[1] == nnumattrs, \
"Wrong number of numerical attributes in init ({}, should be {})." \
.format(init[0].shape[1], nnumattrs)
assert init[1].shape[0] == n_clusters, \
"Wrong number of initial categorical centroids in init ({}, " \
"should be {}).".format(init[1].shape[0], n_clusters)
assert init[1].shape[1] == ncatattrs, \
"Wrong number of categorical attributes in init ({}, should be {})." \
.format(init[1].shape[1], ncatattrs)
centroids = [np.asarray(init[0], dtype=np.float64),
np.asarray(init[1], dtype=np.uint16)]
else:
raise NotImplementedError("Initialization method not supported.")
if not isinstance(init, list):
# Numerical is initialized by drawing from normal distribution,
# categorical following the k-modes methods.
meanx = np.mean(Xnum, axis=0)
stdx = np.std(Xnum, axis=0)
centroids = [
meanx + random_state.randn(n_clusters, nnumattrs) * stdx,
centroids
]
if verbose:
print("Init: initializing clusters")
membship = np.zeros((n_clusters, n_points), dtype=np.uint8)
# Keep track of the sum of attribute values per cluster so that we
# can do k-means on the numerical attributes.
cl_attr_sum = np.zeros((n_clusters, nnumattrs), dtype=np.float64)
# Same for the membership sum per cluster
cl_memb_sum = np.zeros(n_clusters, dtype=int)
# cl_attr_freq is a list of lists with dictionaries that contain
# the frequencies of values per cluster and attribute.
cl_attr_freq = [[defaultdict(int) for _ in range(ncatattrs)]
for _ in range(n_clusters)]
for ipoint in range(n_points):
# Initial assignment to clusters
clust = np.argmin(
num_dissim(centroids[0], Xnum[ipoint]) + gamma *
cat_dissim(centroids[1], Xcat[ipoint], X=Xcat, membship=membship)
)
membship[clust, ipoint] = 1
cl_memb_sum[clust] += 1
# Count attribute values per cluster.
for iattr, curattr in enumerate(Xnum[ipoint]):
cl_attr_sum[clust, iattr] += curattr
for iattr, curattr in enumerate(Xcat[ipoint]):
cl_attr_freq[clust][iattr][curattr] += 1
# If no empty clusters, then consider initialization finalized.
if membship.sum(axis=1).min() > 0:
break
if init_tries == MAX_INIT_TRIES:
# Could not get rid of empty clusters. Randomly
# initialize instead.
init = 'random'
elif init_tries == RAISE_INIT_TRIES:
raise ValueError(
"Clustering algorithm could not initialize. "
"Consider assigning the initial clusters manually."
)
# Perform an initial centroid update.
for ik in range(n_clusters):
for iattr in range(nnumattrs):
centroids[0][ik, iattr] = cl_attr_sum[ik, iattr] / cl_memb_sum[ik]
for iattr in range(ncatattrs):
centroids[1][ik, iattr] = get_max_value_key(cl_attr_freq[ik][iattr])
# _____ ITERATION _____
if verbose:
print("Starting iterations...")
itr = 0
labels = None
converged = False
cost = np.Inf
while itr <= max_iter and not converged:
itr += 1
centroids, moves = _k_prototypes_iter(Xnum, Xcat, centroids,
cl_attr_sum, cl_memb_sum, cl_attr_freq,
membship, num_dissim, cat_dissim, gamma,
random_state)
# All points seen in this iteration
labels, ncost = _labels_cost(Xnum, Xcat, centroids,
num_dissim, cat_dissim, gamma, membship)
converged = (moves == 0) or (ncost >= cost)
cost = ncost
if verbose:
print("Run: {}, iteration: {}/{}, moves: {}, ncost: {}"
.format(init_no + 1, itr, max_iter, moves, ncost))
return centroids, labels, cost, itr
def k_prototypes(X, categorical, n_clusters, max_iter, num_dissim, cat_dissim,
gamma, init, n_init, verbose, random_state, n_jobs):
"""k-prototypes algorithm"""
random_state = check_random_state(random_state)
if sparse.issparse(X):
raise TypeError("k-prototypes does not support sparse data.")
if categorical is None or not categorical:
raise NotImplementedError(
"No categorical data selected, effectively doing k-means. "
"Present a list of categorical columns, or use scikit-learn's "
"KMeans instead."
)
if isinstance(categorical, int):
categorical = [categorical]
assert len(categorical) != X.shape[1], \
"All columns are categorical, use k-modes instead of k-prototypes."
assert max(categorical) < X.shape[1], \
"Categorical index larger than number of columns."
ncatattrs = len(categorical)
nnumattrs = X.shape[1] - ncatattrs
n_points = X.shape[0]
assert n_clusters <= n_points, "Cannot have more clusters ({}) " \
"than data points ({}).".format(n_clusters, n_points)
Xnum, Xcat = _split_num_cat(X, categorical)
Xnum, Xcat = check_array(Xnum), check_array(Xcat, dtype=None)
# Convert the categorical values in Xcat to integers for speed.
# Based on the unique values in Xcat, we can make a mapping to achieve this.
Xcat, enc_map = encode_features(Xcat)
# Are there more n_clusters than unique rows? Then set the unique
# rows as initial values and skip iteration.
unique = get_unique_rows(X)
n_unique = unique.shape[0]
if n_unique <= n_clusters:
max_iter = 0
n_init = 1
n_clusters = n_unique
init = list(_split_num_cat(unique, categorical))
init[1], _ = encode_features(init[1], enc_map)
# Estimate a good value for gamma, which determines the weighing of
# categorical values in clusters (see Huang [1997]).
if gamma is None:
gamma = 0.5 * Xnum.std()
results = []
seeds = random_state.randint(np.iinfo(np.int32).max, size=n_init)
if n_jobs == 1:
for init_no in range(n_init):
results.append(k_prototypes_single(Xnum, Xcat, nnumattrs, ncatattrs,
n_clusters, n_points, max_iter,
num_dissim, cat_dissim, gamma,
init, init_no, verbose, seeds[init_no]))
else:
results = Parallel(n_jobs=n_jobs, verbose=0)(
delayed(k_prototypes_single)(Xnum, Xcat, nnumattrs, ncatattrs,
n_clusters, n_points, max_iter,
num_dissim, cat_dissim, gamma,
init, init_no, verbose, seed)
for init_no, seed in enumerate(seeds))
all_centroids, all_labels, all_costs, all_n_iters = zip(*results)
best = np.argmin(all_costs)
if n_init > 1 and verbose:
print("Best run was number {}".format(best + 1))
# Note: return gamma in case it was automatically determined.
return all_centroids[best], enc_map, all_labels[best], \
all_costs[best], all_n_iters[best], gamma
class KPrototypes(kmodes.KModes):
"""k-protoypes clustering algorithm for mixed numerical/categorical data.
Parameters
-----------
n_clusters : int, optional, default: 8
The number of clusters to form as well as the number of
centroids to generate.
max_iter : int, default: 300
Maximum number of iterations of the k-modes algorithm for a
single run.
num_dissim : func, default: euclidian_dissim
Dissimilarity function used by the algorithm for numerical variables.
Defaults to the Euclidian dissimilarity function.
cat_dissim : func, default: matching_dissim
Dissimilarity function used by the kmodes algorithm for categorical variables.
Defaults to the matching dissimilarity function.
n_init : int, default: 10
Number of time the k-modes algorithm will be run with different
centroid seeds. The final results will be the best output of
n_init consecutive runs in terms of cost.
init : {'Huang', 'Cao', 'random' or a list of ndarrays}, default: 'Cao'
Method for initialization:
'Huang': Method in Huang [1997, 1998]
'Cao': Method in Cao et al. [2009]
'random': choose 'n_clusters' observations (rows) at random from
data for the initial centroids.
If a list of ndarrays is passed, it should be of length 2, with
shapes (n_clusters, n_features) for numerical and categorical
data respectively. These are the initial centroids.
gamma : float, default: None
Weighing factor that determines relative importance of numerical vs.
categorical attributes (see discussion in Huang [1997]). By default,
automatically calculated from data.
verbose : integer, optional
Verbosity mode.
random_state : int, RandomState instance or None, optional, default: None
If int, random_state is the seed used by the random number generator;
If RandomState instance, random_state is the random number generator;
If None, the random number generator is the RandomState instance used
by `np.random`.
n_jobs : int, default: 1
The number of jobs to use for the computation. This works by computing
each of the n_init runs in parallel.
If -1 all CPUs are used. If 1 is given, no parallel computing code is
used at all, which is useful for debugging. For n_jobs below -1,
(n_cpus + 1 + n_jobs) are used. Thus for n_jobs = -2, all CPUs but one
are used.
Attributes
----------
cluster_centroids_ : array, [n_clusters, n_features]
Categories of cluster centroids
labels_ :
Labels of each point
cost_ : float
Clustering cost, defined as the sum distance of all points to
their respective cluster centroids.
n_iter_ : int
The number of iterations the algorithm ran for.
gamma : float
The (potentially calculated) weighing factor.
Notes
-----
See:
Huang, Z.: Extensions to the k-modes algorithm for clustering large
data sets with categorical values, Data Mining and Knowledge
Discovery 2(3), 1998.
"""
def __init__(self, n_clusters=8, max_iter=100, num_dissim=euclidean_dissim,
cat_dissim=matching_dissim, init='Huang', n_init=10, gamma=None,
verbose=0, random_state=None, n_jobs=1):
super(KPrototypes, self).__init__(n_clusters, max_iter, cat_dissim, init,
verbose=verbose, random_state=random_state,
n_jobs=n_jobs)
self.num_dissim = num_dissim
self.gamma = gamma
self.n_init = n_init
if isinstance(self.init, list) and self.n_init > 1:
if self.verbose:
print("Initialization method is deterministic. "
"Setting n_init to 1.")
self.n_init = 1
def fit(self, X, y=None, categorical=None):
"""Compute k-prototypes clustering.
Parameters
----------
X : array-like, shape=[n_samples, n_features]
categorical : Index of columns that contain categorical data
"""
if categorical is not None:
assert isinstance(categorical, (int, list, tuple)), "The 'categorical' \
argument needs to be an integer with the index of the categorical \
column in your data, or a list or tuple of several of them, \
but it is a {}.".format(type(categorical))
X = pandas_to_numpy(X)
random_state = check_random_state(self.random_state)
# If self.gamma is None, gamma will be automatically determined from
# the data. The function below returns its value.
self._enc_cluster_centroids, self._enc_map, self.labels_, self.cost_,\
self.n_iter_, self.gamma = k_prototypes(X,
categorical,
self.n_clusters,
self.max_iter,
self.num_dissim,
self.cat_dissim,
self.gamma,
self.init,
self.n_init,
self.verbose,
random_state,
self.n_jobs)
return self
def predict(self, X, categorical=None):
"""Predict the closest cluster each sample in X belongs to.
Parameters
----------
X : array-like, shape = [n_samples, n_features]
New data to predict.
categorical : Indices of columns that contain categorical data
Returns
-------
labels : array, shape [n_samples,]
Index of the cluster each sample belongs to.
"""
assert hasattr(self, '_enc_cluster_centroids'), "Model not yet fitted."
if categorical is not None:
assert isinstance(categorical, (int, list, tuple)), "The 'categorical' \
argument needs to be an integer with the index of the categorical \
column in your data, or a list or tuple of several of them, \
but it is a {}.".format(type(categorical))
X = pandas_to_numpy(X)
Xnum, Xcat = _split_num_cat(X, categorical)
Xnum, Xcat = check_array(Xnum), check_array(Xcat, dtype=None)
Xcat, _ = encode_features(Xcat, enc_map=self._enc_map)
return _labels_cost(Xnum, Xcat, self._enc_cluster_centroids,
self.num_dissim, self.cat_dissim, self.gamma)[0]
@property
def cluster_centroids_(self):
if hasattr(self, '_enc_cluster_centroids'):
return [
self._enc_cluster_centroids[0],
decode_centroids(self._enc_cluster_centroids[1], self._enc_map)
]
else:
raise AttributeError("'{}' object has no attribute 'cluster_centroids_' "
"because the model is not yet fitted.")
|
nicodv/kmodes | kmodes/kprototypes.py | k_prototypes | python | def k_prototypes(X, categorical, n_clusters, max_iter, num_dissim, cat_dissim,
gamma, init, n_init, verbose, random_state, n_jobs):
random_state = check_random_state(random_state)
if sparse.issparse(X):
raise TypeError("k-prototypes does not support sparse data.")
if categorical is None or not categorical:
raise NotImplementedError(
"No categorical data selected, effectively doing k-means. "
"Present a list of categorical columns, or use scikit-learn's "
"KMeans instead."
)
if isinstance(categorical, int):
categorical = [categorical]
assert len(categorical) != X.shape[1], \
"All columns are categorical, use k-modes instead of k-prototypes."
assert max(categorical) < X.shape[1], \
"Categorical index larger than number of columns."
ncatattrs = len(categorical)
nnumattrs = X.shape[1] - ncatattrs
n_points = X.shape[0]
assert n_clusters <= n_points, "Cannot have more clusters ({}) " \
"than data points ({}).".format(n_clusters, n_points)
Xnum, Xcat = _split_num_cat(X, categorical)
Xnum, Xcat = check_array(Xnum), check_array(Xcat, dtype=None)
# Convert the categorical values in Xcat to integers for speed.
# Based on the unique values in Xcat, we can make a mapping to achieve this.
Xcat, enc_map = encode_features(Xcat)
# Are there more n_clusters than unique rows? Then set the unique
# rows as initial values and skip iteration.
unique = get_unique_rows(X)
n_unique = unique.shape[0]
if n_unique <= n_clusters:
max_iter = 0
n_init = 1
n_clusters = n_unique
init = list(_split_num_cat(unique, categorical))
init[1], _ = encode_features(init[1], enc_map)
# Estimate a good value for gamma, which determines the weighing of
# categorical values in clusters (see Huang [1997]).
if gamma is None:
gamma = 0.5 * Xnum.std()
results = []
seeds = random_state.randint(np.iinfo(np.int32).max, size=n_init)
if n_jobs == 1:
for init_no in range(n_init):
results.append(k_prototypes_single(Xnum, Xcat, nnumattrs, ncatattrs,
n_clusters, n_points, max_iter,
num_dissim, cat_dissim, gamma,
init, init_no, verbose, seeds[init_no]))
else:
results = Parallel(n_jobs=n_jobs, verbose=0)(
delayed(k_prototypes_single)(Xnum, Xcat, nnumattrs, ncatattrs,
n_clusters, n_points, max_iter,
num_dissim, cat_dissim, gamma,
init, init_no, verbose, seed)
for init_no, seed in enumerate(seeds))
all_centroids, all_labels, all_costs, all_n_iters = zip(*results)
best = np.argmin(all_costs)
if n_init > 1 and verbose:
print("Best run was number {}".format(best + 1))
# Note: return gamma in case it was automatically determined.
return all_centroids[best], enc_map, all_labels[best], \
all_costs[best], all_n_iters[best], gamma | k-prototypes algorithm | train | https://github.com/nicodv/kmodes/blob/cdb19fe5448aba1bf501626694bb52e68eafab45/kmodes/kprototypes.py#L255-L327 | null | """
K-prototypes clustering for mixed categorical and numerical data
"""
# pylint: disable=super-on-old-class,unused-argument,attribute-defined-outside-init
from collections import defaultdict
import numpy as np
from joblib import Parallel, delayed
from scipy import sparse
from sklearn.utils import check_random_state
from sklearn.utils.validation import check_array
from . import kmodes
from .util import get_max_value_key, encode_features, get_unique_rows, \
decode_centroids, pandas_to_numpy
from .util.dissim import matching_dissim, euclidean_dissim
# Number of tries we give the initialization methods to find non-empty
# clusters before we switch to random initialization.
MAX_INIT_TRIES = 20
# Number of tries we give the initialization before we raise an
# initialization error.
RAISE_INIT_TRIES = 100
def move_point_num(point, to_clust, from_clust, cl_attr_sum, cl_memb_sum):
"""Move point between clusters, numerical attributes."""
# Update sum of attributes in cluster.
for iattr, curattr in enumerate(point):
cl_attr_sum[to_clust][iattr] += curattr
cl_attr_sum[from_clust][iattr] -= curattr
# Update sums of memberships in cluster
cl_memb_sum[to_clust] += 1
cl_memb_sum[from_clust] -= 1
return cl_attr_sum, cl_memb_sum
def _split_num_cat(X, categorical):
"""Extract numerical and categorical columns.
Convert to numpy arrays, if needed.
:param X: Feature matrix
:param categorical: Indices of categorical columns
"""
Xnum = np.asanyarray(X[:, [ii for ii in range(X.shape[1])
if ii not in categorical]]).astype(np.float64)
Xcat = np.asanyarray(X[:, categorical])
return Xnum, Xcat
def _labels_cost(Xnum, Xcat, centroids, num_dissim, cat_dissim, gamma, membship=None):
"""Calculate labels and cost function given a matrix of points and
a list of centroids for the k-prototypes algorithm.
"""
n_points = Xnum.shape[0]
Xnum = check_array(Xnum)
cost = 0.
labels = np.empty(n_points, dtype=np.uint16)
for ipoint in range(n_points):
# Numerical cost = sum of Euclidean distances
num_costs = num_dissim(centroids[0], Xnum[ipoint])
cat_costs = cat_dissim(centroids[1], Xcat[ipoint], X=Xcat, membship=membship)
# Gamma relates the categorical cost to the numerical cost.
tot_costs = num_costs + gamma * cat_costs
clust = np.argmin(tot_costs)
labels[ipoint] = clust
cost += tot_costs[clust]
return labels, cost
def _k_prototypes_iter(Xnum, Xcat, centroids, cl_attr_sum, cl_memb_sum, cl_attr_freq,
membship, num_dissim, cat_dissim, gamma, random_state):
"""Single iteration of the k-prototypes algorithm"""
moves = 0
for ipoint in range(Xnum.shape[0]):
clust = np.argmin(
num_dissim(centroids[0], Xnum[ipoint]) +
gamma * cat_dissim(centroids[1], Xcat[ipoint], X=Xcat, membship=membship)
)
if membship[clust, ipoint]:
# Point is already in its right place.
continue
# Move point, and update old/new cluster frequencies and centroids.
moves += 1
old_clust = np.argwhere(membship[:, ipoint])[0][0]
# Note that membship gets updated by kmodes.move_point_cat.
# move_point_num only updates things specific to the k-means part.
cl_attr_sum, cl_memb_sum = move_point_num(
Xnum[ipoint], clust, old_clust, cl_attr_sum, cl_memb_sum
)
cl_attr_freq, membship, centroids[1] = kmodes.move_point_cat(
Xcat[ipoint], ipoint, clust, old_clust,
cl_attr_freq, membship, centroids[1]
)
# Update old and new centroids for numerical attributes using
# the means and sums of all values
for iattr in range(len(Xnum[ipoint])):
for curc in (clust, old_clust):
if cl_memb_sum[curc]:
centroids[0][curc, iattr] = cl_attr_sum[curc, iattr] / cl_memb_sum[curc]
else:
centroids[0][curc, iattr] = 0.
# In case of an empty cluster, reinitialize with a random point
# from largest cluster.
if not cl_memb_sum[old_clust]:
from_clust = membship.sum(axis=1).argmax()
choices = [ii for ii, ch in enumerate(membship[from_clust, :]) if ch]
rindx = random_state.choice(choices)
cl_attr_sum, cl_memb_sum = move_point_num(
Xnum[rindx], old_clust, from_clust, cl_attr_sum, cl_memb_sum
)
cl_attr_freq, membship, centroids[1] = kmodes.move_point_cat(
Xcat[rindx], rindx, old_clust, from_clust,
cl_attr_freq, membship, centroids[1]
)
return centroids, moves
def k_prototypes_single(Xnum, Xcat, nnumattrs, ncatattrs, n_clusters, n_points,
max_iter, num_dissim, cat_dissim, gamma, init, init_no,
verbose, random_state):
# For numerical part of initialization, we don't have a guarantee
# that there is not an empty cluster, so we need to retry until
# there is none.
random_state = check_random_state(random_state)
init_tries = 0
while True:
init_tries += 1
# _____ INIT _____
if verbose:
print("Init: initializing centroids")
if isinstance(init, str) and init.lower() == 'huang':
centroids = kmodes.init_huang(Xcat, n_clusters, cat_dissim, random_state)
elif isinstance(init, str) and init.lower() == 'cao':
centroids = kmodes.init_cao(Xcat, n_clusters, cat_dissim)
elif isinstance(init, str) and init.lower() == 'random':
seeds = random_state.choice(range(n_points), n_clusters)
centroids = Xcat[seeds]
elif isinstance(init, list):
# Make sure inits are 2D arrays.
init = [np.atleast_2d(cur_init).T if len(cur_init.shape) == 1
else cur_init
for cur_init in init]
assert init[0].shape[0] == n_clusters, \
"Wrong number of initial numerical centroids in init " \
"({}, should be {}).".format(init[0].shape[0], n_clusters)
assert init[0].shape[1] == nnumattrs, \
"Wrong number of numerical attributes in init ({}, should be {})." \
.format(init[0].shape[1], nnumattrs)
assert init[1].shape[0] == n_clusters, \
"Wrong number of initial categorical centroids in init ({}, " \
"should be {}).".format(init[1].shape[0], n_clusters)
assert init[1].shape[1] == ncatattrs, \
"Wrong number of categorical attributes in init ({}, should be {})." \
.format(init[1].shape[1], ncatattrs)
centroids = [np.asarray(init[0], dtype=np.float64),
np.asarray(init[1], dtype=np.uint16)]
else:
raise NotImplementedError("Initialization method not supported.")
if not isinstance(init, list):
# Numerical is initialized by drawing from normal distribution,
# categorical following the k-modes methods.
meanx = np.mean(Xnum, axis=0)
stdx = np.std(Xnum, axis=0)
centroids = [
meanx + random_state.randn(n_clusters, nnumattrs) * stdx,
centroids
]
if verbose:
print("Init: initializing clusters")
membship = np.zeros((n_clusters, n_points), dtype=np.uint8)
# Keep track of the sum of attribute values per cluster so that we
# can do k-means on the numerical attributes.
cl_attr_sum = np.zeros((n_clusters, nnumattrs), dtype=np.float64)
# Same for the membership sum per cluster
cl_memb_sum = np.zeros(n_clusters, dtype=int)
# cl_attr_freq is a list of lists with dictionaries that contain
# the frequencies of values per cluster and attribute.
cl_attr_freq = [[defaultdict(int) for _ in range(ncatattrs)]
for _ in range(n_clusters)]
for ipoint in range(n_points):
# Initial assignment to clusters
clust = np.argmin(
num_dissim(centroids[0], Xnum[ipoint]) + gamma *
cat_dissim(centroids[1], Xcat[ipoint], X=Xcat, membship=membship)
)
membship[clust, ipoint] = 1
cl_memb_sum[clust] += 1
# Count attribute values per cluster.
for iattr, curattr in enumerate(Xnum[ipoint]):
cl_attr_sum[clust, iattr] += curattr
for iattr, curattr in enumerate(Xcat[ipoint]):
cl_attr_freq[clust][iattr][curattr] += 1
# If no empty clusters, then consider initialization finalized.
if membship.sum(axis=1).min() > 0:
break
if init_tries == MAX_INIT_TRIES:
# Could not get rid of empty clusters. Randomly
# initialize instead.
init = 'random'
elif init_tries == RAISE_INIT_TRIES:
raise ValueError(
"Clustering algorithm could not initialize. "
"Consider assigning the initial clusters manually."
)
# Perform an initial centroid update.
for ik in range(n_clusters):
for iattr in range(nnumattrs):
centroids[0][ik, iattr] = cl_attr_sum[ik, iattr] / cl_memb_sum[ik]
for iattr in range(ncatattrs):
centroids[1][ik, iattr] = get_max_value_key(cl_attr_freq[ik][iattr])
# _____ ITERATION _____
if verbose:
print("Starting iterations...")
itr = 0
labels = None
converged = False
cost = np.Inf
while itr <= max_iter and not converged:
itr += 1
centroids, moves = _k_prototypes_iter(Xnum, Xcat, centroids,
cl_attr_sum, cl_memb_sum, cl_attr_freq,
membship, num_dissim, cat_dissim, gamma,
random_state)
# All points seen in this iteration
labels, ncost = _labels_cost(Xnum, Xcat, centroids,
num_dissim, cat_dissim, gamma, membship)
converged = (moves == 0) or (ncost >= cost)
cost = ncost
if verbose:
print("Run: {}, iteration: {}/{}, moves: {}, ncost: {}"
.format(init_no + 1, itr, max_iter, moves, ncost))
return centroids, labels, cost, itr
class KPrototypes(kmodes.KModes):
"""k-protoypes clustering algorithm for mixed numerical/categorical data.
Parameters
-----------
n_clusters : int, optional, default: 8
The number of clusters to form as well as the number of
centroids to generate.
max_iter : int, default: 300
Maximum number of iterations of the k-modes algorithm for a
single run.
num_dissim : func, default: euclidian_dissim
Dissimilarity function used by the algorithm for numerical variables.
Defaults to the Euclidian dissimilarity function.
cat_dissim : func, default: matching_dissim
Dissimilarity function used by the kmodes algorithm for categorical variables.
Defaults to the matching dissimilarity function.
n_init : int, default: 10
Number of time the k-modes algorithm will be run with different
centroid seeds. The final results will be the best output of
n_init consecutive runs in terms of cost.
init : {'Huang', 'Cao', 'random' or a list of ndarrays}, default: 'Cao'
Method for initialization:
'Huang': Method in Huang [1997, 1998]
'Cao': Method in Cao et al. [2009]
'random': choose 'n_clusters' observations (rows) at random from
data for the initial centroids.
If a list of ndarrays is passed, it should be of length 2, with
shapes (n_clusters, n_features) for numerical and categorical
data respectively. These are the initial centroids.
gamma : float, default: None
Weighing factor that determines relative importance of numerical vs.
categorical attributes (see discussion in Huang [1997]). By default,
automatically calculated from data.
verbose : integer, optional
Verbosity mode.
random_state : int, RandomState instance or None, optional, default: None
If int, random_state is the seed used by the random number generator;
If RandomState instance, random_state is the random number generator;
If None, the random number generator is the RandomState instance used
by `np.random`.
n_jobs : int, default: 1
The number of jobs to use for the computation. This works by computing
each of the n_init runs in parallel.
If -1 all CPUs are used. If 1 is given, no parallel computing code is
used at all, which is useful for debugging. For n_jobs below -1,
(n_cpus + 1 + n_jobs) are used. Thus for n_jobs = -2, all CPUs but one
are used.
Attributes
----------
cluster_centroids_ : array, [n_clusters, n_features]
Categories of cluster centroids
labels_ :
Labels of each point
cost_ : float
Clustering cost, defined as the sum distance of all points to
their respective cluster centroids.
n_iter_ : int
The number of iterations the algorithm ran for.
gamma : float
The (potentially calculated) weighing factor.
Notes
-----
See:
Huang, Z.: Extensions to the k-modes algorithm for clustering large
data sets with categorical values, Data Mining and Knowledge
Discovery 2(3), 1998.
"""
def __init__(self, n_clusters=8, max_iter=100, num_dissim=euclidean_dissim,
cat_dissim=matching_dissim, init='Huang', n_init=10, gamma=None,
verbose=0, random_state=None, n_jobs=1):
super(KPrototypes, self).__init__(n_clusters, max_iter, cat_dissim, init,
verbose=verbose, random_state=random_state,
n_jobs=n_jobs)
self.num_dissim = num_dissim
self.gamma = gamma
self.n_init = n_init
if isinstance(self.init, list) and self.n_init > 1:
if self.verbose:
print("Initialization method is deterministic. "
"Setting n_init to 1.")
self.n_init = 1
def fit(self, X, y=None, categorical=None):
"""Compute k-prototypes clustering.
Parameters
----------
X : array-like, shape=[n_samples, n_features]
categorical : Index of columns that contain categorical data
"""
if categorical is not None:
assert isinstance(categorical, (int, list, tuple)), "The 'categorical' \
argument needs to be an integer with the index of the categorical \
column in your data, or a list or tuple of several of them, \
but it is a {}.".format(type(categorical))
X = pandas_to_numpy(X)
random_state = check_random_state(self.random_state)
# If self.gamma is None, gamma will be automatically determined from
# the data. The function below returns its value.
self._enc_cluster_centroids, self._enc_map, self.labels_, self.cost_,\
self.n_iter_, self.gamma = k_prototypes(X,
categorical,
self.n_clusters,
self.max_iter,
self.num_dissim,
self.cat_dissim,
self.gamma,
self.init,
self.n_init,
self.verbose,
random_state,
self.n_jobs)
return self
def predict(self, X, categorical=None):
"""Predict the closest cluster each sample in X belongs to.
Parameters
----------
X : array-like, shape = [n_samples, n_features]
New data to predict.
categorical : Indices of columns that contain categorical data
Returns
-------
labels : array, shape [n_samples,]
Index of the cluster each sample belongs to.
"""
assert hasattr(self, '_enc_cluster_centroids'), "Model not yet fitted."
if categorical is not None:
assert isinstance(categorical, (int, list, tuple)), "The 'categorical' \
argument needs to be an integer with the index of the categorical \
column in your data, or a list or tuple of several of them, \
but it is a {}.".format(type(categorical))
X = pandas_to_numpy(X)
Xnum, Xcat = _split_num_cat(X, categorical)
Xnum, Xcat = check_array(Xnum), check_array(Xcat, dtype=None)
Xcat, _ = encode_features(Xcat, enc_map=self._enc_map)
return _labels_cost(Xnum, Xcat, self._enc_cluster_centroids,
self.num_dissim, self.cat_dissim, self.gamma)[0]
@property
def cluster_centroids_(self):
if hasattr(self, '_enc_cluster_centroids'):
return [
self._enc_cluster_centroids[0],
decode_centroids(self._enc_cluster_centroids[1], self._enc_map)
]
else:
raise AttributeError("'{}' object has no attribute 'cluster_centroids_' "
"because the model is not yet fitted.")
|
nicodv/kmodes | kmodes/kprototypes.py | KPrototypes.fit | python | def fit(self, X, y=None, categorical=None):
if categorical is not None:
assert isinstance(categorical, (int, list, tuple)), "The 'categorical' \
argument needs to be an integer with the index of the categorical \
column in your data, or a list or tuple of several of them, \
but it is a {}.".format(type(categorical))
X = pandas_to_numpy(X)
random_state = check_random_state(self.random_state)
# If self.gamma is None, gamma will be automatically determined from
# the data. The function below returns its value.
self._enc_cluster_centroids, self._enc_map, self.labels_, self.cost_,\
self.n_iter_, self.gamma = k_prototypes(X,
categorical,
self.n_clusters,
self.max_iter,
self.num_dissim,
self.cat_dissim,
self.gamma,
self.init,
self.n_init,
self.verbose,
random_state,
self.n_jobs)
return self | Compute k-prototypes clustering.
Parameters
----------
X : array-like, shape=[n_samples, n_features]
categorical : Index of columns that contain categorical data | train | https://github.com/nicodv/kmodes/blob/cdb19fe5448aba1bf501626694bb52e68eafab45/kmodes/kprototypes.py#L431-L463 | [
"def pandas_to_numpy(x):\n return x.values if 'pandas' in str(x.__class__) else x\n",
"def k_prototypes(X, categorical, n_clusters, max_iter, num_dissim, cat_dissim,\n gamma, init, n_init, verbose, random_state, n_jobs):\n \"\"\"k-prototypes algorithm\"\"\"\n random_state = check_random_state(random_state)\n if sparse.issparse(X):\n raise TypeError(\"k-prototypes does not support sparse data.\")\n\n if categorical is None or not categorical:\n raise NotImplementedError(\n \"No categorical data selected, effectively doing k-means. \"\n \"Present a list of categorical columns, or use scikit-learn's \"\n \"KMeans instead.\"\n )\n if isinstance(categorical, int):\n categorical = [categorical]\n assert len(categorical) != X.shape[1], \\\n \"All columns are categorical, use k-modes instead of k-prototypes.\"\n assert max(categorical) < X.shape[1], \\\n \"Categorical index larger than number of columns.\"\n\n ncatattrs = len(categorical)\n nnumattrs = X.shape[1] - ncatattrs\n n_points = X.shape[0]\n assert n_clusters <= n_points, \"Cannot have more clusters ({}) \" \\\n \"than data points ({}).\".format(n_clusters, n_points)\n\n Xnum, Xcat = _split_num_cat(X, categorical)\n Xnum, Xcat = check_array(Xnum), check_array(Xcat, dtype=None)\n\n # Convert the categorical values in Xcat to integers for speed.\n # Based on the unique values in Xcat, we can make a mapping to achieve this.\n Xcat, enc_map = encode_features(Xcat)\n\n # Are there more n_clusters than unique rows? Then set the unique\n # rows as initial values and skip iteration.\n unique = get_unique_rows(X)\n n_unique = unique.shape[0]\n if n_unique <= n_clusters:\n max_iter = 0\n n_init = 1\n n_clusters = n_unique\n init = list(_split_num_cat(unique, categorical))\n init[1], _ = encode_features(init[1], enc_map)\n\n # Estimate a good value for gamma, which determines the weighing of\n # categorical values in clusters (see Huang [1997]).\n if gamma is None:\n gamma = 0.5 * Xnum.std()\n\n results = []\n seeds = random_state.randint(np.iinfo(np.int32).max, size=n_init)\n if n_jobs == 1:\n for init_no in range(n_init):\n results.append(k_prototypes_single(Xnum, Xcat, nnumattrs, ncatattrs,\n n_clusters, n_points, max_iter,\n num_dissim, cat_dissim, gamma,\n init, init_no, verbose, seeds[init_no]))\n else:\n results = Parallel(n_jobs=n_jobs, verbose=0)(\n delayed(k_prototypes_single)(Xnum, Xcat, nnumattrs, ncatattrs,\n n_clusters, n_points, max_iter,\n num_dissim, cat_dissim, gamma,\n init, init_no, verbose, seed)\n for init_no, seed in enumerate(seeds))\n all_centroids, all_labels, all_costs, all_n_iters = zip(*results)\n\n best = np.argmin(all_costs)\n if n_init > 1 and verbose:\n print(\"Best run was number {}\".format(best + 1))\n\n # Note: return gamma in case it was automatically determined.\n return all_centroids[best], enc_map, all_labels[best], \\\n all_costs[best], all_n_iters[best], gamma\n"
] | class KPrototypes(kmodes.KModes):
"""k-protoypes clustering algorithm for mixed numerical/categorical data.
Parameters
-----------
n_clusters : int, optional, default: 8
The number of clusters to form as well as the number of
centroids to generate.
max_iter : int, default: 300
Maximum number of iterations of the k-modes algorithm for a
single run.
num_dissim : func, default: euclidian_dissim
Dissimilarity function used by the algorithm for numerical variables.
Defaults to the Euclidian dissimilarity function.
cat_dissim : func, default: matching_dissim
Dissimilarity function used by the kmodes algorithm for categorical variables.
Defaults to the matching dissimilarity function.
n_init : int, default: 10
Number of time the k-modes algorithm will be run with different
centroid seeds. The final results will be the best output of
n_init consecutive runs in terms of cost.
init : {'Huang', 'Cao', 'random' or a list of ndarrays}, default: 'Cao'
Method for initialization:
'Huang': Method in Huang [1997, 1998]
'Cao': Method in Cao et al. [2009]
'random': choose 'n_clusters' observations (rows) at random from
data for the initial centroids.
If a list of ndarrays is passed, it should be of length 2, with
shapes (n_clusters, n_features) for numerical and categorical
data respectively. These are the initial centroids.
gamma : float, default: None
Weighing factor that determines relative importance of numerical vs.
categorical attributes (see discussion in Huang [1997]). By default,
automatically calculated from data.
verbose : integer, optional
Verbosity mode.
random_state : int, RandomState instance or None, optional, default: None
If int, random_state is the seed used by the random number generator;
If RandomState instance, random_state is the random number generator;
If None, the random number generator is the RandomState instance used
by `np.random`.
n_jobs : int, default: 1
The number of jobs to use for the computation. This works by computing
each of the n_init runs in parallel.
If -1 all CPUs are used. If 1 is given, no parallel computing code is
used at all, which is useful for debugging. For n_jobs below -1,
(n_cpus + 1 + n_jobs) are used. Thus for n_jobs = -2, all CPUs but one
are used.
Attributes
----------
cluster_centroids_ : array, [n_clusters, n_features]
Categories of cluster centroids
labels_ :
Labels of each point
cost_ : float
Clustering cost, defined as the sum distance of all points to
their respective cluster centroids.
n_iter_ : int
The number of iterations the algorithm ran for.
gamma : float
The (potentially calculated) weighing factor.
Notes
-----
See:
Huang, Z.: Extensions to the k-modes algorithm for clustering large
data sets with categorical values, Data Mining and Knowledge
Discovery 2(3), 1998.
"""
def __init__(self, n_clusters=8, max_iter=100, num_dissim=euclidean_dissim,
cat_dissim=matching_dissim, init='Huang', n_init=10, gamma=None,
verbose=0, random_state=None, n_jobs=1):
super(KPrototypes, self).__init__(n_clusters, max_iter, cat_dissim, init,
verbose=verbose, random_state=random_state,
n_jobs=n_jobs)
self.num_dissim = num_dissim
self.gamma = gamma
self.n_init = n_init
if isinstance(self.init, list) and self.n_init > 1:
if self.verbose:
print("Initialization method is deterministic. "
"Setting n_init to 1.")
self.n_init = 1
def predict(self, X, categorical=None):
"""Predict the closest cluster each sample in X belongs to.
Parameters
----------
X : array-like, shape = [n_samples, n_features]
New data to predict.
categorical : Indices of columns that contain categorical data
Returns
-------
labels : array, shape [n_samples,]
Index of the cluster each sample belongs to.
"""
assert hasattr(self, '_enc_cluster_centroids'), "Model not yet fitted."
if categorical is not None:
assert isinstance(categorical, (int, list, tuple)), "The 'categorical' \
argument needs to be an integer with the index of the categorical \
column in your data, or a list or tuple of several of them, \
but it is a {}.".format(type(categorical))
X = pandas_to_numpy(X)
Xnum, Xcat = _split_num_cat(X, categorical)
Xnum, Xcat = check_array(Xnum), check_array(Xcat, dtype=None)
Xcat, _ = encode_features(Xcat, enc_map=self._enc_map)
return _labels_cost(Xnum, Xcat, self._enc_cluster_centroids,
self.num_dissim, self.cat_dissim, self.gamma)[0]
@property
def cluster_centroids_(self):
if hasattr(self, '_enc_cluster_centroids'):
return [
self._enc_cluster_centroids[0],
decode_centroids(self._enc_cluster_centroids[1], self._enc_map)
]
else:
raise AttributeError("'{}' object has no attribute 'cluster_centroids_' "
"because the model is not yet fitted.")
|
nicodv/kmodes | kmodes/kprototypes.py | KPrototypes.predict | python | def predict(self, X, categorical=None):
assert hasattr(self, '_enc_cluster_centroids'), "Model not yet fitted."
if categorical is not None:
assert isinstance(categorical, (int, list, tuple)), "The 'categorical' \
argument needs to be an integer with the index of the categorical \
column in your data, or a list or tuple of several of them, \
but it is a {}.".format(type(categorical))
X = pandas_to_numpy(X)
Xnum, Xcat = _split_num_cat(X, categorical)
Xnum, Xcat = check_array(Xnum), check_array(Xcat, dtype=None)
Xcat, _ = encode_features(Xcat, enc_map=self._enc_map)
return _labels_cost(Xnum, Xcat, self._enc_cluster_centroids,
self.num_dissim, self.cat_dissim, self.gamma)[0] | Predict the closest cluster each sample in X belongs to.
Parameters
----------
X : array-like, shape = [n_samples, n_features]
New data to predict.
categorical : Indices of columns that contain categorical data
Returns
-------
labels : array, shape [n_samples,]
Index of the cluster each sample belongs to. | train | https://github.com/nicodv/kmodes/blob/cdb19fe5448aba1bf501626694bb52e68eafab45/kmodes/kprototypes.py#L465-L492 | [
"def pandas_to_numpy(x):\n return x.values if 'pandas' in str(x.__class__) else x\n",
"def encode_features(X, enc_map=None):\n \"\"\"Converts categorical values in each column of X to integers in the range\n [0, n_unique_values_in_column - 1], if X is not already of integer type.\n\n If mapping is not provided, it is calculated based on the values in X.\n\n Unknown values during prediction get a value of -1. np.NaNs are ignored\n during encoding, and get treated as unknowns during prediction.\n \"\"\"\n if enc_map is None:\n fit = True\n # We will calculate enc_map, so initialize the list of column mappings.\n enc_map = []\n else:\n fit = False\n\n Xenc = np.zeros(X.shape).astype('int')\n for ii in range(X.shape[1]):\n if fit:\n col_enc = {val: jj for jj, val in enumerate(np.unique(X[:, ii]))\n if not (isinstance(val, float) and np.isnan(val))}\n enc_map.append(col_enc)\n # Unknown categories (including np.NaNs) all get a value of -1.\n Xenc[:, ii] = np.array([enc_map[ii].get(x, -1) for x in X[:, ii]])\n\n return Xenc, enc_map\n",
"def _labels_cost(Xnum, Xcat, centroids, num_dissim, cat_dissim, gamma, membship=None):\n \"\"\"Calculate labels and cost function given a matrix of points and\n a list of centroids for the k-prototypes algorithm.\n \"\"\"\n\n n_points = Xnum.shape[0]\n Xnum = check_array(Xnum)\n\n cost = 0.\n labels = np.empty(n_points, dtype=np.uint16)\n for ipoint in range(n_points):\n # Numerical cost = sum of Euclidean distances\n num_costs = num_dissim(centroids[0], Xnum[ipoint])\n cat_costs = cat_dissim(centroids[1], Xcat[ipoint], X=Xcat, membship=membship)\n # Gamma relates the categorical cost to the numerical cost.\n tot_costs = num_costs + gamma * cat_costs\n clust = np.argmin(tot_costs)\n labels[ipoint] = clust\n cost += tot_costs[clust]\n\n return labels, cost\n",
"def _split_num_cat(X, categorical):\n \"\"\"Extract numerical and categorical columns.\n Convert to numpy arrays, if needed.\n\n :param X: Feature matrix\n :param categorical: Indices of categorical columns\n \"\"\"\n Xnum = np.asanyarray(X[:, [ii for ii in range(X.shape[1])\n if ii not in categorical]]).astype(np.float64)\n Xcat = np.asanyarray(X[:, categorical])\n return Xnum, Xcat\n"
] | class KPrototypes(kmodes.KModes):
"""k-protoypes clustering algorithm for mixed numerical/categorical data.
Parameters
-----------
n_clusters : int, optional, default: 8
The number of clusters to form as well as the number of
centroids to generate.
max_iter : int, default: 300
Maximum number of iterations of the k-modes algorithm for a
single run.
num_dissim : func, default: euclidian_dissim
Dissimilarity function used by the algorithm for numerical variables.
Defaults to the Euclidian dissimilarity function.
cat_dissim : func, default: matching_dissim
Dissimilarity function used by the kmodes algorithm for categorical variables.
Defaults to the matching dissimilarity function.
n_init : int, default: 10
Number of time the k-modes algorithm will be run with different
centroid seeds. The final results will be the best output of
n_init consecutive runs in terms of cost.
init : {'Huang', 'Cao', 'random' or a list of ndarrays}, default: 'Cao'
Method for initialization:
'Huang': Method in Huang [1997, 1998]
'Cao': Method in Cao et al. [2009]
'random': choose 'n_clusters' observations (rows) at random from
data for the initial centroids.
If a list of ndarrays is passed, it should be of length 2, with
shapes (n_clusters, n_features) for numerical and categorical
data respectively. These are the initial centroids.
gamma : float, default: None
Weighing factor that determines relative importance of numerical vs.
categorical attributes (see discussion in Huang [1997]). By default,
automatically calculated from data.
verbose : integer, optional
Verbosity mode.
random_state : int, RandomState instance or None, optional, default: None
If int, random_state is the seed used by the random number generator;
If RandomState instance, random_state is the random number generator;
If None, the random number generator is the RandomState instance used
by `np.random`.
n_jobs : int, default: 1
The number of jobs to use for the computation. This works by computing
each of the n_init runs in parallel.
If -1 all CPUs are used. If 1 is given, no parallel computing code is
used at all, which is useful for debugging. For n_jobs below -1,
(n_cpus + 1 + n_jobs) are used. Thus for n_jobs = -2, all CPUs but one
are used.
Attributes
----------
cluster_centroids_ : array, [n_clusters, n_features]
Categories of cluster centroids
labels_ :
Labels of each point
cost_ : float
Clustering cost, defined as the sum distance of all points to
their respective cluster centroids.
n_iter_ : int
The number of iterations the algorithm ran for.
gamma : float
The (potentially calculated) weighing factor.
Notes
-----
See:
Huang, Z.: Extensions to the k-modes algorithm for clustering large
data sets with categorical values, Data Mining and Knowledge
Discovery 2(3), 1998.
"""
def __init__(self, n_clusters=8, max_iter=100, num_dissim=euclidean_dissim,
cat_dissim=matching_dissim, init='Huang', n_init=10, gamma=None,
verbose=0, random_state=None, n_jobs=1):
super(KPrototypes, self).__init__(n_clusters, max_iter, cat_dissim, init,
verbose=verbose, random_state=random_state,
n_jobs=n_jobs)
self.num_dissim = num_dissim
self.gamma = gamma
self.n_init = n_init
if isinstance(self.init, list) and self.n_init > 1:
if self.verbose:
print("Initialization method is deterministic. "
"Setting n_init to 1.")
self.n_init = 1
def fit(self, X, y=None, categorical=None):
"""Compute k-prototypes clustering.
Parameters
----------
X : array-like, shape=[n_samples, n_features]
categorical : Index of columns that contain categorical data
"""
if categorical is not None:
assert isinstance(categorical, (int, list, tuple)), "The 'categorical' \
argument needs to be an integer with the index of the categorical \
column in your data, or a list or tuple of several of them, \
but it is a {}.".format(type(categorical))
X = pandas_to_numpy(X)
random_state = check_random_state(self.random_state)
# If self.gamma is None, gamma will be automatically determined from
# the data. The function below returns its value.
self._enc_cluster_centroids, self._enc_map, self.labels_, self.cost_,\
self.n_iter_, self.gamma = k_prototypes(X,
categorical,
self.n_clusters,
self.max_iter,
self.num_dissim,
self.cat_dissim,
self.gamma,
self.init,
self.n_init,
self.verbose,
random_state,
self.n_jobs)
return self
@property
def cluster_centroids_(self):
if hasattr(self, '_enc_cluster_centroids'):
return [
self._enc_cluster_centroids[0],
decode_centroids(self._enc_cluster_centroids[1], self._enc_map)
]
else:
raise AttributeError("'{}' object has no attribute 'cluster_centroids_' "
"because the model is not yet fitted.")
|
nicodv/kmodes | kmodes/util/dissim.py | euclidean_dissim | python | def euclidean_dissim(a, b, **_):
if np.isnan(a).any() or np.isnan(b).any():
raise ValueError("Missing values detected in numerical columns.")
return np.sum((a - b) ** 2, axis=1) | Euclidean distance dissimilarity function | train | https://github.com/nicodv/kmodes/blob/cdb19fe5448aba1bf501626694bb52e68eafab45/kmodes/util/dissim.py#L13-L17 | null | """
Dissimilarity measures for clustering
"""
import numpy as np
def matching_dissim(a, b, **_):
"""Simple matching dissimilarity function"""
return np.sum(a != b, axis=1)
def ng_dissim(a, b, X=None, membship=None):
"""Ng et al.'s dissimilarity measure, as presented in
Michael K. Ng, Mark Junjie Li, Joshua Zhexue Huang, and Zengyou He, "On the
Impact of Dissimilarity Measure in k-Modes Clustering Algorithm", IEEE
Transactions on Pattern Analysis and Machine Intelligence, Vol. 29, No. 3,
January, 2007
This function can potentially speed up training convergence.
Note that membship must be a rectangular array such that the
len(membship) = len(a) and len(membship[i]) = X.shape[1]
In case of missing membship, this function reverts back to
matching dissimilarity (e.g., when predicting).
"""
# Without membership, revert to matching dissimilarity
if membship is None:
return matching_dissim(a, b)
def calc_cjr(b, X, memj, idr):
"""Num objects w/ category value x_{i,r} for rth attr in jth cluster"""
xcids = np.where(memj == 1)
return float((np.take(X, xcids, axis=0)[0][:, idr] == b[idr]).sum(0))
def calc_dissim(b, X, memj, idr):
# Size of jth cluster
cj = float(np.sum(memj))
return (1.0 - (calc_cjr(b, X, memj, idr) / cj)) if cj != 0.0 else 0.0
if len(membship) != a.shape[0] and len(membship[0]) != X.shape[1]:
raise ValueError("'membship' must be a rectangular array where "
"the number of rows in 'membship' equals the "
"number of rows in 'a' and the number of "
"columns in 'membship' equals the number of rows in 'X'.")
return np.array([np.array([calc_dissim(b, X, membship[idj], idr)
if b[idr] == t else 1.0
for idr, t in enumerate(val_a)]).sum(0)
for idj, val_a in enumerate(a)])
|
nicodv/kmodes | kmodes/util/dissim.py | ng_dissim | python | def ng_dissim(a, b, X=None, membship=None):
# Without membership, revert to matching dissimilarity
if membship is None:
return matching_dissim(a, b)
def calc_cjr(b, X, memj, idr):
"""Num objects w/ category value x_{i,r} for rth attr in jth cluster"""
xcids = np.where(memj == 1)
return float((np.take(X, xcids, axis=0)[0][:, idr] == b[idr]).sum(0))
def calc_dissim(b, X, memj, idr):
# Size of jth cluster
cj = float(np.sum(memj))
return (1.0 - (calc_cjr(b, X, memj, idr) / cj)) if cj != 0.0 else 0.0
if len(membship) != a.shape[0] and len(membship[0]) != X.shape[1]:
raise ValueError("'membship' must be a rectangular array where "
"the number of rows in 'membship' equals the "
"number of rows in 'a' and the number of "
"columns in 'membship' equals the number of rows in 'X'.")
return np.array([np.array([calc_dissim(b, X, membship[idj], idr)
if b[idr] == t else 1.0
for idr, t in enumerate(val_a)]).sum(0)
for idj, val_a in enumerate(a)]) | Ng et al.'s dissimilarity measure, as presented in
Michael K. Ng, Mark Junjie Li, Joshua Zhexue Huang, and Zengyou He, "On the
Impact of Dissimilarity Measure in k-Modes Clustering Algorithm", IEEE
Transactions on Pattern Analysis and Machine Intelligence, Vol. 29, No. 3,
January, 2007
This function can potentially speed up training convergence.
Note that membship must be a rectangular array such that the
len(membship) = len(a) and len(membship[i]) = X.shape[1]
In case of missing membship, this function reverts back to
matching dissimilarity (e.g., when predicting). | train | https://github.com/nicodv/kmodes/blob/cdb19fe5448aba1bf501626694bb52e68eafab45/kmodes/util/dissim.py#L20-L58 | [
"def matching_dissim(a, b, **_):\n \"\"\"Simple matching dissimilarity function\"\"\"\n return np.sum(a != b, axis=1)\n"
] | """
Dissimilarity measures for clustering
"""
import numpy as np
def matching_dissim(a, b, **_):
"""Simple matching dissimilarity function"""
return np.sum(a != b, axis=1)
def euclidean_dissim(a, b, **_):
"""Euclidean distance dissimilarity function"""
if np.isnan(a).any() or np.isnan(b).any():
raise ValueError("Missing values detected in numerical columns.")
return np.sum((a - b) ** 2, axis=1)
|
aerkalov/ebooklib | ebooklib/epub.py | write_epub | python | def write_epub(name, book, options=None):
epub = EpubWriter(name, book, options)
epub.process()
try:
epub.write()
except IOError:
pass | Creates epub file with the content defined in EpubBook.
>>> ebooklib.write_epub('book.epub', book)
:Args:
- name: file name for the output file
- book: instance of EpubBook
- options: extra opions as dictionary (optional) | train | https://github.com/aerkalov/ebooklib/blob/305f2dd7f02923ffabf9586a5d16266113d00c4a/ebooklib/epub.py#L1705-L1723 | [
"def process(self):\n # should cache this html parsing so we don't do it for every plugin\n for plg in self.options.get('plugins', []):\n if hasattr(plg, 'before_write'):\n plg.before_write(self.book)\n\n for item in self.book.get_items():\n if isinstance(item, EpubHtml):\n for plg in self.options.get('plugins', []):\n if hasattr(plg, 'html_before_write'):\n plg.html_before_write(self.book, item)\n",
"def write(self):\n # check for the option allowZip64\n self.out = zipfile.ZipFile(self.file_name, 'w', zipfile.ZIP_DEFLATED)\n self.out.writestr('mimetype', 'application/epub+zip', compress_type=zipfile.ZIP_STORED)\n\n self._write_container()\n self._write_opf()\n self._write_items()\n\n self.out.close()\n"
] | # This file is part of EbookLib.
# Copyright (c) 2013 Aleksandar Erkalovic <aerkalov@gmail.com>
#
# EbookLib is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# EbookLib is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with EbookLib. If not, see <http://www.gnu.org/licenses/>.
import zipfile
import six
import logging
import uuid
import posixpath as zip_path
import os.path
from collections import OrderedDict
try:
from urllib.parse import unquote
except ImportError:
from urllib import unquote
from lxml import etree
import ebooklib
from ebooklib.utils import parse_string, parse_html_string, guess_type, get_pages_for_items
# Version of EPUB library
VERSION = (0, 17, 1)
NAMESPACES = {'XML': 'http://www.w3.org/XML/1998/namespace',
'EPUB': 'http://www.idpf.org/2007/ops',
'DAISY': 'http://www.daisy.org/z3986/2005/ncx/',
'OPF': 'http://www.idpf.org/2007/opf',
'CONTAINERNS': 'urn:oasis:names:tc:opendocument:xmlns:container',
'DC': 'http://purl.org/dc/elements/1.1/',
'XHTML': 'http://www.w3.org/1999/xhtml'}
# XML Templates
CONTAINER_PATH = 'META-INF/container.xml'
CONTAINER_XML = '''<?xml version='1.0' encoding='utf-8'?>
<container xmlns="urn:oasis:names:tc:opendocument:xmlns:container" version="1.0">
<rootfiles>
<rootfile media-type="application/oebps-package+xml" full-path="%(folder_name)s/content.opf"/>
</rootfiles>
</container>
'''
NCX_XML = six.b('''<!DOCTYPE ncx PUBLIC "-//NISO//DTD ncx 2005-1//EN" "http://www.daisy.org/z3986/2005/ncx-2005-1.dtd">
<ncx xmlns="http://www.daisy.org/z3986/2005/ncx/" version="2005-1" />''')
NAV_XML = six.b('''<?xml version="1.0" encoding="utf-8"?><!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml" xmlns:epub="http://www.idpf.org/2007/ops"/>''')
CHAPTER_XML = six.b('''<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml" xmlns:epub="http://www.idpf.org/2007/ops" epub:prefix="z3998: http://www.daisy.org/z3998/2012/vocab/structure/#"></html>''')
COVER_XML = six.b('''<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:epub="http://www.idpf.org/2007/ops" lang="en" xml:lang="en">
<head>
<style>
body { margin: 0em; padding: 0em; }
img { max-width: 100%; max-height: 100%; }
</style>
</head>
<body>
<img src="" alt="" />
</body>
</html>''')
IMAGE_MEDIA_TYPES = ['image/jpeg', 'image/jpg', 'image/png', 'image/svg+xml']
# TOC and navigation elements
class Section(object):
def __init__(self, title, href=''):
self.title = title
self.href = href
class Link(object):
def __init__(self, href, title, uid=None):
self.href = href
self.title = title
self.uid = uid
# Exceptions
class EpubException(Exception):
def __init__(self, code, msg):
self.code = code
self.msg = msg
def __str__(self):
return repr(self.msg)
# Items
class EpubItem(object):
"""
Base class for the items in a book.
"""
def __init__(self, uid=None, file_name='', media_type='', content=six.b(''), manifest=True):
"""
:Args:
- uid: Unique identifier for this item (optional)
- file_name: File name for this item (optional)
- media_type: Media type for this item (optional)
- content: Content for this item (optional)
- manifest: Manifest for this item (optional)
"""
self.id = uid
self.file_name = file_name
self.media_type = media_type
self.content = content
self.is_linear = True
self.manifest = manifest
self.book = None
def get_id(self):
"""
Returns unique identifier for this item.
:Returns:
Returns uid number as string.
"""
return self.id
def get_name(self):
"""
Returns name for this item. By default it is always file name but it does not have to be.
:Returns:
Returns file name for this item.
"""
return self.file_name
def get_type(self):
"""
Guess type according to the file extension. Might not be the best way how to do it, but it works for now.
Items can be of type:
- ITEM_UNKNOWN = 0
- ITEM_IMAGE = 1
- ITEM_STYLE = 2
- ITEM_SCRIPT = 3
- ITEM_NAVIGATION = 4
- ITEM_VECTOR = 5
- ITEM_FONT = 6
- ITEM_VIDEO = 7
- ITEM_AUDIO = 8
- ITEM_DOCUMENT = 9
- ITEM_COVER = 10
We map type according to the extensions which are defined in ebooklib.EXTENSIONS.
:Returns:
Returns type of the item as number.
"""
_, ext = zip_path.splitext(self.get_name())
ext = ext.lower()
for uid, ext_list in six.iteritems(ebooklib.EXTENSIONS):
if ext in ext_list:
return uid
return ebooklib.ITEM_UNKNOWN
def get_content(self, default=six.b('')):
"""
Returns content of the item. Content should be of type 'str' (Python 2) or 'bytes' (Python 3)
:Args:
- default: Default value for the content if it is not already defined.
:Returns:
Returns content of the item.
"""
return self.content or default
def set_content(self, content):
"""
Sets content value for this item.
:Args:
- content: Content value
"""
self.content = content
def __str__(self):
return '<EpubItem:%s>' % self.id
class EpubNcx(EpubItem):
"Represents Navigation Control File (NCX) in the EPUB."
def __init__(self, uid='ncx', file_name='toc.ncx'):
super(EpubNcx, self).__init__(uid=uid, file_name=file_name, media_type='application/x-dtbncx+xml')
def __str__(self):
return '<EpubNcx:%s>' % self.id
class EpubCover(EpubItem):
"""
Represents Cover image in the EPUB file.
"""
def __init__(self, uid='cover-img', file_name=''):
super(EpubCover, self).__init__(uid=uid, file_name=file_name)
def get_type(self):
return ebooklib.ITEM_COVER
def __str__(self):
return '<EpubCover:%s:%s>' % (self.id, self.file_name)
class EpubHtml(EpubItem):
"""
Represents HTML document in the EPUB file.
"""
_template_name = 'chapter'
def __init__(self, uid=None, file_name='', media_type='', content=None, title='',
lang=None, direction=None, media_overlay=None, media_duration=None):
super(EpubHtml, self).__init__(uid, file_name, media_type, content)
self.title = title
self.lang = lang
self.direction = direction
self.media_overlay = media_overlay
self.media_duration = media_duration
self.links = []
self.properties = []
self.pages = []
def is_chapter(self):
"""
Returns if this document is chapter or not.
:Returns:
Returns book value.
"""
return True
def get_type(self):
"""
Always returns ebooklib.ITEM_DOCUMENT as type of this document.
:Returns:
Always returns ebooklib.ITEM_DOCUMENT
"""
return ebooklib.ITEM_DOCUMENT
def set_language(self, lang):
"""
Sets language for this book item. By default it will use language of the book but it
can be overwritten with this call.
"""
self.lang = lang
def get_language(self):
"""
Get language code for this book item. Language of the book item can be different from
the language settings defined globaly for book.
:Returns:
As string returns language code.
"""
return self.lang
def add_link(self, **kwgs):
"""
Add additional link to the document. Links will be embeded only inside of this document.
>>> add_link(href='styles.css', rel='stylesheet', type='text/css')
"""
self.links.append(kwgs)
if kwgs.get('type') == 'text/javascript':
if 'scripted' not in self.properties:
self.properties.append('scripted')
def get_links(self):
"""
Returns list of additional links defined for this document.
:Returns:
As tuple return list of links.
"""
return (link for link in self.links)
def get_links_of_type(self, link_type):
"""
Returns list of additional links of specific type.
:Returns:
As tuple returns list of links.
"""
return (link for link in self.links if link.get('type', '') == link_type)
def add_item(self, item):
"""
Add other item to this document. It will create additional links according to the item type.
:Args:
- item: item we want to add defined as instance of EpubItem
"""
if item.get_type() == ebooklib.ITEM_STYLE:
self.add_link(href=item.get_name(), rel='stylesheet', type='text/css')
if item.get_type() == ebooklib.ITEM_SCRIPT:
self.add_link(src=item.get_name(), type='text/javascript')
def get_body_content(self):
"""
Returns content of BODY element for this HTML document. Content will be of type 'str' (Python 2)
or 'bytes' (Python 3).
:Returns:
Returns content of this document.
"""
try:
html_tree = parse_html_string(self.content)
except:
return ''
html_root = html_tree.getroottree()
if len(html_root.find('body')) != 0:
body = html_tree.find('body')
tree_str = etree.tostring(body, pretty_print=True, encoding='utf-8', xml_declaration=False)
# this is so stupid
if tree_str.startswith(six.b('<body>')):
n = tree_str.rindex(six.b('</body>'))
return tree_str[6:n]
return tree_str
return ''
def get_content(self, default=None):
"""
Returns content for this document as HTML string. Content will be of type 'str' (Python 2)
or 'bytes' (Python 3).
:Args:
- default: Default value for the content if it is not defined.
:Returns:
Returns content of this document.
"""
tree = parse_string(self.book.get_template(self._template_name))
tree_root = tree.getroot()
tree_root.set('lang', self.lang or self.book.language)
tree_root.attrib['{%s}lang' % NAMESPACES['XML']] = self.lang or self.book.language
# add to the head also
# <meta charset="utf-8" />
try:
html_tree = parse_html_string(self.content)
except:
return ''
html_root = html_tree.getroottree()
# create and populate head
_head = etree.SubElement(tree_root, 'head')
if self.title != '':
_title = etree.SubElement(_head, 'title')
_title.text = self.title
for lnk in self.links:
if lnk.get('type') == 'text/javascript':
_lnk = etree.SubElement(_head, 'script', lnk)
# force <script></script>
_lnk.text = ''
else:
_lnk = etree.SubElement(_head, 'link', lnk)
# this should not be like this
# head = html_root.find('head')
# if head is not None:
# for i in head.getchildren():
# if i.tag == 'title' and self.title != '':
# continue
# _head.append(i)
# create and populate body
_body = etree.SubElement(tree_root, 'body')
if self.direction:
_body.set('dir', self.direction)
tree_root.set('dir', self.direction)
body = html_tree.find('body')
if body is not None:
for i in body.getchildren():
_body.append(i)
tree_str = etree.tostring(tree, pretty_print=True, encoding='utf-8', xml_declaration=True)
return tree_str
def __str__(self):
return '<EpubHtml:%s:%s>' % (self.id, self.file_name)
class EpubCoverHtml(EpubHtml):
"""
Represents Cover page in the EPUB file.
"""
def __init__(self, uid='cover', file_name='cover.xhtml', image_name='', title='Cover'):
super(EpubCoverHtml, self).__init__(uid=uid, file_name=file_name, title=title)
self.image_name = image_name
self.is_linear = False
def is_chapter(self):
"""
Returns if this document is chapter or not.
:Returns:
Returns book value.
"""
return False
def get_content(self):
"""
Returns content for cover page as HTML string. Content will be of type 'str' (Python 2) or 'bytes' (Python 3).
:Returns:
Returns content of this document.
"""
self.content = self.book.get_template('cover')
tree = parse_string(super(EpubCoverHtml, self).get_content())
tree_root = tree.getroot()
images = tree_root.xpath('//xhtml:img', namespaces={'xhtml': NAMESPACES['XHTML']})
images[0].set('src', self.image_name)
images[0].set('alt', self.title)
tree_str = etree.tostring(tree, pretty_print=True, encoding='utf-8', xml_declaration=True)
return tree_str
def __str__(self):
return '<EpubCoverHtml:%s:%s>' % (self.id, self.file_name)
class EpubNav(EpubHtml):
"""
Represents Navigation Document in the EPUB file.
"""
def __init__(self, uid='nav', file_name='nav.xhtml', media_type='application/xhtml+xml'):
super(EpubNav, self).__init__(uid=uid, file_name=file_name, media_type=media_type)
def is_chapter(self):
"""
Returns if this document is chapter or not.
:Returns:
Returns book value.
"""
return False
def __str__(self):
return '<EpubNav:%s:%s>' % (self.id, self.file_name)
class EpubImage(EpubItem):
"""
Represents Image in the EPUB file.
"""
def __init__(self):
super(EpubImage, self).__init__()
def get_type(self):
return ebooklib.ITEM_IMAGE
def __str__(self):
return '<EpubImage:%s:%s>' % (self.id, self.file_name)
class EpubSMIL(EpubItem):
def __init__(self, uid=None, file_name='', content=None):
super(EpubSMIL, self).__init__(uid=uid, file_name=file_name, media_type='application/smil+xml', content=content)
def get_type(self):
return ebooklib.ITEM_SMIL
def __str__(self):
return '<EpubSMIL:%s:%s>' % (self.id, self.file_name)
# EpubBook
class EpubBook(object):
def __init__(self):
self.EPUB_VERSION = None
self.reset()
# we should have options here
def reset(self):
"Initialises all needed variables to default values"
self.metadata = {}
self.items = []
self.spine = []
self.guide = []
self.pages = []
self.toc = []
self.bindings = []
self.IDENTIFIER_ID = 'id'
self.FOLDER_NAME = 'EPUB'
self._id_html = 0
self._id_image = 0
self._id_static = 0
self.title = ''
self.language = 'en'
self.direction = None
self.templates = {
'ncx': NCX_XML,
'nav': NAV_XML,
'chapter': CHAPTER_XML,
'cover': COVER_XML
}
self.add_metadata('OPF', 'generator', '', {
'name': 'generator', 'content': 'Ebook-lib %s' % '.'.join([str(s) for s in VERSION])
})
# default to using a randomly-unique identifier if one is not specified manually
self.set_identifier(str(uuid.uuid4()))
# custom prefixes and namespaces to be set to the content.opf doc
self.prefixes = []
self.namespaces = {}
def set_identifier(self, uid):
"""
Sets unique id for this epub
:Args:
- uid: Value of unique identifier for this book
"""
self.uid = uid
self.set_unique_metadata('DC', 'identifier', self.uid, {'id': self.IDENTIFIER_ID})
def set_title(self, title):
"""
Set title. You can set multiple titles.
:Args:
- title: Title value
"""
self.title = title
self.add_metadata('DC', 'title', self.title)
def set_language(self, lang):
"""
Set language for this epub. You can set multiple languages. Specific items in the book can have
different language settings.
:Args:
- lang: Language code
"""
self.language = lang
self.add_metadata('DC', 'language', lang)
def set_direction(self, direction):
"""
:Args:
- direction: Options are "ltr", "rtl" and "default"
"""
self.direction = direction
def set_cover(self, file_name, content, create_page=True):
"""
Set cover and create cover document if needed.
:Args:
- file_name: file name of the cover page
- content: Content for the cover image
- create_page: Should cover page be defined. Defined as bool value (optional). Default value is True.
"""
# as it is now, it can only be called once
c0 = EpubCover(file_name=file_name)
c0.content = content
self.add_item(c0)
if create_page:
c1 = EpubCoverHtml(image_name=file_name)
self.add_item(c1)
self.add_metadata(None, 'meta', '', OrderedDict([('name', 'cover'), ('content', 'cover-img')]))
def add_author(self, author, file_as=None, role=None, uid='creator'):
"Add author for this document"
self.add_metadata('DC', 'creator', author, {'id': uid})
if file_as:
self.add_metadata(None, 'meta', file_as, {'refines': '#' + uid,
'property': 'file-as',
'scheme': 'marc:relators'})
if role:
self.add_metadata(None, 'meta', role, {'refines': '#' + uid,
'property': 'role',
'scheme': 'marc:relators'})
def add_metadata(self, namespace, name, value, others=None):
"Add metadata"
if namespace in NAMESPACES:
namespace = NAMESPACES[namespace]
if namespace not in self.metadata:
self.metadata[namespace] = {}
if name not in self.metadata[namespace]:
self.metadata[namespace][name] = []
self.metadata[namespace][name].append((value, others))
def get_metadata(self, namespace, name):
"Retrieve metadata"
if namespace in NAMESPACES:
namespace = NAMESPACES[namespace]
return self.metadata[namespace].get(name, [])
def set_unique_metadata(self, namespace, name, value, others=None):
"Add metadata if metadata with this identifier does not already exist, otherwise update existing metadata."
if namespace in NAMESPACES:
namespace = NAMESPACES[namespace]
if namespace in self.metadata and name in self.metadata[namespace]:
self.metadata[namespace][name] = [(value, others)]
else:
self.add_metadata(namespace, name, value, others)
def add_item(self, item):
"""
Add additional item to the book. If not defined, media type and chapter id will be defined
for the item.
:Args:
- item: Item instance
"""
if item.media_type == '':
(has_guessed, media_type) = guess_type(item.get_name().lower())
if has_guessed:
if media_type is not None:
item.media_type = media_type
else:
item.media_type = has_guessed
else:
item.media_type = 'application/octet-stream'
if not item.get_id():
# make chapter_, image_ and static_ configurable
if isinstance(item, EpubHtml):
item.id = 'chapter_%d' % self._id_html
self._id_html += 1
# If there's a page list, append it to the book's page list
self.pages += item.pages
elif isinstance(item, EpubImage):
item.id = 'image_%d' % self._id_image
self._id_image += 1
else:
item.id = 'static_%d' % self._id_image
self._id_image += 1
item.book = self
self.items.append(item)
return item
def get_item_with_id(self, uid):
"""
Returns item for defined UID.
>>> book.get_item_with_id('image_001')
:Args:
- uid: UID for the item
:Returns:
Returns item object. Returns None if nothing was found.
"""
for item in self.get_items():
if item.id == uid:
return item
return None
def get_item_with_href(self, href):
"""
Returns item for defined HREF.
>>> book.get_item_with_href('EPUB/document.xhtml')
:Args:
- href: HREF for the item we are searching for
:Returns:
Returns item object. Returns None if nothing was found.
"""
for item in self.get_items():
if item.get_name() == href:
return item
return None
def get_items(self):
"""
Returns all items attached to this book.
:Returns:
Returns all items as tuple.
"""
return (item for item in self.items)
def get_items_of_type(self, item_type):
"""
Returns all items of specified type.
>>> book.get_items_of_type(epub.ITEM_IMAGE)
:Args:
- item_type: Type for items we are searching for
:Returns:
Returns found items as tuple.
"""
return (item for item in self.items if item.get_type() == item_type)
def get_items_of_media_type(self, media_type):
"""
Returns all items of specified media type.
:Args:
- media_type: Media type for items we are searching for
:Returns:
Returns found items as tuple.
"""
return (item for item in self.items if item.media_type == media_type)
def set_template(self, name, value):
"""
Defines templates which are used to generate certain types of pages. When defining new value for the template
we have to use content of type 'str' (Python 2) or 'bytes' (Python 3).
At the moment we use these templates:
- ncx
- nav
- chapter
- cover
:Args:
- name: Name for the template
- value: Content for the template
"""
self.templates[name] = value
def get_template(self, name):
"""
Returns value for the template.
:Args:
- name: template name
:Returns:
Value of the template.
"""
return self.templates.get(name)
def add_prefix(self, name, uri):
"""
Appends custom prefix to be added to the content.opf document
>>> epub_book.add_prefix('bkterms', 'http://booktype.org/')
:Args:
- name: namespave name
- uri: URI for the namespace
"""
self.prefixes.append('%s: %s' % (name, uri))
class EpubWriter(object):
DEFAULT_OPTIONS = {
'epub2_guide': True,
'epub3_landmark': True,
'epub3_pages': True,
'landmark_title': 'Guide',
'pages_title': 'Pages',
'spine_direction': True,
'package_direction': False,
'play_order': {
'enabled': False,
'start_from': 1
}
}
def __init__(self, name, book, options=None):
self.file_name = name
self.book = book
self.options = dict(self.DEFAULT_OPTIONS)
if options:
self.options.update(options)
self._init_play_order()
def _init_play_order(self):
self._play_order = {
'enabled': False,
'start_from': 1
}
try:
self._play_order['enabled'] = self.options['play_order']['enabled']
self._play_order['start_from'] = self.options['play_order']['start_from']
except KeyError:
pass
def process(self):
# should cache this html parsing so we don't do it for every plugin
for plg in self.options.get('plugins', []):
if hasattr(plg, 'before_write'):
plg.before_write(self.book)
for item in self.book.get_items():
if isinstance(item, EpubHtml):
for plg in self.options.get('plugins', []):
if hasattr(plg, 'html_before_write'):
plg.html_before_write(self.book, item)
def _write_container(self):
container_xml = CONTAINER_XML % {'folder_name': self.book.FOLDER_NAME}
self.out.writestr(CONTAINER_PATH, container_xml)
def _write_opf_metadata(self, root):
# This is really not needed
# problem is uppercase/lowercase
# for ns_name, values in six.iteritems(self.book.metadata):
# if ns_name:
# for n_id, ns_url in six.iteritems(NAMESPACES):
# if ns_name == ns_url:
# nsmap[n_id.lower()] = NAMESPACES[n_id]
nsmap = {'dc': NAMESPACES['DC'], 'opf': NAMESPACES['OPF']}
nsmap.update(self.book.namespaces)
metadata = etree.SubElement(root, 'metadata', nsmap=nsmap)
el = etree.SubElement(metadata, 'meta', {'property': 'dcterms:modified'})
if 'mtime' in self.options:
mtime = self.options['mtime']
else:
import datetime
mtime = datetime.datetime.now()
el.text = mtime.strftime('%Y-%m-%dT%H:%M:%SZ')
for ns_name, values in six.iteritems(self.book.metadata):
if ns_name == NAMESPACES['OPF']:
for values in values.values():
for v in values:
if 'property' in v[1] and v[1]['property'] == 'dcterms:modified':
continue
try:
el = etree.SubElement(metadata, 'meta', v[1])
if v[0]:
el.text = v[0]
except ValueError:
logging.error('Could not create metadata.')
else:
for name, values in six.iteritems(values):
for v in values:
try:
if ns_name:
el = etree.SubElement(metadata, '{%s}%s' % (ns_name, name), v[1])
else:
el = etree.SubElement(metadata, '%s' % name, v[1])
el.text = v[0]
except ValueError:
logging.error('Could not create metadata "{}".'.format(name))
def _write_opf_manifest(self, root):
manifest = etree.SubElement(root, 'manifest')
_ncx_id = None
# mathml, scripted, svg, remote-resources, and switch
# nav
# cover-image
for item in self.book.get_items():
if not item.manifest:
continue
if isinstance(item, EpubNav):
etree.SubElement(manifest, 'item', {'href': item.get_name(),
'id': item.id,
'media-type': item.media_type,
'properties': 'nav'})
elif isinstance(item, EpubNcx):
_ncx_id = item.id
etree.SubElement(manifest, 'item', {'href': item.file_name,
'id': item.id,
'media-type': item.media_type})
elif isinstance(item, EpubCover):
etree.SubElement(manifest, 'item', {'href': item.file_name,
'id': item.id,
'media-type': item.media_type,
'properties': 'cover-image'})
else:
opts = {'href': item.file_name,
'id': item.id,
'media-type': item.media_type}
if hasattr(item, 'properties') and len(item.properties) > 0:
opts['properties'] = ' '.join(item.properties)
if hasattr(item, 'media_overlay') and item.media_overlay is not None:
opts['media-overlay'] = item.media_overlay
if hasattr(item, 'media_duration') and item.media_duration is not None:
opts['duration'] = item.media_duration
etree.SubElement(manifest, 'item', opts)
return _ncx_id
def _write_opf_spine(self, root, ncx_id):
spine_attributes = {'toc': ncx_id or 'ncx'}
if self.book.direction and self.options['spine_direction']:
spine_attributes['page-progression-direction'] = self.book.direction
spine = etree.SubElement(root, 'spine', spine_attributes)
for _item in self.book.spine:
# this is for now
# later we should be able to fetch things from tuple
is_linear = True
if isinstance(_item, tuple):
item = _item[0]
if len(_item) > 1:
if _item[1] == 'no':
is_linear = False
else:
item = _item
if isinstance(item, EpubHtml):
opts = {'idref': item.get_id()}
if not item.is_linear or not is_linear:
opts['linear'] = 'no'
elif isinstance(item, EpubItem):
opts = {'idref': item.get_id()}
if not item.is_linear or not is_linear:
opts['linear'] = 'no'
else:
opts = {'idref': item}
try:
itm = self.book.get_item_with_id(item)
if not itm.is_linear or not is_linear:
opts['linear'] = 'no'
except:
pass
etree.SubElement(spine, 'itemref', opts)
def _write_opf_guide(self, root):
# - http://www.idpf.org/epub/20/spec/OPF_2.0.1_draft.htm#Section2.6
if len(self.book.guide) > 0 and self.options.get('epub2_guide'):
guide = etree.SubElement(root, 'guide', {})
for item in self.book.guide:
if 'item' in item:
chap = item.get('item')
if chap:
_href = chap.file_name
_title = chap.title
else:
_href = item.get('href', '')
_title = item.get('title', '')
if _title is None:
_title = ''
ref = etree.SubElement(guide, 'reference', {'type': item.get('type', ''),
'title': _title,
'href': _href})
def _write_opf_bindings(self, root):
if len(self.book.bindings) > 0:
bindings = etree.SubElement(root, 'bindings', {})
for item in self.book.bindings:
etree.SubElement(bindings, 'mediaType', item)
def _write_opf_file(self, root):
tree_str = etree.tostring(root, pretty_print=True, encoding='utf-8', xml_declaration=True)
self.out.writestr('%s/content.opf' % self.book.FOLDER_NAME, tree_str)
def _write_opf(self):
package_attributes = {'xmlns': NAMESPACES['OPF'],
'unique-identifier': self.book.IDENTIFIER_ID,
'version': '3.0'}
if self.book.direction and self.options['package_direction']:
package_attributes['dir'] = self.book.direction
root = etree.Element('package', package_attributes)
prefixes = ['rendition: http://www.idpf.org/vocab/rendition/#'] + self.book.prefixes
root.attrib['prefix'] = ' '.join(prefixes)
# METADATA
self._write_opf_metadata(root)
# MANIFEST
_ncx_id = self._write_opf_manifest(root)
# SPINE
self._write_opf_spine(root, _ncx_id)
# GUIDE
self._write_opf_guide(root)
# BINDINGS
self._write_opf_bindings(root)
# WRITE FILE
self._write_opf_file(root)
def _get_nav(self, item):
# just a basic navigation for now
nav_xml = parse_string(self.book.get_template('nav'))
root = nav_xml.getroot()
root.set('lang', self.book.language)
root.attrib['{%s}lang' % NAMESPACES['XML']] = self.book.language
nav_dir_name = os.path.dirname(item.file_name)
head = etree.SubElement(root, 'head')
title = etree.SubElement(head, 'title')
title.text = self.book.title
# for now this just handles css files and ignores others
for _link in item.links:
_lnk = etree.SubElement(head, 'link', {
'href': _link.get('href', ''), 'rel': 'stylesheet', 'type': 'text/css'
})
body = etree.SubElement(root, 'body')
nav = etree.SubElement(body, 'nav', {
'{%s}type' % NAMESPACES['EPUB']: 'toc',
'id': 'id',
'role': 'doc-toc',
})
content_title = etree.SubElement(nav, 'h2')
content_title.text = self.book.title
def _create_section(itm, items):
ol = etree.SubElement(itm, 'ol')
for item in items:
if isinstance(item, tuple) or isinstance(item, list):
li = etree.SubElement(ol, 'li')
if isinstance(item[0], EpubHtml):
a = etree.SubElement(li, 'a', {'href': os.path.relpath(item[0].file_name, nav_dir_name)})
elif isinstance(item[0], Section) and item[0].href != '':
a = etree.SubElement(li, 'a', {'href': os.path.relpath(item[0].href, nav_dir_name)})
elif isinstance(item[0], Link):
a = etree.SubElement(li, 'a', {'href': os.path.relpath(item[0].href, nav_dir_name)})
else:
a = etree.SubElement(li, 'span')
a.text = item[0].title
_create_section(li, item[1])
elif isinstance(item, Link):
li = etree.SubElement(ol, 'li')
a = etree.SubElement(li, 'a', {'href': os.path.relpath(item.href, nav_dir_name)})
a.text = item.title
elif isinstance(item, EpubHtml):
li = etree.SubElement(ol, 'li')
a = etree.SubElement(li, 'a', {'href': os.path.relpath(item.file_name, nav_dir_name)})
a.text = item.title
_create_section(nav, self.book.toc)
# LANDMARKS / GUIDE
# - http://www.idpf.org/epub/30/spec/epub30-contentdocs.html#sec-xhtml-nav-def-types-landmarks
if len(self.book.guide) > 0 and self.options.get('epub3_landmark'):
# Epub2 guide types do not map completely to epub3 landmark types.
guide_to_landscape_map = {
'notes': 'rearnotes',
'text': 'bodymatter'
}
guide_nav = etree.SubElement(body, 'nav', {'{%s}type' % NAMESPACES['EPUB']: 'landmarks'})
guide_content_title = etree.SubElement(guide_nav, 'h2')
guide_content_title.text = self.options.get('landmark_title', 'Guide')
guild_ol = etree.SubElement(guide_nav, 'ol')
for elem in self.book.guide:
li_item = etree.SubElement(guild_ol, 'li')
if 'item' in elem:
chap = elem.get('item', None)
if chap:
_href = chap.file_name
_title = chap.title
else:
_href = elem.get('href', '')
_title = elem.get('title', '')
guide_type = elem.get('type', '')
a_item = etree.SubElement(li_item, 'a', {
'{%s}type' % NAMESPACES['EPUB']: guide_to_landscape_map.get(guide_type, guide_type),
'href': os.path.relpath(_href, nav_dir_name)
})
a_item.text = _title
# PAGE-LIST
if self.options.get('epub3_pages'):
inserted_pages = get_pages_for_items([item for item in self.book.get_items_of_type(ebooklib.ITEM_DOCUMENT) \
if not isinstance(item, EpubNav)])
if len(inserted_pages) > 0:
pagelist_nav = etree.SubElement(
body,
'nav',
{
'{%s}type' % NAMESPACES['EPUB']: 'page-list',
'id': 'pages',
'hidden': 'hidden',
}
)
pagelist_content_title = etree.SubElement(pagelist_nav, 'h2')
pagelist_content_title.text = self.options.get(
'pages_title', 'Pages'
)
pages_ol = etree.SubElement(pagelist_nav, 'ol')
for filename, pageref, label in inserted_pages:
li_item = etree.SubElement(pages_ol, 'li')
_href = u'{}#{}'.format(filename, pageref)
_title = label
a_item = etree.SubElement(li_item, 'a', {
'href': os.path.relpath(_href, nav_dir_name),
})
a_item.text = _title
tree_str = etree.tostring(nav_xml, pretty_print=True, encoding='utf-8', xml_declaration=True)
return tree_str
def _get_ncx(self):
# we should be able to setup language for NCX as also
ncx = parse_string(self.book.get_template('ncx'))
root = ncx.getroot()
head = etree.SubElement(root, 'head')
# get this id
uid = etree.SubElement(head, 'meta', {'content': self.book.uid, 'name': 'dtb:uid'})
uid = etree.SubElement(head, 'meta', {'content': '0', 'name': 'dtb:depth'})
uid = etree.SubElement(head, 'meta', {'content': '0', 'name': 'dtb:totalPageCount'})
uid = etree.SubElement(head, 'meta', {'content': '0', 'name': 'dtb:maxPageNumber'})
doc_title = etree.SubElement(root, 'docTitle')
title = etree.SubElement(doc_title, 'text')
title.text = self.book.title
# doc_author = etree.SubElement(root, 'docAuthor')
# author = etree.SubElement(doc_author, 'text')
# author.text = 'Name of the person'
# For now just make a very simple navMap
nav_map = etree.SubElement(root, 'navMap')
def _add_play_order(nav_point):
nav_point.set('playOrder', str(self._play_order['start_from']))
self._play_order['start_from'] += 1
def _create_section(itm, items, uid):
for item in items:
if isinstance(item, tuple) or isinstance(item, list):
section, subsection = item[0], item[1]
np = etree.SubElement(itm, 'navPoint', {
'id': section.get_id() if isinstance(section, EpubHtml) else 'sep_%d' % uid
})
if self._play_order['enabled']:
_add_play_order(np)
nl = etree.SubElement(np, 'navLabel')
nt = etree.SubElement(nl, 'text')
nt.text = section.title
# CAN NOT HAVE EMPTY SRC HERE
href = ''
if isinstance(section, EpubHtml):
href = section.file_name
elif isinstance(section, Section) and section.href != '':
href = section.href
elif isinstance(section, Link):
href = section.href
nc = etree.SubElement(np, 'content', {'src': href})
uid = _create_section(np, subsection, uid + 1)
elif isinstance(item, Link):
_parent = itm
_content = _parent.find('content')
if _content is not None:
if _content.get('src') == '':
_content.set('src', item.href)
np = etree.SubElement(itm, 'navPoint', {'id': item.uid})
if self._play_order['enabled']:
_add_play_order(np)
nl = etree.SubElement(np, 'navLabel')
nt = etree.SubElement(nl, 'text')
nt.text = item.title
nc = etree.SubElement(np, 'content', {'src': item.href})
elif isinstance(item, EpubHtml):
_parent = itm
_content = _parent.find('content')
if _content is not None:
if _content.get('src') == '':
_content.set('src', item.file_name)
np = etree.SubElement(itm, 'navPoint', {'id': item.get_id()})
if self._play_order['enabled']:
_add_play_order(np)
nl = etree.SubElement(np, 'navLabel')
nt = etree.SubElement(nl, 'text')
nt.text = item.title
nc = etree.SubElement(np, 'content', {'src': item.file_name})
return uid
_create_section(nav_map, self.book.toc, 0)
tree_str = etree.tostring(root, pretty_print=True, encoding='utf-8', xml_declaration=True)
return tree_str
def _write_items(self):
for item in self.book.get_items():
if isinstance(item, EpubNcx):
self.out.writestr('%s/%s' % (self.book.FOLDER_NAME, item.file_name), self._get_ncx())
elif isinstance(item, EpubNav):
self.out.writestr('%s/%s' % (self.book.FOLDER_NAME, item.file_name), self._get_nav(item))
elif item.manifest:
self.out.writestr('%s/%s' % (self.book.FOLDER_NAME, item.file_name), item.get_content())
else:
self.out.writestr('%s' % item.file_name, item.get_content())
def write(self):
# check for the option allowZip64
self.out = zipfile.ZipFile(self.file_name, 'w', zipfile.ZIP_DEFLATED)
self.out.writestr('mimetype', 'application/epub+zip', compress_type=zipfile.ZIP_STORED)
self._write_container()
self._write_opf()
self._write_items()
self.out.close()
class EpubReader(object):
DEFAULT_OPTIONS = {}
def __init__(self, epub_file_name, options=None):
self.file_name = epub_file_name
self.book = EpubBook()
self.zf = None
self.opf_file = ''
self.opf_dir = ''
self.options = dict(self.DEFAULT_OPTIONS)
if options:
self.options.update(options)
def process(self):
# should cache this html parsing so we don't do it for every plugin
for plg in self.options.get('plugins', []):
if hasattr(plg, 'after_read'):
plg.after_read(self.book)
for item in self.book.get_items():
if isinstance(item, EpubHtml):
for plg in self.options.get('plugins', []):
if hasattr(plg, 'html_after_read'):
plg.html_after_read(self.book, item)
def load(self):
self._load()
return self.book
def read_file(self, name):
# Raises KeyError
name = zip_path.normpath(name)
return self.zf.read(name)
def _load_container(self):
meta_inf = self.read_file('META-INF/container.xml')
tree = parse_string(meta_inf)
for root_file in tree.findall('//xmlns:rootfile[@media-type]', namespaces={'xmlns': NAMESPACES['CONTAINERNS']}):
if root_file.get('media-type') == 'application/oebps-package+xml':
self.opf_file = root_file.get('full-path')
self.opf_dir = zip_path.dirname(self.opf_file)
def _load_metadata(self):
container_root = self.container.getroot()
# get epub version
self.book.version = container_root.get('version', None)
# get unique-identifier
if container_root.get('unique-identifier', None):
self.book.IDENTIFIER_ID = container_root.get('unique-identifier')
# get xml:lang
# get metadata
metadata = self.container.find('{%s}%s' % (NAMESPACES['OPF'], 'metadata'))
nsmap = metadata.nsmap
nstags = dict((k, '{%s}' % v) for k, v in six.iteritems(nsmap))
default_ns = nstags.get(None, '')
nsdict = dict((v, {}) for v in nsmap.values())
def add_item(ns, tag, value, extra):
if ns not in nsdict:
nsdict[ns] = {}
values = nsdict[ns].setdefault(tag, [])
values.append((value, extra))
for t in metadata:
if not etree.iselement(t) or t.tag is etree.Comment:
continue
if t.tag == default_ns + 'meta':
name = t.get('name')
others = dict((k, v) for k, v in t.items())
if name and ':' in name:
prefix, name = name.split(':', 1)
else:
prefix = None
add_item(t.nsmap.get(prefix, prefix), name, t.text, others)
else:
tag = t.tag[t.tag.rfind('}') + 1:]
if (t.prefix and t.prefix.lower() == 'dc') and tag == 'identifier':
_id = t.get('id', None)
if _id:
self.book.IDENTIFIER_ID = _id
others = dict((k, v) for k, v in t.items())
add_item(t.nsmap[t.prefix], tag, t.text, others)
self.book.metadata = nsdict
titles = self.book.get_metadata('DC', 'title')
if len(titles) > 0:
self.book.title = titles[0][0]
for value, others in self.book.get_metadata('DC', 'identifier'):
if others.get('id') == self.book.IDENTIFIER_ID:
self.book.uid = value
def _load_manifest(self):
for r in self.container.find('{%s}%s' % (NAMESPACES['OPF'], 'manifest')):
if r is not None and r.tag != '{%s}item' % NAMESPACES['OPF']:
continue
media_type = r.get('media-type')
_properties = r.get('properties', '')
if _properties:
properties = _properties.split(' ')
else:
properties = []
# people use wrong content types
if media_type == 'image/jpg':
media_type = 'image/jpeg'
if media_type == 'application/x-dtbncx+xml':
ei = EpubNcx(uid=r.get('id'), file_name=unquote(r.get('href')))
ei.content = self.read_file(zip_path.join(self.opf_dir, ei.file_name))
if media_type == 'application/smil+xml':
ei = EpubSMIL(uid=r.get('id'), file_name=unquote(r.get('href')))
ei.content = self.read_file(zip_path.join(self.opf_dir, ei.file_name))
elif media_type == 'application/xhtml+xml':
if 'nav' in properties:
ei = EpubNav(uid=r.get('id'), file_name=unquote(r.get('href')))
ei.content = self.read_file(zip_path.join(self.opf_dir, r.get('href')))
elif 'cover' in properties:
ei = EpubCoverHtml()
ei.content = self.read_file(zip_path.join(self.opf_dir, unquote(r.get('href'))))
else:
ei = EpubHtml()
ei.id = r.get('id')
ei.file_name = unquote(r.get('href'))
ei.media_type = media_type
ei.media_overlay = r.get('media-overlay', None)
ei.media_duration = r.get('duration', None)
ei.content = self.read_file(zip_path.join(self.opf_dir, ei.get_name()))
ei.properties = properties
elif media_type in IMAGE_MEDIA_TYPES:
if 'cover-image' in properties:
ei = EpubCover(uid=r.get('id'), file_name=unquote(r.get('href')))
ei.media_type = media_type
ei.content = self.read_file(zip_path.join(self.opf_dir, ei.get_name()))
else:
ei = EpubImage()
ei.id = r.get('id')
ei.file_name = unquote(r.get('href'))
ei.media_type = media_type
ei.content = self.read_file(zip_path.join(self.opf_dir, ei.get_name()))
else:
# different types
ei = EpubItem()
ei.id = r.get('id')
ei.file_name = unquote(r.get('href'))
ei.media_type = media_type
ei.content = self.read_file(zip_path.join(self.opf_dir, ei.get_name()))
self.book.add_item(ei)
def _parse_ncx(self, data):
tree = parse_string(data)
tree_root = tree.getroot()
nav_map = tree_root.find('{%s}navMap' % NAMESPACES['DAISY'])
def _get_children(elems, n, nid):
label, content = '', ''
children = []
for a in elems.getchildren():
if a.tag == '{%s}navLabel' % NAMESPACES['DAISY']:
label = a.getchildren()[0].text
if a.tag == '{%s}content' % NAMESPACES['DAISY']:
content = a.get('src', '')
if a.tag == '{%s}navPoint' % NAMESPACES['DAISY']:
children.append(_get_children(a, n + 1, a.get('id', '')))
if len(children) > 0:
if n == 0:
return children
return (Section(label, href=content),
children)
else:
return Link(content, label, nid)
self.book.toc = _get_children(nav_map, 0, '')
def _parse_nav(self, data, base_path, navtype='toc'):
html_node = parse_html_string(data)
if navtype == 'toc':
# parsing the table of contents
nav_node = html_node.xpath("//nav[@*='toc']")[0]
else:
# parsing the list of pages
_page_list = html_node.xpath("//nav[@*='page-list']")
if len(_page_list) == 0:
return
nav_node = _page_list[0]
def parse_list(list_node):
items = []
for item_node in list_node.findall('li'):
sublist_node = item_node.find('ol')
link_node = item_node.find('a')
if sublist_node is not None:
title = item_node[0].text
children = parse_list(sublist_node)
if link_node is not None:
href = zip_path.normpath(zip_path.join(base_path, link_node.get('href')))
items.append((Section(title, href=href), children))
else:
items.append((Section(title), children))
elif link_node is not None:
title = link_node.text
href = zip_path.normpath(zip_path.join(base_path, link_node.get('href')))
items.append(Link(href, title))
return items
if navtype == 'toc':
self.book.toc = parse_list(nav_node.find('ol'))
elif nav_node is not None:
# generate the pages list if there is one
self.book.pages = parse_list(nav_node.find('ol'))
# generate the per-file pages lists
# because of the order of parsing the files, this can't be done
# when building the EpubHtml objects
htmlfiles = dict()
for htmlfile in self.book.items:
if isinstance(htmlfile, EpubHtml):
htmlfiles[htmlfile.file_name] = htmlfile
for page in self.book.pages:
try:
(filename, idref) = page.href.split('#')
except ValueError:
filename = page.href
if filename in htmlfiles:
htmlfiles[filename].pages.append(page)
def _load_spine(self):
spine = self.container.find('{%s}%s' % (NAMESPACES['OPF'], 'spine'))
self.book.spine = [(t.get('idref'), t.get('linear', 'yes')) for t in spine]
toc = spine.get('toc', '')
self.book.set_direction(spine.get('page-progression-direction', None))
# should read ncx or nav file
if toc:
try:
ncxFile = self.read_file(zip_path.join(self.opf_dir, self.book.get_item_with_id(toc).get_name()))
except KeyError:
raise EpubException(-1, 'Can not find ncx file.')
self._parse_ncx(ncxFile)
def _load_guide(self):
guide = self.container.find('{%s}%s' % (NAMESPACES['OPF'], 'guide'))
if guide is not None:
self.book.guide = [{'href': t.get('href'), 'title': t.get('title'), 'type': t.get('type')} for t in guide]
def _load_opf_file(self):
try:
s = self.read_file(self.opf_file)
except KeyError:
raise EpubException(-1, 'Can not find container file')
self.container = parse_string(s)
self._load_metadata()
self._load_manifest()
self._load_spine()
self._load_guide()
# read nav file if found
#
nav_item = next((item for item in self.book.items if isinstance(item, EpubNav)), None)
if nav_item:
if not self.book.toc:
self._parse_nav(
nav_item.content,
zip_path.dirname(nav_item.file_name),
navtype='toc'
)
self._parse_nav(
nav_item.content,
zip_path.dirname(nav_item.file_name),
navtype='pages'
)
def _load(self):
try:
self.zf = zipfile.ZipFile(self.file_name, 'r', compression=zipfile.ZIP_DEFLATED, allowZip64=True)
except zipfile.BadZipfile as bz:
raise EpubException(0, 'Bad Zip file')
except zipfile.LargeZipFile as bz:
raise EpubException(1, 'Large Zip file')
# 1st check metadata
self._load_container()
self._load_opf_file()
self.zf.close()
# WRITE
# READ
def read_epub(name, options=None):
"""
Creates new instance of EpubBook with the content defined in the input file.
>>> book = ebooklib.read_epub('book.epub')
:Args:
- name: full path to the input file
- options: extra options as dictionary (optional)
:Returns:
Instance of EpubBook.
"""
reader = EpubReader(name, options)
book = reader.load()
reader.process()
return book
|
aerkalov/ebooklib | ebooklib/epub.py | read_epub | python | def read_epub(name, options=None):
reader = EpubReader(name, options)
book = reader.load()
reader.process()
return book | Creates new instance of EpubBook with the content defined in the input file.
>>> book = ebooklib.read_epub('book.epub')
:Args:
- name: full path to the input file
- options: extra options as dictionary (optional)
:Returns:
Instance of EpubBook. | train | https://github.com/aerkalov/ebooklib/blob/305f2dd7f02923ffabf9586a5d16266113d00c4a/ebooklib/epub.py#L1728-L1746 | [
"def process(self):\n # should cache this html parsing so we don't do it for every plugin\n for plg in self.options.get('plugins', []):\n if hasattr(plg, 'after_read'):\n plg.after_read(self.book)\n\n for item in self.book.get_items():\n if isinstance(item, EpubHtml):\n for plg in self.options.get('plugins', []):\n if hasattr(plg, 'html_after_read'):\n plg.html_after_read(self.book, item)\n",
"def load(self):\n self._load()\n\n return self.book\n"
] | # This file is part of EbookLib.
# Copyright (c) 2013 Aleksandar Erkalovic <aerkalov@gmail.com>
#
# EbookLib is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# EbookLib is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with EbookLib. If not, see <http://www.gnu.org/licenses/>.
import zipfile
import six
import logging
import uuid
import posixpath as zip_path
import os.path
from collections import OrderedDict
try:
from urllib.parse import unquote
except ImportError:
from urllib import unquote
from lxml import etree
import ebooklib
from ebooklib.utils import parse_string, parse_html_string, guess_type, get_pages_for_items
# Version of EPUB library
VERSION = (0, 17, 1)
NAMESPACES = {'XML': 'http://www.w3.org/XML/1998/namespace',
'EPUB': 'http://www.idpf.org/2007/ops',
'DAISY': 'http://www.daisy.org/z3986/2005/ncx/',
'OPF': 'http://www.idpf.org/2007/opf',
'CONTAINERNS': 'urn:oasis:names:tc:opendocument:xmlns:container',
'DC': 'http://purl.org/dc/elements/1.1/',
'XHTML': 'http://www.w3.org/1999/xhtml'}
# XML Templates
CONTAINER_PATH = 'META-INF/container.xml'
CONTAINER_XML = '''<?xml version='1.0' encoding='utf-8'?>
<container xmlns="urn:oasis:names:tc:opendocument:xmlns:container" version="1.0">
<rootfiles>
<rootfile media-type="application/oebps-package+xml" full-path="%(folder_name)s/content.opf"/>
</rootfiles>
</container>
'''
NCX_XML = six.b('''<!DOCTYPE ncx PUBLIC "-//NISO//DTD ncx 2005-1//EN" "http://www.daisy.org/z3986/2005/ncx-2005-1.dtd">
<ncx xmlns="http://www.daisy.org/z3986/2005/ncx/" version="2005-1" />''')
NAV_XML = six.b('''<?xml version="1.0" encoding="utf-8"?><!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml" xmlns:epub="http://www.idpf.org/2007/ops"/>''')
CHAPTER_XML = six.b('''<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml" xmlns:epub="http://www.idpf.org/2007/ops" epub:prefix="z3998: http://www.daisy.org/z3998/2012/vocab/structure/#"></html>''')
COVER_XML = six.b('''<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:epub="http://www.idpf.org/2007/ops" lang="en" xml:lang="en">
<head>
<style>
body { margin: 0em; padding: 0em; }
img { max-width: 100%; max-height: 100%; }
</style>
</head>
<body>
<img src="" alt="" />
</body>
</html>''')
IMAGE_MEDIA_TYPES = ['image/jpeg', 'image/jpg', 'image/png', 'image/svg+xml']
# TOC and navigation elements
class Section(object):
def __init__(self, title, href=''):
self.title = title
self.href = href
class Link(object):
def __init__(self, href, title, uid=None):
self.href = href
self.title = title
self.uid = uid
# Exceptions
class EpubException(Exception):
def __init__(self, code, msg):
self.code = code
self.msg = msg
def __str__(self):
return repr(self.msg)
# Items
class EpubItem(object):
"""
Base class for the items in a book.
"""
def __init__(self, uid=None, file_name='', media_type='', content=six.b(''), manifest=True):
"""
:Args:
- uid: Unique identifier for this item (optional)
- file_name: File name for this item (optional)
- media_type: Media type for this item (optional)
- content: Content for this item (optional)
- manifest: Manifest for this item (optional)
"""
self.id = uid
self.file_name = file_name
self.media_type = media_type
self.content = content
self.is_linear = True
self.manifest = manifest
self.book = None
def get_id(self):
"""
Returns unique identifier for this item.
:Returns:
Returns uid number as string.
"""
return self.id
def get_name(self):
"""
Returns name for this item. By default it is always file name but it does not have to be.
:Returns:
Returns file name for this item.
"""
return self.file_name
def get_type(self):
"""
Guess type according to the file extension. Might not be the best way how to do it, but it works for now.
Items can be of type:
- ITEM_UNKNOWN = 0
- ITEM_IMAGE = 1
- ITEM_STYLE = 2
- ITEM_SCRIPT = 3
- ITEM_NAVIGATION = 4
- ITEM_VECTOR = 5
- ITEM_FONT = 6
- ITEM_VIDEO = 7
- ITEM_AUDIO = 8
- ITEM_DOCUMENT = 9
- ITEM_COVER = 10
We map type according to the extensions which are defined in ebooklib.EXTENSIONS.
:Returns:
Returns type of the item as number.
"""
_, ext = zip_path.splitext(self.get_name())
ext = ext.lower()
for uid, ext_list in six.iteritems(ebooklib.EXTENSIONS):
if ext in ext_list:
return uid
return ebooklib.ITEM_UNKNOWN
def get_content(self, default=six.b('')):
"""
Returns content of the item. Content should be of type 'str' (Python 2) or 'bytes' (Python 3)
:Args:
- default: Default value for the content if it is not already defined.
:Returns:
Returns content of the item.
"""
return self.content or default
def set_content(self, content):
"""
Sets content value for this item.
:Args:
- content: Content value
"""
self.content = content
def __str__(self):
return '<EpubItem:%s>' % self.id
class EpubNcx(EpubItem):
"Represents Navigation Control File (NCX) in the EPUB."
def __init__(self, uid='ncx', file_name='toc.ncx'):
super(EpubNcx, self).__init__(uid=uid, file_name=file_name, media_type='application/x-dtbncx+xml')
def __str__(self):
return '<EpubNcx:%s>' % self.id
class EpubCover(EpubItem):
"""
Represents Cover image in the EPUB file.
"""
def __init__(self, uid='cover-img', file_name=''):
super(EpubCover, self).__init__(uid=uid, file_name=file_name)
def get_type(self):
return ebooklib.ITEM_COVER
def __str__(self):
return '<EpubCover:%s:%s>' % (self.id, self.file_name)
class EpubHtml(EpubItem):
"""
Represents HTML document in the EPUB file.
"""
_template_name = 'chapter'
def __init__(self, uid=None, file_name='', media_type='', content=None, title='',
lang=None, direction=None, media_overlay=None, media_duration=None):
super(EpubHtml, self).__init__(uid, file_name, media_type, content)
self.title = title
self.lang = lang
self.direction = direction
self.media_overlay = media_overlay
self.media_duration = media_duration
self.links = []
self.properties = []
self.pages = []
def is_chapter(self):
"""
Returns if this document is chapter or not.
:Returns:
Returns book value.
"""
return True
def get_type(self):
"""
Always returns ebooklib.ITEM_DOCUMENT as type of this document.
:Returns:
Always returns ebooklib.ITEM_DOCUMENT
"""
return ebooklib.ITEM_DOCUMENT
def set_language(self, lang):
"""
Sets language for this book item. By default it will use language of the book but it
can be overwritten with this call.
"""
self.lang = lang
def get_language(self):
"""
Get language code for this book item. Language of the book item can be different from
the language settings defined globaly for book.
:Returns:
As string returns language code.
"""
return self.lang
def add_link(self, **kwgs):
"""
Add additional link to the document. Links will be embeded only inside of this document.
>>> add_link(href='styles.css', rel='stylesheet', type='text/css')
"""
self.links.append(kwgs)
if kwgs.get('type') == 'text/javascript':
if 'scripted' not in self.properties:
self.properties.append('scripted')
def get_links(self):
"""
Returns list of additional links defined for this document.
:Returns:
As tuple return list of links.
"""
return (link for link in self.links)
def get_links_of_type(self, link_type):
"""
Returns list of additional links of specific type.
:Returns:
As tuple returns list of links.
"""
return (link for link in self.links if link.get('type', '') == link_type)
def add_item(self, item):
"""
Add other item to this document. It will create additional links according to the item type.
:Args:
- item: item we want to add defined as instance of EpubItem
"""
if item.get_type() == ebooklib.ITEM_STYLE:
self.add_link(href=item.get_name(), rel='stylesheet', type='text/css')
if item.get_type() == ebooklib.ITEM_SCRIPT:
self.add_link(src=item.get_name(), type='text/javascript')
def get_body_content(self):
"""
Returns content of BODY element for this HTML document. Content will be of type 'str' (Python 2)
or 'bytes' (Python 3).
:Returns:
Returns content of this document.
"""
try:
html_tree = parse_html_string(self.content)
except:
return ''
html_root = html_tree.getroottree()
if len(html_root.find('body')) != 0:
body = html_tree.find('body')
tree_str = etree.tostring(body, pretty_print=True, encoding='utf-8', xml_declaration=False)
# this is so stupid
if tree_str.startswith(six.b('<body>')):
n = tree_str.rindex(six.b('</body>'))
return tree_str[6:n]
return tree_str
return ''
def get_content(self, default=None):
"""
Returns content for this document as HTML string. Content will be of type 'str' (Python 2)
or 'bytes' (Python 3).
:Args:
- default: Default value for the content if it is not defined.
:Returns:
Returns content of this document.
"""
tree = parse_string(self.book.get_template(self._template_name))
tree_root = tree.getroot()
tree_root.set('lang', self.lang or self.book.language)
tree_root.attrib['{%s}lang' % NAMESPACES['XML']] = self.lang or self.book.language
# add to the head also
# <meta charset="utf-8" />
try:
html_tree = parse_html_string(self.content)
except:
return ''
html_root = html_tree.getroottree()
# create and populate head
_head = etree.SubElement(tree_root, 'head')
if self.title != '':
_title = etree.SubElement(_head, 'title')
_title.text = self.title
for lnk in self.links:
if lnk.get('type') == 'text/javascript':
_lnk = etree.SubElement(_head, 'script', lnk)
# force <script></script>
_lnk.text = ''
else:
_lnk = etree.SubElement(_head, 'link', lnk)
# this should not be like this
# head = html_root.find('head')
# if head is not None:
# for i in head.getchildren():
# if i.tag == 'title' and self.title != '':
# continue
# _head.append(i)
# create and populate body
_body = etree.SubElement(tree_root, 'body')
if self.direction:
_body.set('dir', self.direction)
tree_root.set('dir', self.direction)
body = html_tree.find('body')
if body is not None:
for i in body.getchildren():
_body.append(i)
tree_str = etree.tostring(tree, pretty_print=True, encoding='utf-8', xml_declaration=True)
return tree_str
def __str__(self):
return '<EpubHtml:%s:%s>' % (self.id, self.file_name)
class EpubCoverHtml(EpubHtml):
"""
Represents Cover page in the EPUB file.
"""
def __init__(self, uid='cover', file_name='cover.xhtml', image_name='', title='Cover'):
super(EpubCoverHtml, self).__init__(uid=uid, file_name=file_name, title=title)
self.image_name = image_name
self.is_linear = False
def is_chapter(self):
"""
Returns if this document is chapter or not.
:Returns:
Returns book value.
"""
return False
def get_content(self):
"""
Returns content for cover page as HTML string. Content will be of type 'str' (Python 2) or 'bytes' (Python 3).
:Returns:
Returns content of this document.
"""
self.content = self.book.get_template('cover')
tree = parse_string(super(EpubCoverHtml, self).get_content())
tree_root = tree.getroot()
images = tree_root.xpath('//xhtml:img', namespaces={'xhtml': NAMESPACES['XHTML']})
images[0].set('src', self.image_name)
images[0].set('alt', self.title)
tree_str = etree.tostring(tree, pretty_print=True, encoding='utf-8', xml_declaration=True)
return tree_str
def __str__(self):
return '<EpubCoverHtml:%s:%s>' % (self.id, self.file_name)
class EpubNav(EpubHtml):
"""
Represents Navigation Document in the EPUB file.
"""
def __init__(self, uid='nav', file_name='nav.xhtml', media_type='application/xhtml+xml'):
super(EpubNav, self).__init__(uid=uid, file_name=file_name, media_type=media_type)
def is_chapter(self):
"""
Returns if this document is chapter or not.
:Returns:
Returns book value.
"""
return False
def __str__(self):
return '<EpubNav:%s:%s>' % (self.id, self.file_name)
class EpubImage(EpubItem):
"""
Represents Image in the EPUB file.
"""
def __init__(self):
super(EpubImage, self).__init__()
def get_type(self):
return ebooklib.ITEM_IMAGE
def __str__(self):
return '<EpubImage:%s:%s>' % (self.id, self.file_name)
class EpubSMIL(EpubItem):
def __init__(self, uid=None, file_name='', content=None):
super(EpubSMIL, self).__init__(uid=uid, file_name=file_name, media_type='application/smil+xml', content=content)
def get_type(self):
return ebooklib.ITEM_SMIL
def __str__(self):
return '<EpubSMIL:%s:%s>' % (self.id, self.file_name)
# EpubBook
class EpubBook(object):
def __init__(self):
self.EPUB_VERSION = None
self.reset()
# we should have options here
def reset(self):
"Initialises all needed variables to default values"
self.metadata = {}
self.items = []
self.spine = []
self.guide = []
self.pages = []
self.toc = []
self.bindings = []
self.IDENTIFIER_ID = 'id'
self.FOLDER_NAME = 'EPUB'
self._id_html = 0
self._id_image = 0
self._id_static = 0
self.title = ''
self.language = 'en'
self.direction = None
self.templates = {
'ncx': NCX_XML,
'nav': NAV_XML,
'chapter': CHAPTER_XML,
'cover': COVER_XML
}
self.add_metadata('OPF', 'generator', '', {
'name': 'generator', 'content': 'Ebook-lib %s' % '.'.join([str(s) for s in VERSION])
})
# default to using a randomly-unique identifier if one is not specified manually
self.set_identifier(str(uuid.uuid4()))
# custom prefixes and namespaces to be set to the content.opf doc
self.prefixes = []
self.namespaces = {}
def set_identifier(self, uid):
"""
Sets unique id for this epub
:Args:
- uid: Value of unique identifier for this book
"""
self.uid = uid
self.set_unique_metadata('DC', 'identifier', self.uid, {'id': self.IDENTIFIER_ID})
def set_title(self, title):
"""
Set title. You can set multiple titles.
:Args:
- title: Title value
"""
self.title = title
self.add_metadata('DC', 'title', self.title)
def set_language(self, lang):
"""
Set language for this epub. You can set multiple languages. Specific items in the book can have
different language settings.
:Args:
- lang: Language code
"""
self.language = lang
self.add_metadata('DC', 'language', lang)
def set_direction(self, direction):
"""
:Args:
- direction: Options are "ltr", "rtl" and "default"
"""
self.direction = direction
def set_cover(self, file_name, content, create_page=True):
"""
Set cover and create cover document if needed.
:Args:
- file_name: file name of the cover page
- content: Content for the cover image
- create_page: Should cover page be defined. Defined as bool value (optional). Default value is True.
"""
# as it is now, it can only be called once
c0 = EpubCover(file_name=file_name)
c0.content = content
self.add_item(c0)
if create_page:
c1 = EpubCoverHtml(image_name=file_name)
self.add_item(c1)
self.add_metadata(None, 'meta', '', OrderedDict([('name', 'cover'), ('content', 'cover-img')]))
def add_author(self, author, file_as=None, role=None, uid='creator'):
"Add author for this document"
self.add_metadata('DC', 'creator', author, {'id': uid})
if file_as:
self.add_metadata(None, 'meta', file_as, {'refines': '#' + uid,
'property': 'file-as',
'scheme': 'marc:relators'})
if role:
self.add_metadata(None, 'meta', role, {'refines': '#' + uid,
'property': 'role',
'scheme': 'marc:relators'})
def add_metadata(self, namespace, name, value, others=None):
"Add metadata"
if namespace in NAMESPACES:
namespace = NAMESPACES[namespace]
if namespace not in self.metadata:
self.metadata[namespace] = {}
if name not in self.metadata[namespace]:
self.metadata[namespace][name] = []
self.metadata[namespace][name].append((value, others))
def get_metadata(self, namespace, name):
"Retrieve metadata"
if namespace in NAMESPACES:
namespace = NAMESPACES[namespace]
return self.metadata[namespace].get(name, [])
def set_unique_metadata(self, namespace, name, value, others=None):
"Add metadata if metadata with this identifier does not already exist, otherwise update existing metadata."
if namespace in NAMESPACES:
namespace = NAMESPACES[namespace]
if namespace in self.metadata and name in self.metadata[namespace]:
self.metadata[namespace][name] = [(value, others)]
else:
self.add_metadata(namespace, name, value, others)
def add_item(self, item):
"""
Add additional item to the book. If not defined, media type and chapter id will be defined
for the item.
:Args:
- item: Item instance
"""
if item.media_type == '':
(has_guessed, media_type) = guess_type(item.get_name().lower())
if has_guessed:
if media_type is not None:
item.media_type = media_type
else:
item.media_type = has_guessed
else:
item.media_type = 'application/octet-stream'
if not item.get_id():
# make chapter_, image_ and static_ configurable
if isinstance(item, EpubHtml):
item.id = 'chapter_%d' % self._id_html
self._id_html += 1
# If there's a page list, append it to the book's page list
self.pages += item.pages
elif isinstance(item, EpubImage):
item.id = 'image_%d' % self._id_image
self._id_image += 1
else:
item.id = 'static_%d' % self._id_image
self._id_image += 1
item.book = self
self.items.append(item)
return item
def get_item_with_id(self, uid):
"""
Returns item for defined UID.
>>> book.get_item_with_id('image_001')
:Args:
- uid: UID for the item
:Returns:
Returns item object. Returns None if nothing was found.
"""
for item in self.get_items():
if item.id == uid:
return item
return None
def get_item_with_href(self, href):
"""
Returns item for defined HREF.
>>> book.get_item_with_href('EPUB/document.xhtml')
:Args:
- href: HREF for the item we are searching for
:Returns:
Returns item object. Returns None if nothing was found.
"""
for item in self.get_items():
if item.get_name() == href:
return item
return None
def get_items(self):
"""
Returns all items attached to this book.
:Returns:
Returns all items as tuple.
"""
return (item for item in self.items)
def get_items_of_type(self, item_type):
"""
Returns all items of specified type.
>>> book.get_items_of_type(epub.ITEM_IMAGE)
:Args:
- item_type: Type for items we are searching for
:Returns:
Returns found items as tuple.
"""
return (item for item in self.items if item.get_type() == item_type)
def get_items_of_media_type(self, media_type):
"""
Returns all items of specified media type.
:Args:
- media_type: Media type for items we are searching for
:Returns:
Returns found items as tuple.
"""
return (item for item in self.items if item.media_type == media_type)
def set_template(self, name, value):
"""
Defines templates which are used to generate certain types of pages. When defining new value for the template
we have to use content of type 'str' (Python 2) or 'bytes' (Python 3).
At the moment we use these templates:
- ncx
- nav
- chapter
- cover
:Args:
- name: Name for the template
- value: Content for the template
"""
self.templates[name] = value
def get_template(self, name):
"""
Returns value for the template.
:Args:
- name: template name
:Returns:
Value of the template.
"""
return self.templates.get(name)
def add_prefix(self, name, uri):
"""
Appends custom prefix to be added to the content.opf document
>>> epub_book.add_prefix('bkterms', 'http://booktype.org/')
:Args:
- name: namespave name
- uri: URI for the namespace
"""
self.prefixes.append('%s: %s' % (name, uri))
class EpubWriter(object):
DEFAULT_OPTIONS = {
'epub2_guide': True,
'epub3_landmark': True,
'epub3_pages': True,
'landmark_title': 'Guide',
'pages_title': 'Pages',
'spine_direction': True,
'package_direction': False,
'play_order': {
'enabled': False,
'start_from': 1
}
}
def __init__(self, name, book, options=None):
self.file_name = name
self.book = book
self.options = dict(self.DEFAULT_OPTIONS)
if options:
self.options.update(options)
self._init_play_order()
def _init_play_order(self):
self._play_order = {
'enabled': False,
'start_from': 1
}
try:
self._play_order['enabled'] = self.options['play_order']['enabled']
self._play_order['start_from'] = self.options['play_order']['start_from']
except KeyError:
pass
def process(self):
# should cache this html parsing so we don't do it for every plugin
for plg in self.options.get('plugins', []):
if hasattr(plg, 'before_write'):
plg.before_write(self.book)
for item in self.book.get_items():
if isinstance(item, EpubHtml):
for plg in self.options.get('plugins', []):
if hasattr(plg, 'html_before_write'):
plg.html_before_write(self.book, item)
def _write_container(self):
container_xml = CONTAINER_XML % {'folder_name': self.book.FOLDER_NAME}
self.out.writestr(CONTAINER_PATH, container_xml)
def _write_opf_metadata(self, root):
# This is really not needed
# problem is uppercase/lowercase
# for ns_name, values in six.iteritems(self.book.metadata):
# if ns_name:
# for n_id, ns_url in six.iteritems(NAMESPACES):
# if ns_name == ns_url:
# nsmap[n_id.lower()] = NAMESPACES[n_id]
nsmap = {'dc': NAMESPACES['DC'], 'opf': NAMESPACES['OPF']}
nsmap.update(self.book.namespaces)
metadata = etree.SubElement(root, 'metadata', nsmap=nsmap)
el = etree.SubElement(metadata, 'meta', {'property': 'dcterms:modified'})
if 'mtime' in self.options:
mtime = self.options['mtime']
else:
import datetime
mtime = datetime.datetime.now()
el.text = mtime.strftime('%Y-%m-%dT%H:%M:%SZ')
for ns_name, values in six.iteritems(self.book.metadata):
if ns_name == NAMESPACES['OPF']:
for values in values.values():
for v in values:
if 'property' in v[1] and v[1]['property'] == 'dcterms:modified':
continue
try:
el = etree.SubElement(metadata, 'meta', v[1])
if v[0]:
el.text = v[0]
except ValueError:
logging.error('Could not create metadata.')
else:
for name, values in six.iteritems(values):
for v in values:
try:
if ns_name:
el = etree.SubElement(metadata, '{%s}%s' % (ns_name, name), v[1])
else:
el = etree.SubElement(metadata, '%s' % name, v[1])
el.text = v[0]
except ValueError:
logging.error('Could not create metadata "{}".'.format(name))
def _write_opf_manifest(self, root):
manifest = etree.SubElement(root, 'manifest')
_ncx_id = None
# mathml, scripted, svg, remote-resources, and switch
# nav
# cover-image
for item in self.book.get_items():
if not item.manifest:
continue
if isinstance(item, EpubNav):
etree.SubElement(manifest, 'item', {'href': item.get_name(),
'id': item.id,
'media-type': item.media_type,
'properties': 'nav'})
elif isinstance(item, EpubNcx):
_ncx_id = item.id
etree.SubElement(manifest, 'item', {'href': item.file_name,
'id': item.id,
'media-type': item.media_type})
elif isinstance(item, EpubCover):
etree.SubElement(manifest, 'item', {'href': item.file_name,
'id': item.id,
'media-type': item.media_type,
'properties': 'cover-image'})
else:
opts = {'href': item.file_name,
'id': item.id,
'media-type': item.media_type}
if hasattr(item, 'properties') and len(item.properties) > 0:
opts['properties'] = ' '.join(item.properties)
if hasattr(item, 'media_overlay') and item.media_overlay is not None:
opts['media-overlay'] = item.media_overlay
if hasattr(item, 'media_duration') and item.media_duration is not None:
opts['duration'] = item.media_duration
etree.SubElement(manifest, 'item', opts)
return _ncx_id
def _write_opf_spine(self, root, ncx_id):
spine_attributes = {'toc': ncx_id or 'ncx'}
if self.book.direction and self.options['spine_direction']:
spine_attributes['page-progression-direction'] = self.book.direction
spine = etree.SubElement(root, 'spine', spine_attributes)
for _item in self.book.spine:
# this is for now
# later we should be able to fetch things from tuple
is_linear = True
if isinstance(_item, tuple):
item = _item[0]
if len(_item) > 1:
if _item[1] == 'no':
is_linear = False
else:
item = _item
if isinstance(item, EpubHtml):
opts = {'idref': item.get_id()}
if not item.is_linear or not is_linear:
opts['linear'] = 'no'
elif isinstance(item, EpubItem):
opts = {'idref': item.get_id()}
if not item.is_linear or not is_linear:
opts['linear'] = 'no'
else:
opts = {'idref': item}
try:
itm = self.book.get_item_with_id(item)
if not itm.is_linear or not is_linear:
opts['linear'] = 'no'
except:
pass
etree.SubElement(spine, 'itemref', opts)
def _write_opf_guide(self, root):
# - http://www.idpf.org/epub/20/spec/OPF_2.0.1_draft.htm#Section2.6
if len(self.book.guide) > 0 and self.options.get('epub2_guide'):
guide = etree.SubElement(root, 'guide', {})
for item in self.book.guide:
if 'item' in item:
chap = item.get('item')
if chap:
_href = chap.file_name
_title = chap.title
else:
_href = item.get('href', '')
_title = item.get('title', '')
if _title is None:
_title = ''
ref = etree.SubElement(guide, 'reference', {'type': item.get('type', ''),
'title': _title,
'href': _href})
def _write_opf_bindings(self, root):
if len(self.book.bindings) > 0:
bindings = etree.SubElement(root, 'bindings', {})
for item in self.book.bindings:
etree.SubElement(bindings, 'mediaType', item)
def _write_opf_file(self, root):
tree_str = etree.tostring(root, pretty_print=True, encoding='utf-8', xml_declaration=True)
self.out.writestr('%s/content.opf' % self.book.FOLDER_NAME, tree_str)
def _write_opf(self):
package_attributes = {'xmlns': NAMESPACES['OPF'],
'unique-identifier': self.book.IDENTIFIER_ID,
'version': '3.0'}
if self.book.direction and self.options['package_direction']:
package_attributes['dir'] = self.book.direction
root = etree.Element('package', package_attributes)
prefixes = ['rendition: http://www.idpf.org/vocab/rendition/#'] + self.book.prefixes
root.attrib['prefix'] = ' '.join(prefixes)
# METADATA
self._write_opf_metadata(root)
# MANIFEST
_ncx_id = self._write_opf_manifest(root)
# SPINE
self._write_opf_spine(root, _ncx_id)
# GUIDE
self._write_opf_guide(root)
# BINDINGS
self._write_opf_bindings(root)
# WRITE FILE
self._write_opf_file(root)
def _get_nav(self, item):
# just a basic navigation for now
nav_xml = parse_string(self.book.get_template('nav'))
root = nav_xml.getroot()
root.set('lang', self.book.language)
root.attrib['{%s}lang' % NAMESPACES['XML']] = self.book.language
nav_dir_name = os.path.dirname(item.file_name)
head = etree.SubElement(root, 'head')
title = etree.SubElement(head, 'title')
title.text = self.book.title
# for now this just handles css files and ignores others
for _link in item.links:
_lnk = etree.SubElement(head, 'link', {
'href': _link.get('href', ''), 'rel': 'stylesheet', 'type': 'text/css'
})
body = etree.SubElement(root, 'body')
nav = etree.SubElement(body, 'nav', {
'{%s}type' % NAMESPACES['EPUB']: 'toc',
'id': 'id',
'role': 'doc-toc',
})
content_title = etree.SubElement(nav, 'h2')
content_title.text = self.book.title
def _create_section(itm, items):
ol = etree.SubElement(itm, 'ol')
for item in items:
if isinstance(item, tuple) or isinstance(item, list):
li = etree.SubElement(ol, 'li')
if isinstance(item[0], EpubHtml):
a = etree.SubElement(li, 'a', {'href': os.path.relpath(item[0].file_name, nav_dir_name)})
elif isinstance(item[0], Section) and item[0].href != '':
a = etree.SubElement(li, 'a', {'href': os.path.relpath(item[0].href, nav_dir_name)})
elif isinstance(item[0], Link):
a = etree.SubElement(li, 'a', {'href': os.path.relpath(item[0].href, nav_dir_name)})
else:
a = etree.SubElement(li, 'span')
a.text = item[0].title
_create_section(li, item[1])
elif isinstance(item, Link):
li = etree.SubElement(ol, 'li')
a = etree.SubElement(li, 'a', {'href': os.path.relpath(item.href, nav_dir_name)})
a.text = item.title
elif isinstance(item, EpubHtml):
li = etree.SubElement(ol, 'li')
a = etree.SubElement(li, 'a', {'href': os.path.relpath(item.file_name, nav_dir_name)})
a.text = item.title
_create_section(nav, self.book.toc)
# LANDMARKS / GUIDE
# - http://www.idpf.org/epub/30/spec/epub30-contentdocs.html#sec-xhtml-nav-def-types-landmarks
if len(self.book.guide) > 0 and self.options.get('epub3_landmark'):
# Epub2 guide types do not map completely to epub3 landmark types.
guide_to_landscape_map = {
'notes': 'rearnotes',
'text': 'bodymatter'
}
guide_nav = etree.SubElement(body, 'nav', {'{%s}type' % NAMESPACES['EPUB']: 'landmarks'})
guide_content_title = etree.SubElement(guide_nav, 'h2')
guide_content_title.text = self.options.get('landmark_title', 'Guide')
guild_ol = etree.SubElement(guide_nav, 'ol')
for elem in self.book.guide:
li_item = etree.SubElement(guild_ol, 'li')
if 'item' in elem:
chap = elem.get('item', None)
if chap:
_href = chap.file_name
_title = chap.title
else:
_href = elem.get('href', '')
_title = elem.get('title', '')
guide_type = elem.get('type', '')
a_item = etree.SubElement(li_item, 'a', {
'{%s}type' % NAMESPACES['EPUB']: guide_to_landscape_map.get(guide_type, guide_type),
'href': os.path.relpath(_href, nav_dir_name)
})
a_item.text = _title
# PAGE-LIST
if self.options.get('epub3_pages'):
inserted_pages = get_pages_for_items([item for item in self.book.get_items_of_type(ebooklib.ITEM_DOCUMENT) \
if not isinstance(item, EpubNav)])
if len(inserted_pages) > 0:
pagelist_nav = etree.SubElement(
body,
'nav',
{
'{%s}type' % NAMESPACES['EPUB']: 'page-list',
'id': 'pages',
'hidden': 'hidden',
}
)
pagelist_content_title = etree.SubElement(pagelist_nav, 'h2')
pagelist_content_title.text = self.options.get(
'pages_title', 'Pages'
)
pages_ol = etree.SubElement(pagelist_nav, 'ol')
for filename, pageref, label in inserted_pages:
li_item = etree.SubElement(pages_ol, 'li')
_href = u'{}#{}'.format(filename, pageref)
_title = label
a_item = etree.SubElement(li_item, 'a', {
'href': os.path.relpath(_href, nav_dir_name),
})
a_item.text = _title
tree_str = etree.tostring(nav_xml, pretty_print=True, encoding='utf-8', xml_declaration=True)
return tree_str
def _get_ncx(self):
# we should be able to setup language for NCX as also
ncx = parse_string(self.book.get_template('ncx'))
root = ncx.getroot()
head = etree.SubElement(root, 'head')
# get this id
uid = etree.SubElement(head, 'meta', {'content': self.book.uid, 'name': 'dtb:uid'})
uid = etree.SubElement(head, 'meta', {'content': '0', 'name': 'dtb:depth'})
uid = etree.SubElement(head, 'meta', {'content': '0', 'name': 'dtb:totalPageCount'})
uid = etree.SubElement(head, 'meta', {'content': '0', 'name': 'dtb:maxPageNumber'})
doc_title = etree.SubElement(root, 'docTitle')
title = etree.SubElement(doc_title, 'text')
title.text = self.book.title
# doc_author = etree.SubElement(root, 'docAuthor')
# author = etree.SubElement(doc_author, 'text')
# author.text = 'Name of the person'
# For now just make a very simple navMap
nav_map = etree.SubElement(root, 'navMap')
def _add_play_order(nav_point):
nav_point.set('playOrder', str(self._play_order['start_from']))
self._play_order['start_from'] += 1
def _create_section(itm, items, uid):
for item in items:
if isinstance(item, tuple) or isinstance(item, list):
section, subsection = item[0], item[1]
np = etree.SubElement(itm, 'navPoint', {
'id': section.get_id() if isinstance(section, EpubHtml) else 'sep_%d' % uid
})
if self._play_order['enabled']:
_add_play_order(np)
nl = etree.SubElement(np, 'navLabel')
nt = etree.SubElement(nl, 'text')
nt.text = section.title
# CAN NOT HAVE EMPTY SRC HERE
href = ''
if isinstance(section, EpubHtml):
href = section.file_name
elif isinstance(section, Section) and section.href != '':
href = section.href
elif isinstance(section, Link):
href = section.href
nc = etree.SubElement(np, 'content', {'src': href})
uid = _create_section(np, subsection, uid + 1)
elif isinstance(item, Link):
_parent = itm
_content = _parent.find('content')
if _content is not None:
if _content.get('src') == '':
_content.set('src', item.href)
np = etree.SubElement(itm, 'navPoint', {'id': item.uid})
if self._play_order['enabled']:
_add_play_order(np)
nl = etree.SubElement(np, 'navLabel')
nt = etree.SubElement(nl, 'text')
nt.text = item.title
nc = etree.SubElement(np, 'content', {'src': item.href})
elif isinstance(item, EpubHtml):
_parent = itm
_content = _parent.find('content')
if _content is not None:
if _content.get('src') == '':
_content.set('src', item.file_name)
np = etree.SubElement(itm, 'navPoint', {'id': item.get_id()})
if self._play_order['enabled']:
_add_play_order(np)
nl = etree.SubElement(np, 'navLabel')
nt = etree.SubElement(nl, 'text')
nt.text = item.title
nc = etree.SubElement(np, 'content', {'src': item.file_name})
return uid
_create_section(nav_map, self.book.toc, 0)
tree_str = etree.tostring(root, pretty_print=True, encoding='utf-8', xml_declaration=True)
return tree_str
def _write_items(self):
for item in self.book.get_items():
if isinstance(item, EpubNcx):
self.out.writestr('%s/%s' % (self.book.FOLDER_NAME, item.file_name), self._get_ncx())
elif isinstance(item, EpubNav):
self.out.writestr('%s/%s' % (self.book.FOLDER_NAME, item.file_name), self._get_nav(item))
elif item.manifest:
self.out.writestr('%s/%s' % (self.book.FOLDER_NAME, item.file_name), item.get_content())
else:
self.out.writestr('%s' % item.file_name, item.get_content())
def write(self):
# check for the option allowZip64
self.out = zipfile.ZipFile(self.file_name, 'w', zipfile.ZIP_DEFLATED)
self.out.writestr('mimetype', 'application/epub+zip', compress_type=zipfile.ZIP_STORED)
self._write_container()
self._write_opf()
self._write_items()
self.out.close()
class EpubReader(object):
DEFAULT_OPTIONS = {}
def __init__(self, epub_file_name, options=None):
self.file_name = epub_file_name
self.book = EpubBook()
self.zf = None
self.opf_file = ''
self.opf_dir = ''
self.options = dict(self.DEFAULT_OPTIONS)
if options:
self.options.update(options)
def process(self):
# should cache this html parsing so we don't do it for every plugin
for plg in self.options.get('plugins', []):
if hasattr(plg, 'after_read'):
plg.after_read(self.book)
for item in self.book.get_items():
if isinstance(item, EpubHtml):
for plg in self.options.get('plugins', []):
if hasattr(plg, 'html_after_read'):
plg.html_after_read(self.book, item)
def load(self):
self._load()
return self.book
def read_file(self, name):
# Raises KeyError
name = zip_path.normpath(name)
return self.zf.read(name)
def _load_container(self):
meta_inf = self.read_file('META-INF/container.xml')
tree = parse_string(meta_inf)
for root_file in tree.findall('//xmlns:rootfile[@media-type]', namespaces={'xmlns': NAMESPACES['CONTAINERNS']}):
if root_file.get('media-type') == 'application/oebps-package+xml':
self.opf_file = root_file.get('full-path')
self.opf_dir = zip_path.dirname(self.opf_file)
def _load_metadata(self):
container_root = self.container.getroot()
# get epub version
self.book.version = container_root.get('version', None)
# get unique-identifier
if container_root.get('unique-identifier', None):
self.book.IDENTIFIER_ID = container_root.get('unique-identifier')
# get xml:lang
# get metadata
metadata = self.container.find('{%s}%s' % (NAMESPACES['OPF'], 'metadata'))
nsmap = metadata.nsmap
nstags = dict((k, '{%s}' % v) for k, v in six.iteritems(nsmap))
default_ns = nstags.get(None, '')
nsdict = dict((v, {}) for v in nsmap.values())
def add_item(ns, tag, value, extra):
if ns not in nsdict:
nsdict[ns] = {}
values = nsdict[ns].setdefault(tag, [])
values.append((value, extra))
for t in metadata:
if not etree.iselement(t) or t.tag is etree.Comment:
continue
if t.tag == default_ns + 'meta':
name = t.get('name')
others = dict((k, v) for k, v in t.items())
if name and ':' in name:
prefix, name = name.split(':', 1)
else:
prefix = None
add_item(t.nsmap.get(prefix, prefix), name, t.text, others)
else:
tag = t.tag[t.tag.rfind('}') + 1:]
if (t.prefix and t.prefix.lower() == 'dc') and tag == 'identifier':
_id = t.get('id', None)
if _id:
self.book.IDENTIFIER_ID = _id
others = dict((k, v) for k, v in t.items())
add_item(t.nsmap[t.prefix], tag, t.text, others)
self.book.metadata = nsdict
titles = self.book.get_metadata('DC', 'title')
if len(titles) > 0:
self.book.title = titles[0][0]
for value, others in self.book.get_metadata('DC', 'identifier'):
if others.get('id') == self.book.IDENTIFIER_ID:
self.book.uid = value
def _load_manifest(self):
for r in self.container.find('{%s}%s' % (NAMESPACES['OPF'], 'manifest')):
if r is not None and r.tag != '{%s}item' % NAMESPACES['OPF']:
continue
media_type = r.get('media-type')
_properties = r.get('properties', '')
if _properties:
properties = _properties.split(' ')
else:
properties = []
# people use wrong content types
if media_type == 'image/jpg':
media_type = 'image/jpeg'
if media_type == 'application/x-dtbncx+xml':
ei = EpubNcx(uid=r.get('id'), file_name=unquote(r.get('href')))
ei.content = self.read_file(zip_path.join(self.opf_dir, ei.file_name))
if media_type == 'application/smil+xml':
ei = EpubSMIL(uid=r.get('id'), file_name=unquote(r.get('href')))
ei.content = self.read_file(zip_path.join(self.opf_dir, ei.file_name))
elif media_type == 'application/xhtml+xml':
if 'nav' in properties:
ei = EpubNav(uid=r.get('id'), file_name=unquote(r.get('href')))
ei.content = self.read_file(zip_path.join(self.opf_dir, r.get('href')))
elif 'cover' in properties:
ei = EpubCoverHtml()
ei.content = self.read_file(zip_path.join(self.opf_dir, unquote(r.get('href'))))
else:
ei = EpubHtml()
ei.id = r.get('id')
ei.file_name = unquote(r.get('href'))
ei.media_type = media_type
ei.media_overlay = r.get('media-overlay', None)
ei.media_duration = r.get('duration', None)
ei.content = self.read_file(zip_path.join(self.opf_dir, ei.get_name()))
ei.properties = properties
elif media_type in IMAGE_MEDIA_TYPES:
if 'cover-image' in properties:
ei = EpubCover(uid=r.get('id'), file_name=unquote(r.get('href')))
ei.media_type = media_type
ei.content = self.read_file(zip_path.join(self.opf_dir, ei.get_name()))
else:
ei = EpubImage()
ei.id = r.get('id')
ei.file_name = unquote(r.get('href'))
ei.media_type = media_type
ei.content = self.read_file(zip_path.join(self.opf_dir, ei.get_name()))
else:
# different types
ei = EpubItem()
ei.id = r.get('id')
ei.file_name = unquote(r.get('href'))
ei.media_type = media_type
ei.content = self.read_file(zip_path.join(self.opf_dir, ei.get_name()))
self.book.add_item(ei)
def _parse_ncx(self, data):
tree = parse_string(data)
tree_root = tree.getroot()
nav_map = tree_root.find('{%s}navMap' % NAMESPACES['DAISY'])
def _get_children(elems, n, nid):
label, content = '', ''
children = []
for a in elems.getchildren():
if a.tag == '{%s}navLabel' % NAMESPACES['DAISY']:
label = a.getchildren()[0].text
if a.tag == '{%s}content' % NAMESPACES['DAISY']:
content = a.get('src', '')
if a.tag == '{%s}navPoint' % NAMESPACES['DAISY']:
children.append(_get_children(a, n + 1, a.get('id', '')))
if len(children) > 0:
if n == 0:
return children
return (Section(label, href=content),
children)
else:
return Link(content, label, nid)
self.book.toc = _get_children(nav_map, 0, '')
def _parse_nav(self, data, base_path, navtype='toc'):
html_node = parse_html_string(data)
if navtype == 'toc':
# parsing the table of contents
nav_node = html_node.xpath("//nav[@*='toc']")[0]
else:
# parsing the list of pages
_page_list = html_node.xpath("//nav[@*='page-list']")
if len(_page_list) == 0:
return
nav_node = _page_list[0]
def parse_list(list_node):
items = []
for item_node in list_node.findall('li'):
sublist_node = item_node.find('ol')
link_node = item_node.find('a')
if sublist_node is not None:
title = item_node[0].text
children = parse_list(sublist_node)
if link_node is not None:
href = zip_path.normpath(zip_path.join(base_path, link_node.get('href')))
items.append((Section(title, href=href), children))
else:
items.append((Section(title), children))
elif link_node is not None:
title = link_node.text
href = zip_path.normpath(zip_path.join(base_path, link_node.get('href')))
items.append(Link(href, title))
return items
if navtype == 'toc':
self.book.toc = parse_list(nav_node.find('ol'))
elif nav_node is not None:
# generate the pages list if there is one
self.book.pages = parse_list(nav_node.find('ol'))
# generate the per-file pages lists
# because of the order of parsing the files, this can't be done
# when building the EpubHtml objects
htmlfiles = dict()
for htmlfile in self.book.items:
if isinstance(htmlfile, EpubHtml):
htmlfiles[htmlfile.file_name] = htmlfile
for page in self.book.pages:
try:
(filename, idref) = page.href.split('#')
except ValueError:
filename = page.href
if filename in htmlfiles:
htmlfiles[filename].pages.append(page)
def _load_spine(self):
spine = self.container.find('{%s}%s' % (NAMESPACES['OPF'], 'spine'))
self.book.spine = [(t.get('idref'), t.get('linear', 'yes')) for t in spine]
toc = spine.get('toc', '')
self.book.set_direction(spine.get('page-progression-direction', None))
# should read ncx or nav file
if toc:
try:
ncxFile = self.read_file(zip_path.join(self.opf_dir, self.book.get_item_with_id(toc).get_name()))
except KeyError:
raise EpubException(-1, 'Can not find ncx file.')
self._parse_ncx(ncxFile)
def _load_guide(self):
guide = self.container.find('{%s}%s' % (NAMESPACES['OPF'], 'guide'))
if guide is not None:
self.book.guide = [{'href': t.get('href'), 'title': t.get('title'), 'type': t.get('type')} for t in guide]
def _load_opf_file(self):
try:
s = self.read_file(self.opf_file)
except KeyError:
raise EpubException(-1, 'Can not find container file')
self.container = parse_string(s)
self._load_metadata()
self._load_manifest()
self._load_spine()
self._load_guide()
# read nav file if found
#
nav_item = next((item for item in self.book.items if isinstance(item, EpubNav)), None)
if nav_item:
if not self.book.toc:
self._parse_nav(
nav_item.content,
zip_path.dirname(nav_item.file_name),
navtype='toc'
)
self._parse_nav(
nav_item.content,
zip_path.dirname(nav_item.file_name),
navtype='pages'
)
def _load(self):
try:
self.zf = zipfile.ZipFile(self.file_name, 'r', compression=zipfile.ZIP_DEFLATED, allowZip64=True)
except zipfile.BadZipfile as bz:
raise EpubException(0, 'Bad Zip file')
except zipfile.LargeZipFile as bz:
raise EpubException(1, 'Large Zip file')
# 1st check metadata
self._load_container()
self._load_opf_file()
self.zf.close()
# WRITE
def write_epub(name, book, options=None):
"""
Creates epub file with the content defined in EpubBook.
>>> ebooklib.write_epub('book.epub', book)
:Args:
- name: file name for the output file
- book: instance of EpubBook
- options: extra opions as dictionary (optional)
"""
epub = EpubWriter(name, book, options)
epub.process()
try:
epub.write()
except IOError:
pass
# READ
|
aerkalov/ebooklib | ebooklib/epub.py | EpubItem.get_type | python | def get_type(self):
_, ext = zip_path.splitext(self.get_name())
ext = ext.lower()
for uid, ext_list in six.iteritems(ebooklib.EXTENSIONS):
if ext in ext_list:
return uid
return ebooklib.ITEM_UNKNOWN | Guess type according to the file extension. Might not be the best way how to do it, but it works for now.
Items can be of type:
- ITEM_UNKNOWN = 0
- ITEM_IMAGE = 1
- ITEM_STYLE = 2
- ITEM_SCRIPT = 3
- ITEM_NAVIGATION = 4
- ITEM_VECTOR = 5
- ITEM_FONT = 6
- ITEM_VIDEO = 7
- ITEM_AUDIO = 8
- ITEM_DOCUMENT = 9
- ITEM_COVER = 10
We map type according to the extensions which are defined in ebooklib.EXTENSIONS.
:Returns:
Returns type of the item as number. | train | https://github.com/aerkalov/ebooklib/blob/305f2dd7f02923ffabf9586a5d16266113d00c4a/ebooklib/epub.py#L158-L187 | [
"def get_name(self):\n \"\"\"\n Returns name for this item. By default it is always file name but it does not have to be.\n\n :Returns:\n Returns file name for this item.\n \"\"\"\n return self.file_name\n"
] | class EpubItem(object):
"""
Base class for the items in a book.
"""
def __init__(self, uid=None, file_name='', media_type='', content=six.b(''), manifest=True):
"""
:Args:
- uid: Unique identifier for this item (optional)
- file_name: File name for this item (optional)
- media_type: Media type for this item (optional)
- content: Content for this item (optional)
- manifest: Manifest for this item (optional)
"""
self.id = uid
self.file_name = file_name
self.media_type = media_type
self.content = content
self.is_linear = True
self.manifest = manifest
self.book = None
def get_id(self):
"""
Returns unique identifier for this item.
:Returns:
Returns uid number as string.
"""
return self.id
def get_name(self):
"""
Returns name for this item. By default it is always file name but it does not have to be.
:Returns:
Returns file name for this item.
"""
return self.file_name
def get_content(self, default=six.b('')):
"""
Returns content of the item. Content should be of type 'str' (Python 2) or 'bytes' (Python 3)
:Args:
- default: Default value for the content if it is not already defined.
:Returns:
Returns content of the item.
"""
return self.content or default
def set_content(self, content):
"""
Sets content value for this item.
:Args:
- content: Content value
"""
self.content = content
def __str__(self):
return '<EpubItem:%s>' % self.id
|
aerkalov/ebooklib | ebooklib/epub.py | EpubHtml.add_link | python | def add_link(self, **kwgs):
self.links.append(kwgs)
if kwgs.get('type') == 'text/javascript':
if 'scripted' not in self.properties:
self.properties.append('scripted') | Add additional link to the document. Links will be embeded only inside of this document.
>>> add_link(href='styles.css', rel='stylesheet', type='text/css') | train | https://github.com/aerkalov/ebooklib/blob/305f2dd7f02923ffabf9586a5d16266113d00c4a/ebooklib/epub.py#L299-L308 | null | class EpubHtml(EpubItem):
"""
Represents HTML document in the EPUB file.
"""
_template_name = 'chapter'
def __init__(self, uid=None, file_name='', media_type='', content=None, title='',
lang=None, direction=None, media_overlay=None, media_duration=None):
super(EpubHtml, self).__init__(uid, file_name, media_type, content)
self.title = title
self.lang = lang
self.direction = direction
self.media_overlay = media_overlay
self.media_duration = media_duration
self.links = []
self.properties = []
self.pages = []
def is_chapter(self):
"""
Returns if this document is chapter or not.
:Returns:
Returns book value.
"""
return True
def get_type(self):
"""
Always returns ebooklib.ITEM_DOCUMENT as type of this document.
:Returns:
Always returns ebooklib.ITEM_DOCUMENT
"""
return ebooklib.ITEM_DOCUMENT
def set_language(self, lang):
"""
Sets language for this book item. By default it will use language of the book but it
can be overwritten with this call.
"""
self.lang = lang
def get_language(self):
"""
Get language code for this book item. Language of the book item can be different from
the language settings defined globaly for book.
:Returns:
As string returns language code.
"""
return self.lang
def get_links(self):
"""
Returns list of additional links defined for this document.
:Returns:
As tuple return list of links.
"""
return (link for link in self.links)
def get_links_of_type(self, link_type):
"""
Returns list of additional links of specific type.
:Returns:
As tuple returns list of links.
"""
return (link for link in self.links if link.get('type', '') == link_type)
def add_item(self, item):
"""
Add other item to this document. It will create additional links according to the item type.
:Args:
- item: item we want to add defined as instance of EpubItem
"""
if item.get_type() == ebooklib.ITEM_STYLE:
self.add_link(href=item.get_name(), rel='stylesheet', type='text/css')
if item.get_type() == ebooklib.ITEM_SCRIPT:
self.add_link(src=item.get_name(), type='text/javascript')
def get_body_content(self):
"""
Returns content of BODY element for this HTML document. Content will be of type 'str' (Python 2)
or 'bytes' (Python 3).
:Returns:
Returns content of this document.
"""
try:
html_tree = parse_html_string(self.content)
except:
return ''
html_root = html_tree.getroottree()
if len(html_root.find('body')) != 0:
body = html_tree.find('body')
tree_str = etree.tostring(body, pretty_print=True, encoding='utf-8', xml_declaration=False)
# this is so stupid
if tree_str.startswith(six.b('<body>')):
n = tree_str.rindex(six.b('</body>'))
return tree_str[6:n]
return tree_str
return ''
def get_content(self, default=None):
"""
Returns content for this document as HTML string. Content will be of type 'str' (Python 2)
or 'bytes' (Python 3).
:Args:
- default: Default value for the content if it is not defined.
:Returns:
Returns content of this document.
"""
tree = parse_string(self.book.get_template(self._template_name))
tree_root = tree.getroot()
tree_root.set('lang', self.lang or self.book.language)
tree_root.attrib['{%s}lang' % NAMESPACES['XML']] = self.lang or self.book.language
# add to the head also
# <meta charset="utf-8" />
try:
html_tree = parse_html_string(self.content)
except:
return ''
html_root = html_tree.getroottree()
# create and populate head
_head = etree.SubElement(tree_root, 'head')
if self.title != '':
_title = etree.SubElement(_head, 'title')
_title.text = self.title
for lnk in self.links:
if lnk.get('type') == 'text/javascript':
_lnk = etree.SubElement(_head, 'script', lnk)
# force <script></script>
_lnk.text = ''
else:
_lnk = etree.SubElement(_head, 'link', lnk)
# this should not be like this
# head = html_root.find('head')
# if head is not None:
# for i in head.getchildren():
# if i.tag == 'title' and self.title != '':
# continue
# _head.append(i)
# create and populate body
_body = etree.SubElement(tree_root, 'body')
if self.direction:
_body.set('dir', self.direction)
tree_root.set('dir', self.direction)
body = html_tree.find('body')
if body is not None:
for i in body.getchildren():
_body.append(i)
tree_str = etree.tostring(tree, pretty_print=True, encoding='utf-8', xml_declaration=True)
return tree_str
def __str__(self):
return '<EpubHtml:%s:%s>' % (self.id, self.file_name)
|
aerkalov/ebooklib | ebooklib/epub.py | EpubHtml.get_links_of_type | python | def get_links_of_type(self, link_type):
return (link for link in self.links if link.get('type', '') == link_type) | Returns list of additional links of specific type.
:Returns:
As tuple returns list of links. | train | https://github.com/aerkalov/ebooklib/blob/305f2dd7f02923ffabf9586a5d16266113d00c4a/ebooklib/epub.py#L319-L326 | null | class EpubHtml(EpubItem):
"""
Represents HTML document in the EPUB file.
"""
_template_name = 'chapter'
def __init__(self, uid=None, file_name='', media_type='', content=None, title='',
lang=None, direction=None, media_overlay=None, media_duration=None):
super(EpubHtml, self).__init__(uid, file_name, media_type, content)
self.title = title
self.lang = lang
self.direction = direction
self.media_overlay = media_overlay
self.media_duration = media_duration
self.links = []
self.properties = []
self.pages = []
def is_chapter(self):
"""
Returns if this document is chapter or not.
:Returns:
Returns book value.
"""
return True
def get_type(self):
"""
Always returns ebooklib.ITEM_DOCUMENT as type of this document.
:Returns:
Always returns ebooklib.ITEM_DOCUMENT
"""
return ebooklib.ITEM_DOCUMENT
def set_language(self, lang):
"""
Sets language for this book item. By default it will use language of the book but it
can be overwritten with this call.
"""
self.lang = lang
def get_language(self):
"""
Get language code for this book item. Language of the book item can be different from
the language settings defined globaly for book.
:Returns:
As string returns language code.
"""
return self.lang
def add_link(self, **kwgs):
"""
Add additional link to the document. Links will be embeded only inside of this document.
>>> add_link(href='styles.css', rel='stylesheet', type='text/css')
"""
self.links.append(kwgs)
if kwgs.get('type') == 'text/javascript':
if 'scripted' not in self.properties:
self.properties.append('scripted')
def get_links(self):
"""
Returns list of additional links defined for this document.
:Returns:
As tuple return list of links.
"""
return (link for link in self.links)
def add_item(self, item):
"""
Add other item to this document. It will create additional links according to the item type.
:Args:
- item: item we want to add defined as instance of EpubItem
"""
if item.get_type() == ebooklib.ITEM_STYLE:
self.add_link(href=item.get_name(), rel='stylesheet', type='text/css')
if item.get_type() == ebooklib.ITEM_SCRIPT:
self.add_link(src=item.get_name(), type='text/javascript')
def get_body_content(self):
"""
Returns content of BODY element for this HTML document. Content will be of type 'str' (Python 2)
or 'bytes' (Python 3).
:Returns:
Returns content of this document.
"""
try:
html_tree = parse_html_string(self.content)
except:
return ''
html_root = html_tree.getroottree()
if len(html_root.find('body')) != 0:
body = html_tree.find('body')
tree_str = etree.tostring(body, pretty_print=True, encoding='utf-8', xml_declaration=False)
# this is so stupid
if tree_str.startswith(six.b('<body>')):
n = tree_str.rindex(six.b('</body>'))
return tree_str[6:n]
return tree_str
return ''
def get_content(self, default=None):
"""
Returns content for this document as HTML string. Content will be of type 'str' (Python 2)
or 'bytes' (Python 3).
:Args:
- default: Default value for the content if it is not defined.
:Returns:
Returns content of this document.
"""
tree = parse_string(self.book.get_template(self._template_name))
tree_root = tree.getroot()
tree_root.set('lang', self.lang or self.book.language)
tree_root.attrib['{%s}lang' % NAMESPACES['XML']] = self.lang or self.book.language
# add to the head also
# <meta charset="utf-8" />
try:
html_tree = parse_html_string(self.content)
except:
return ''
html_root = html_tree.getroottree()
# create and populate head
_head = etree.SubElement(tree_root, 'head')
if self.title != '':
_title = etree.SubElement(_head, 'title')
_title.text = self.title
for lnk in self.links:
if lnk.get('type') == 'text/javascript':
_lnk = etree.SubElement(_head, 'script', lnk)
# force <script></script>
_lnk.text = ''
else:
_lnk = etree.SubElement(_head, 'link', lnk)
# this should not be like this
# head = html_root.find('head')
# if head is not None:
# for i in head.getchildren():
# if i.tag == 'title' and self.title != '':
# continue
# _head.append(i)
# create and populate body
_body = etree.SubElement(tree_root, 'body')
if self.direction:
_body.set('dir', self.direction)
tree_root.set('dir', self.direction)
body = html_tree.find('body')
if body is not None:
for i in body.getchildren():
_body.append(i)
tree_str = etree.tostring(tree, pretty_print=True, encoding='utf-8', xml_declaration=True)
return tree_str
def __str__(self):
return '<EpubHtml:%s:%s>' % (self.id, self.file_name)
|
aerkalov/ebooklib | ebooklib/epub.py | EpubHtml.add_item | python | def add_item(self, item):
if item.get_type() == ebooklib.ITEM_STYLE:
self.add_link(href=item.get_name(), rel='stylesheet', type='text/css')
if item.get_type() == ebooklib.ITEM_SCRIPT:
self.add_link(src=item.get_name(), type='text/javascript') | Add other item to this document. It will create additional links according to the item type.
:Args:
- item: item we want to add defined as instance of EpubItem | train | https://github.com/aerkalov/ebooklib/blob/305f2dd7f02923ffabf9586a5d16266113d00c4a/ebooklib/epub.py#L328-L339 | [
"def get_type(self):\n \"\"\"\n Guess type according to the file extension. Might not be the best way how to do it, but it works for now.\n\n Items can be of type:\n - ITEM_UNKNOWN = 0\n - ITEM_IMAGE = 1\n - ITEM_STYLE = 2\n - ITEM_SCRIPT = 3\n - ITEM_NAVIGATION = 4\n - ITEM_VECTOR = 5\n - ITEM_FONT = 6\n - ITEM_VIDEO = 7\n - ITEM_AUDIO = 8\n - ITEM_DOCUMENT = 9\n - ITEM_COVER = 10\n\n We map type according to the extensions which are defined in ebooklib.EXTENSIONS.\n\n :Returns:\n Returns type of the item as number.\n \"\"\"\n _, ext = zip_path.splitext(self.get_name())\n ext = ext.lower()\n\n for uid, ext_list in six.iteritems(ebooklib.EXTENSIONS):\n if ext in ext_list:\n return uid\n\n return ebooklib.ITEM_UNKNOWN\n",
"def add_link(self, **kwgs):\n \"\"\"\n Add additional link to the document. Links will be embeded only inside of this document.\n\n >>> add_link(href='styles.css', rel='stylesheet', type='text/css')\n \"\"\"\n self.links.append(kwgs)\n if kwgs.get('type') == 'text/javascript':\n if 'scripted' not in self.properties:\n self.properties.append('scripted')\n"
] | class EpubHtml(EpubItem):
"""
Represents HTML document in the EPUB file.
"""
_template_name = 'chapter'
def __init__(self, uid=None, file_name='', media_type='', content=None, title='',
lang=None, direction=None, media_overlay=None, media_duration=None):
super(EpubHtml, self).__init__(uid, file_name, media_type, content)
self.title = title
self.lang = lang
self.direction = direction
self.media_overlay = media_overlay
self.media_duration = media_duration
self.links = []
self.properties = []
self.pages = []
def is_chapter(self):
"""
Returns if this document is chapter or not.
:Returns:
Returns book value.
"""
return True
def get_type(self):
"""
Always returns ebooklib.ITEM_DOCUMENT as type of this document.
:Returns:
Always returns ebooklib.ITEM_DOCUMENT
"""
return ebooklib.ITEM_DOCUMENT
def set_language(self, lang):
"""
Sets language for this book item. By default it will use language of the book but it
can be overwritten with this call.
"""
self.lang = lang
def get_language(self):
"""
Get language code for this book item. Language of the book item can be different from
the language settings defined globaly for book.
:Returns:
As string returns language code.
"""
return self.lang
def add_link(self, **kwgs):
"""
Add additional link to the document. Links will be embeded only inside of this document.
>>> add_link(href='styles.css', rel='stylesheet', type='text/css')
"""
self.links.append(kwgs)
if kwgs.get('type') == 'text/javascript':
if 'scripted' not in self.properties:
self.properties.append('scripted')
def get_links(self):
"""
Returns list of additional links defined for this document.
:Returns:
As tuple return list of links.
"""
return (link for link in self.links)
def get_links_of_type(self, link_type):
"""
Returns list of additional links of specific type.
:Returns:
As tuple returns list of links.
"""
return (link for link in self.links if link.get('type', '') == link_type)
def get_body_content(self):
"""
Returns content of BODY element for this HTML document. Content will be of type 'str' (Python 2)
or 'bytes' (Python 3).
:Returns:
Returns content of this document.
"""
try:
html_tree = parse_html_string(self.content)
except:
return ''
html_root = html_tree.getroottree()
if len(html_root.find('body')) != 0:
body = html_tree.find('body')
tree_str = etree.tostring(body, pretty_print=True, encoding='utf-8', xml_declaration=False)
# this is so stupid
if tree_str.startswith(six.b('<body>')):
n = tree_str.rindex(six.b('</body>'))
return tree_str[6:n]
return tree_str
return ''
def get_content(self, default=None):
"""
Returns content for this document as HTML string. Content will be of type 'str' (Python 2)
or 'bytes' (Python 3).
:Args:
- default: Default value for the content if it is not defined.
:Returns:
Returns content of this document.
"""
tree = parse_string(self.book.get_template(self._template_name))
tree_root = tree.getroot()
tree_root.set('lang', self.lang or self.book.language)
tree_root.attrib['{%s}lang' % NAMESPACES['XML']] = self.lang or self.book.language
# add to the head also
# <meta charset="utf-8" />
try:
html_tree = parse_html_string(self.content)
except:
return ''
html_root = html_tree.getroottree()
# create and populate head
_head = etree.SubElement(tree_root, 'head')
if self.title != '':
_title = etree.SubElement(_head, 'title')
_title.text = self.title
for lnk in self.links:
if lnk.get('type') == 'text/javascript':
_lnk = etree.SubElement(_head, 'script', lnk)
# force <script></script>
_lnk.text = ''
else:
_lnk = etree.SubElement(_head, 'link', lnk)
# this should not be like this
# head = html_root.find('head')
# if head is not None:
# for i in head.getchildren():
# if i.tag == 'title' and self.title != '':
# continue
# _head.append(i)
# create and populate body
_body = etree.SubElement(tree_root, 'body')
if self.direction:
_body.set('dir', self.direction)
tree_root.set('dir', self.direction)
body = html_tree.find('body')
if body is not None:
for i in body.getchildren():
_body.append(i)
tree_str = etree.tostring(tree, pretty_print=True, encoding='utf-8', xml_declaration=True)
return tree_str
def __str__(self):
return '<EpubHtml:%s:%s>' % (self.id, self.file_name)
|
aerkalov/ebooklib | ebooklib/epub.py | EpubHtml.get_body_content | python | def get_body_content(self):
try:
html_tree = parse_html_string(self.content)
except:
return ''
html_root = html_tree.getroottree()
if len(html_root.find('body')) != 0:
body = html_tree.find('body')
tree_str = etree.tostring(body, pretty_print=True, encoding='utf-8', xml_declaration=False)
# this is so stupid
if tree_str.startswith(six.b('<body>')):
n = tree_str.rindex(six.b('</body>'))
return tree_str[6:n]
return tree_str
return '' | Returns content of BODY element for this HTML document. Content will be of type 'str' (Python 2)
or 'bytes' (Python 3).
:Returns:
Returns content of this document. | train | https://github.com/aerkalov/ebooklib/blob/305f2dd7f02923ffabf9586a5d16266113d00c4a/ebooklib/epub.py#L341-L370 | [
"def parse_html_string(s):\n from lxml import html\n\n utf8_parser = html.HTMLParser(encoding='utf-8')\n\n html_tree = html.document_fromstring(s, parser=utf8_parser)\n\n return html_tree\n"
] | class EpubHtml(EpubItem):
"""
Represents HTML document in the EPUB file.
"""
_template_name = 'chapter'
def __init__(self, uid=None, file_name='', media_type='', content=None, title='',
lang=None, direction=None, media_overlay=None, media_duration=None):
super(EpubHtml, self).__init__(uid, file_name, media_type, content)
self.title = title
self.lang = lang
self.direction = direction
self.media_overlay = media_overlay
self.media_duration = media_duration
self.links = []
self.properties = []
self.pages = []
def is_chapter(self):
"""
Returns if this document is chapter or not.
:Returns:
Returns book value.
"""
return True
def get_type(self):
"""
Always returns ebooklib.ITEM_DOCUMENT as type of this document.
:Returns:
Always returns ebooklib.ITEM_DOCUMENT
"""
return ebooklib.ITEM_DOCUMENT
def set_language(self, lang):
"""
Sets language for this book item. By default it will use language of the book but it
can be overwritten with this call.
"""
self.lang = lang
def get_language(self):
"""
Get language code for this book item. Language of the book item can be different from
the language settings defined globaly for book.
:Returns:
As string returns language code.
"""
return self.lang
def add_link(self, **kwgs):
"""
Add additional link to the document. Links will be embeded only inside of this document.
>>> add_link(href='styles.css', rel='stylesheet', type='text/css')
"""
self.links.append(kwgs)
if kwgs.get('type') == 'text/javascript':
if 'scripted' not in self.properties:
self.properties.append('scripted')
def get_links(self):
"""
Returns list of additional links defined for this document.
:Returns:
As tuple return list of links.
"""
return (link for link in self.links)
def get_links_of_type(self, link_type):
"""
Returns list of additional links of specific type.
:Returns:
As tuple returns list of links.
"""
return (link for link in self.links if link.get('type', '') == link_type)
def add_item(self, item):
"""
Add other item to this document. It will create additional links according to the item type.
:Args:
- item: item we want to add defined as instance of EpubItem
"""
if item.get_type() == ebooklib.ITEM_STYLE:
self.add_link(href=item.get_name(), rel='stylesheet', type='text/css')
if item.get_type() == ebooklib.ITEM_SCRIPT:
self.add_link(src=item.get_name(), type='text/javascript')
def get_content(self, default=None):
"""
Returns content for this document as HTML string. Content will be of type 'str' (Python 2)
or 'bytes' (Python 3).
:Args:
- default: Default value for the content if it is not defined.
:Returns:
Returns content of this document.
"""
tree = parse_string(self.book.get_template(self._template_name))
tree_root = tree.getroot()
tree_root.set('lang', self.lang or self.book.language)
tree_root.attrib['{%s}lang' % NAMESPACES['XML']] = self.lang or self.book.language
# add to the head also
# <meta charset="utf-8" />
try:
html_tree = parse_html_string(self.content)
except:
return ''
html_root = html_tree.getroottree()
# create and populate head
_head = etree.SubElement(tree_root, 'head')
if self.title != '':
_title = etree.SubElement(_head, 'title')
_title.text = self.title
for lnk in self.links:
if lnk.get('type') == 'text/javascript':
_lnk = etree.SubElement(_head, 'script', lnk)
# force <script></script>
_lnk.text = ''
else:
_lnk = etree.SubElement(_head, 'link', lnk)
# this should not be like this
# head = html_root.find('head')
# if head is not None:
# for i in head.getchildren():
# if i.tag == 'title' and self.title != '':
# continue
# _head.append(i)
# create and populate body
_body = etree.SubElement(tree_root, 'body')
if self.direction:
_body.set('dir', self.direction)
tree_root.set('dir', self.direction)
body = html_tree.find('body')
if body is not None:
for i in body.getchildren():
_body.append(i)
tree_str = etree.tostring(tree, pretty_print=True, encoding='utf-8', xml_declaration=True)
return tree_str
def __str__(self):
return '<EpubHtml:%s:%s>' % (self.id, self.file_name)
|
aerkalov/ebooklib | ebooklib/epub.py | EpubHtml.get_content | python | def get_content(self, default=None):
tree = parse_string(self.book.get_template(self._template_name))
tree_root = tree.getroot()
tree_root.set('lang', self.lang or self.book.language)
tree_root.attrib['{%s}lang' % NAMESPACES['XML']] = self.lang or self.book.language
# add to the head also
# <meta charset="utf-8" />
try:
html_tree = parse_html_string(self.content)
except:
return ''
html_root = html_tree.getroottree()
# create and populate head
_head = etree.SubElement(tree_root, 'head')
if self.title != '':
_title = etree.SubElement(_head, 'title')
_title.text = self.title
for lnk in self.links:
if lnk.get('type') == 'text/javascript':
_lnk = etree.SubElement(_head, 'script', lnk)
# force <script></script>
_lnk.text = ''
else:
_lnk = etree.SubElement(_head, 'link', lnk)
# this should not be like this
# head = html_root.find('head')
# if head is not None:
# for i in head.getchildren():
# if i.tag == 'title' and self.title != '':
# continue
# _head.append(i)
# create and populate body
_body = etree.SubElement(tree_root, 'body')
if self.direction:
_body.set('dir', self.direction)
tree_root.set('dir', self.direction)
body = html_tree.find('body')
if body is not None:
for i in body.getchildren():
_body.append(i)
tree_str = etree.tostring(tree, pretty_print=True, encoding='utf-8', xml_declaration=True)
return tree_str | Returns content for this document as HTML string. Content will be of type 'str' (Python 2)
or 'bytes' (Python 3).
:Args:
- default: Default value for the content if it is not defined.
:Returns:
Returns content of this document. | train | https://github.com/aerkalov/ebooklib/blob/305f2dd7f02923ffabf9586a5d16266113d00c4a/ebooklib/epub.py#L372-L438 | [
"def parse_html_string(s):\n from lxml import html\n\n utf8_parser = html.HTMLParser(encoding='utf-8')\n\n html_tree = html.document_fromstring(s, parser=utf8_parser)\n\n return html_tree\n",
"def parse_string(s):\n try:\n tree = etree.parse(io.BytesIO(s.encode('utf-8')))\n except:\n tree = etree.parse(io.BytesIO(s))\n\n return tree\n"
] | class EpubHtml(EpubItem):
"""
Represents HTML document in the EPUB file.
"""
_template_name = 'chapter'
def __init__(self, uid=None, file_name='', media_type='', content=None, title='',
lang=None, direction=None, media_overlay=None, media_duration=None):
super(EpubHtml, self).__init__(uid, file_name, media_type, content)
self.title = title
self.lang = lang
self.direction = direction
self.media_overlay = media_overlay
self.media_duration = media_duration
self.links = []
self.properties = []
self.pages = []
def is_chapter(self):
"""
Returns if this document is chapter or not.
:Returns:
Returns book value.
"""
return True
def get_type(self):
"""
Always returns ebooklib.ITEM_DOCUMENT as type of this document.
:Returns:
Always returns ebooklib.ITEM_DOCUMENT
"""
return ebooklib.ITEM_DOCUMENT
def set_language(self, lang):
"""
Sets language for this book item. By default it will use language of the book but it
can be overwritten with this call.
"""
self.lang = lang
def get_language(self):
"""
Get language code for this book item. Language of the book item can be different from
the language settings defined globaly for book.
:Returns:
As string returns language code.
"""
return self.lang
def add_link(self, **kwgs):
"""
Add additional link to the document. Links will be embeded only inside of this document.
>>> add_link(href='styles.css', rel='stylesheet', type='text/css')
"""
self.links.append(kwgs)
if kwgs.get('type') == 'text/javascript':
if 'scripted' not in self.properties:
self.properties.append('scripted')
def get_links(self):
"""
Returns list of additional links defined for this document.
:Returns:
As tuple return list of links.
"""
return (link for link in self.links)
def get_links_of_type(self, link_type):
"""
Returns list of additional links of specific type.
:Returns:
As tuple returns list of links.
"""
return (link for link in self.links if link.get('type', '') == link_type)
def add_item(self, item):
"""
Add other item to this document. It will create additional links according to the item type.
:Args:
- item: item we want to add defined as instance of EpubItem
"""
if item.get_type() == ebooklib.ITEM_STYLE:
self.add_link(href=item.get_name(), rel='stylesheet', type='text/css')
if item.get_type() == ebooklib.ITEM_SCRIPT:
self.add_link(src=item.get_name(), type='text/javascript')
def get_body_content(self):
"""
Returns content of BODY element for this HTML document. Content will be of type 'str' (Python 2)
or 'bytes' (Python 3).
:Returns:
Returns content of this document.
"""
try:
html_tree = parse_html_string(self.content)
except:
return ''
html_root = html_tree.getroottree()
if len(html_root.find('body')) != 0:
body = html_tree.find('body')
tree_str = etree.tostring(body, pretty_print=True, encoding='utf-8', xml_declaration=False)
# this is so stupid
if tree_str.startswith(six.b('<body>')):
n = tree_str.rindex(six.b('</body>'))
return tree_str[6:n]
return tree_str
return ''
def __str__(self):
return '<EpubHtml:%s:%s>' % (self.id, self.file_name)
|
aerkalov/ebooklib | ebooklib/epub.py | EpubCoverHtml.get_content | python | def get_content(self):
self.content = self.book.get_template('cover')
tree = parse_string(super(EpubCoverHtml, self).get_content())
tree_root = tree.getroot()
images = tree_root.xpath('//xhtml:img', namespaces={'xhtml': NAMESPACES['XHTML']})
images[0].set('src', self.image_name)
images[0].set('alt', self.title)
tree_str = etree.tostring(tree, pretty_print=True, encoding='utf-8', xml_declaration=True)
return tree_str | Returns content for cover page as HTML string. Content will be of type 'str' (Python 2) or 'bytes' (Python 3).
:Returns:
Returns content of this document. | train | https://github.com/aerkalov/ebooklib/blob/305f2dd7f02923ffabf9586a5d16266113d00c4a/ebooklib/epub.py#L466-L486 | [
"def parse_string(s):\n try:\n tree = etree.parse(io.BytesIO(s.encode('utf-8')))\n except:\n tree = etree.parse(io.BytesIO(s))\n\n return tree\n",
"def get_content(self, default=None):\n \"\"\"\n Returns content for this document as HTML string. Content will be of type 'str' (Python 2)\n or 'bytes' (Python 3).\n\n :Args:\n - default: Default value for the content if it is not defined.\n\n :Returns:\n Returns content of this document.\n \"\"\"\n\n tree = parse_string(self.book.get_template(self._template_name))\n tree_root = tree.getroot()\n\n tree_root.set('lang', self.lang or self.book.language)\n tree_root.attrib['{%s}lang' % NAMESPACES['XML']] = self.lang or self.book.language\n\n # add to the head also\n # <meta charset=\"utf-8\" />\n\n try:\n html_tree = parse_html_string(self.content)\n except:\n return ''\n\n html_root = html_tree.getroottree()\n\n # create and populate head\n\n _head = etree.SubElement(tree_root, 'head')\n\n if self.title != '':\n _title = etree.SubElement(_head, 'title')\n _title.text = self.title\n\n for lnk in self.links:\n if lnk.get('type') == 'text/javascript':\n _lnk = etree.SubElement(_head, 'script', lnk)\n # force <script></script>\n _lnk.text = ''\n else:\n _lnk = etree.SubElement(_head, 'link', lnk)\n\n # this should not be like this\n # head = html_root.find('head')\n # if head is not None:\n # for i in head.getchildren():\n # if i.tag == 'title' and self.title != '':\n # continue\n # _head.append(i)\n\n # create and populate body\n\n _body = etree.SubElement(tree_root, 'body')\n if self.direction:\n _body.set('dir', self.direction)\n tree_root.set('dir', self.direction)\n\n body = html_tree.find('body')\n if body is not None:\n for i in body.getchildren():\n _body.append(i)\n\n tree_str = etree.tostring(tree, pretty_print=True, encoding='utf-8', xml_declaration=True)\n\n return tree_str\n"
] | class EpubCoverHtml(EpubHtml):
"""
Represents Cover page in the EPUB file.
"""
def __init__(self, uid='cover', file_name='cover.xhtml', image_name='', title='Cover'):
super(EpubCoverHtml, self).__init__(uid=uid, file_name=file_name, title=title)
self.image_name = image_name
self.is_linear = False
def is_chapter(self):
"""
Returns if this document is chapter or not.
:Returns:
Returns book value.
"""
return False
def __str__(self):
return '<EpubCoverHtml:%s:%s>' % (self.id, self.file_name)
|
aerkalov/ebooklib | ebooklib/epub.py | EpubBook.reset | python | def reset(self):
"Initialises all needed variables to default values"
self.metadata = {}
self.items = []
self.spine = []
self.guide = []
self.pages = []
self.toc = []
self.bindings = []
self.IDENTIFIER_ID = 'id'
self.FOLDER_NAME = 'EPUB'
self._id_html = 0
self._id_image = 0
self._id_static = 0
self.title = ''
self.language = 'en'
self.direction = None
self.templates = {
'ncx': NCX_XML,
'nav': NAV_XML,
'chapter': CHAPTER_XML,
'cover': COVER_XML
}
self.add_metadata('OPF', 'generator', '', {
'name': 'generator', 'content': 'Ebook-lib %s' % '.'.join([str(s) for s in VERSION])
})
# default to using a randomly-unique identifier if one is not specified manually
self.set_identifier(str(uuid.uuid4()))
# custom prefixes and namespaces to be set to the content.opf doc
self.prefixes = []
self.namespaces = {} | Initialises all needed variables to default values | train | https://github.com/aerkalov/ebooklib/blob/305f2dd7f02923ffabf9586a5d16266113d00c4a/ebooklib/epub.py#L554-L592 | [
"def set_identifier(self, uid):\n \"\"\"\n Sets unique id for this epub\n\n :Args:\n - uid: Value of unique identifier for this book\n \"\"\"\n\n self.uid = uid\n\n self.set_unique_metadata('DC', 'identifier', self.uid, {'id': self.IDENTIFIER_ID})\n",
"def add_metadata(self, namespace, name, value, others=None):\n \"Add metadata\"\n\n if namespace in NAMESPACES:\n namespace = NAMESPACES[namespace]\n\n if namespace not in self.metadata:\n self.metadata[namespace] = {}\n\n if name not in self.metadata[namespace]:\n self.metadata[namespace][name] = []\n\n self.metadata[namespace][name].append((value, others))\n"
] | class EpubBook(object):
def __init__(self):
self.EPUB_VERSION = None
self.reset()
# we should have options here
def set_identifier(self, uid):
"""
Sets unique id for this epub
:Args:
- uid: Value of unique identifier for this book
"""
self.uid = uid
self.set_unique_metadata('DC', 'identifier', self.uid, {'id': self.IDENTIFIER_ID})
def set_title(self, title):
"""
Set title. You can set multiple titles.
:Args:
- title: Title value
"""
self.title = title
self.add_metadata('DC', 'title', self.title)
def set_language(self, lang):
"""
Set language for this epub. You can set multiple languages. Specific items in the book can have
different language settings.
:Args:
- lang: Language code
"""
self.language = lang
self.add_metadata('DC', 'language', lang)
def set_direction(self, direction):
"""
:Args:
- direction: Options are "ltr", "rtl" and "default"
"""
self.direction = direction
def set_cover(self, file_name, content, create_page=True):
"""
Set cover and create cover document if needed.
:Args:
- file_name: file name of the cover page
- content: Content for the cover image
- create_page: Should cover page be defined. Defined as bool value (optional). Default value is True.
"""
# as it is now, it can only be called once
c0 = EpubCover(file_name=file_name)
c0.content = content
self.add_item(c0)
if create_page:
c1 = EpubCoverHtml(image_name=file_name)
self.add_item(c1)
self.add_metadata(None, 'meta', '', OrderedDict([('name', 'cover'), ('content', 'cover-img')]))
def add_author(self, author, file_as=None, role=None, uid='creator'):
"Add author for this document"
self.add_metadata('DC', 'creator', author, {'id': uid})
if file_as:
self.add_metadata(None, 'meta', file_as, {'refines': '#' + uid,
'property': 'file-as',
'scheme': 'marc:relators'})
if role:
self.add_metadata(None, 'meta', role, {'refines': '#' + uid,
'property': 'role',
'scheme': 'marc:relators'})
def add_metadata(self, namespace, name, value, others=None):
"Add metadata"
if namespace in NAMESPACES:
namespace = NAMESPACES[namespace]
if namespace not in self.metadata:
self.metadata[namespace] = {}
if name not in self.metadata[namespace]:
self.metadata[namespace][name] = []
self.metadata[namespace][name].append((value, others))
def get_metadata(self, namespace, name):
"Retrieve metadata"
if namespace in NAMESPACES:
namespace = NAMESPACES[namespace]
return self.metadata[namespace].get(name, [])
def set_unique_metadata(self, namespace, name, value, others=None):
"Add metadata if metadata with this identifier does not already exist, otherwise update existing metadata."
if namespace in NAMESPACES:
namespace = NAMESPACES[namespace]
if namespace in self.metadata and name in self.metadata[namespace]:
self.metadata[namespace][name] = [(value, others)]
else:
self.add_metadata(namespace, name, value, others)
def add_item(self, item):
"""
Add additional item to the book. If not defined, media type and chapter id will be defined
for the item.
:Args:
- item: Item instance
"""
if item.media_type == '':
(has_guessed, media_type) = guess_type(item.get_name().lower())
if has_guessed:
if media_type is not None:
item.media_type = media_type
else:
item.media_type = has_guessed
else:
item.media_type = 'application/octet-stream'
if not item.get_id():
# make chapter_, image_ and static_ configurable
if isinstance(item, EpubHtml):
item.id = 'chapter_%d' % self._id_html
self._id_html += 1
# If there's a page list, append it to the book's page list
self.pages += item.pages
elif isinstance(item, EpubImage):
item.id = 'image_%d' % self._id_image
self._id_image += 1
else:
item.id = 'static_%d' % self._id_image
self._id_image += 1
item.book = self
self.items.append(item)
return item
def get_item_with_id(self, uid):
"""
Returns item for defined UID.
>>> book.get_item_with_id('image_001')
:Args:
- uid: UID for the item
:Returns:
Returns item object. Returns None if nothing was found.
"""
for item in self.get_items():
if item.id == uid:
return item
return None
def get_item_with_href(self, href):
"""
Returns item for defined HREF.
>>> book.get_item_with_href('EPUB/document.xhtml')
:Args:
- href: HREF for the item we are searching for
:Returns:
Returns item object. Returns None if nothing was found.
"""
for item in self.get_items():
if item.get_name() == href:
return item
return None
def get_items(self):
"""
Returns all items attached to this book.
:Returns:
Returns all items as tuple.
"""
return (item for item in self.items)
def get_items_of_type(self, item_type):
"""
Returns all items of specified type.
>>> book.get_items_of_type(epub.ITEM_IMAGE)
:Args:
- item_type: Type for items we are searching for
:Returns:
Returns found items as tuple.
"""
return (item for item in self.items if item.get_type() == item_type)
def get_items_of_media_type(self, media_type):
"""
Returns all items of specified media type.
:Args:
- media_type: Media type for items we are searching for
:Returns:
Returns found items as tuple.
"""
return (item for item in self.items if item.media_type == media_type)
def set_template(self, name, value):
"""
Defines templates which are used to generate certain types of pages. When defining new value for the template
we have to use content of type 'str' (Python 2) or 'bytes' (Python 3).
At the moment we use these templates:
- ncx
- nav
- chapter
- cover
:Args:
- name: Name for the template
- value: Content for the template
"""
self.templates[name] = value
def get_template(self, name):
"""
Returns value for the template.
:Args:
- name: template name
:Returns:
Value of the template.
"""
return self.templates.get(name)
def add_prefix(self, name, uri):
"""
Appends custom prefix to be added to the content.opf document
>>> epub_book.add_prefix('bkterms', 'http://booktype.org/')
:Args:
- name: namespave name
- uri: URI for the namespace
"""
self.prefixes.append('%s: %s' % (name, uri))
|
aerkalov/ebooklib | ebooklib/epub.py | EpubBook.set_identifier | python | def set_identifier(self, uid):
self.uid = uid
self.set_unique_metadata('DC', 'identifier', self.uid, {'id': self.IDENTIFIER_ID}) | Sets unique id for this epub
:Args:
- uid: Value of unique identifier for this book | train | https://github.com/aerkalov/ebooklib/blob/305f2dd7f02923ffabf9586a5d16266113d00c4a/ebooklib/epub.py#L594-L604 | [
"def set_unique_metadata(self, namespace, name, value, others=None):\n \"Add metadata if metadata with this identifier does not already exist, otherwise update existing metadata.\"\n\n if namespace in NAMESPACES:\n namespace = NAMESPACES[namespace]\n\n if namespace in self.metadata and name in self.metadata[namespace]:\n self.metadata[namespace][name] = [(value, others)]\n else:\n self.add_metadata(namespace, name, value, others)\n"
] | class EpubBook(object):
def __init__(self):
self.EPUB_VERSION = None
self.reset()
# we should have options here
def reset(self):
"Initialises all needed variables to default values"
self.metadata = {}
self.items = []
self.spine = []
self.guide = []
self.pages = []
self.toc = []
self.bindings = []
self.IDENTIFIER_ID = 'id'
self.FOLDER_NAME = 'EPUB'
self._id_html = 0
self._id_image = 0
self._id_static = 0
self.title = ''
self.language = 'en'
self.direction = None
self.templates = {
'ncx': NCX_XML,
'nav': NAV_XML,
'chapter': CHAPTER_XML,
'cover': COVER_XML
}
self.add_metadata('OPF', 'generator', '', {
'name': 'generator', 'content': 'Ebook-lib %s' % '.'.join([str(s) for s in VERSION])
})
# default to using a randomly-unique identifier if one is not specified manually
self.set_identifier(str(uuid.uuid4()))
# custom prefixes and namespaces to be set to the content.opf doc
self.prefixes = []
self.namespaces = {}
def set_title(self, title):
"""
Set title. You can set multiple titles.
:Args:
- title: Title value
"""
self.title = title
self.add_metadata('DC', 'title', self.title)
def set_language(self, lang):
"""
Set language for this epub. You can set multiple languages. Specific items in the book can have
different language settings.
:Args:
- lang: Language code
"""
self.language = lang
self.add_metadata('DC', 'language', lang)
def set_direction(self, direction):
"""
:Args:
- direction: Options are "ltr", "rtl" and "default"
"""
self.direction = direction
def set_cover(self, file_name, content, create_page=True):
"""
Set cover and create cover document if needed.
:Args:
- file_name: file name of the cover page
- content: Content for the cover image
- create_page: Should cover page be defined. Defined as bool value (optional). Default value is True.
"""
# as it is now, it can only be called once
c0 = EpubCover(file_name=file_name)
c0.content = content
self.add_item(c0)
if create_page:
c1 = EpubCoverHtml(image_name=file_name)
self.add_item(c1)
self.add_metadata(None, 'meta', '', OrderedDict([('name', 'cover'), ('content', 'cover-img')]))
def add_author(self, author, file_as=None, role=None, uid='creator'):
"Add author for this document"
self.add_metadata('DC', 'creator', author, {'id': uid})
if file_as:
self.add_metadata(None, 'meta', file_as, {'refines': '#' + uid,
'property': 'file-as',
'scheme': 'marc:relators'})
if role:
self.add_metadata(None, 'meta', role, {'refines': '#' + uid,
'property': 'role',
'scheme': 'marc:relators'})
def add_metadata(self, namespace, name, value, others=None):
"Add metadata"
if namespace in NAMESPACES:
namespace = NAMESPACES[namespace]
if namespace not in self.metadata:
self.metadata[namespace] = {}
if name not in self.metadata[namespace]:
self.metadata[namespace][name] = []
self.metadata[namespace][name].append((value, others))
def get_metadata(self, namespace, name):
"Retrieve metadata"
if namespace in NAMESPACES:
namespace = NAMESPACES[namespace]
return self.metadata[namespace].get(name, [])
def set_unique_metadata(self, namespace, name, value, others=None):
"Add metadata if metadata with this identifier does not already exist, otherwise update existing metadata."
if namespace in NAMESPACES:
namespace = NAMESPACES[namespace]
if namespace in self.metadata and name in self.metadata[namespace]:
self.metadata[namespace][name] = [(value, others)]
else:
self.add_metadata(namespace, name, value, others)
def add_item(self, item):
"""
Add additional item to the book. If not defined, media type and chapter id will be defined
for the item.
:Args:
- item: Item instance
"""
if item.media_type == '':
(has_guessed, media_type) = guess_type(item.get_name().lower())
if has_guessed:
if media_type is not None:
item.media_type = media_type
else:
item.media_type = has_guessed
else:
item.media_type = 'application/octet-stream'
if not item.get_id():
# make chapter_, image_ and static_ configurable
if isinstance(item, EpubHtml):
item.id = 'chapter_%d' % self._id_html
self._id_html += 1
# If there's a page list, append it to the book's page list
self.pages += item.pages
elif isinstance(item, EpubImage):
item.id = 'image_%d' % self._id_image
self._id_image += 1
else:
item.id = 'static_%d' % self._id_image
self._id_image += 1
item.book = self
self.items.append(item)
return item
def get_item_with_id(self, uid):
"""
Returns item for defined UID.
>>> book.get_item_with_id('image_001')
:Args:
- uid: UID for the item
:Returns:
Returns item object. Returns None if nothing was found.
"""
for item in self.get_items():
if item.id == uid:
return item
return None
def get_item_with_href(self, href):
"""
Returns item for defined HREF.
>>> book.get_item_with_href('EPUB/document.xhtml')
:Args:
- href: HREF for the item we are searching for
:Returns:
Returns item object. Returns None if nothing was found.
"""
for item in self.get_items():
if item.get_name() == href:
return item
return None
def get_items(self):
"""
Returns all items attached to this book.
:Returns:
Returns all items as tuple.
"""
return (item for item in self.items)
def get_items_of_type(self, item_type):
"""
Returns all items of specified type.
>>> book.get_items_of_type(epub.ITEM_IMAGE)
:Args:
- item_type: Type for items we are searching for
:Returns:
Returns found items as tuple.
"""
return (item for item in self.items if item.get_type() == item_type)
def get_items_of_media_type(self, media_type):
"""
Returns all items of specified media type.
:Args:
- media_type: Media type for items we are searching for
:Returns:
Returns found items as tuple.
"""
return (item for item in self.items if item.media_type == media_type)
def set_template(self, name, value):
"""
Defines templates which are used to generate certain types of pages. When defining new value for the template
we have to use content of type 'str' (Python 2) or 'bytes' (Python 3).
At the moment we use these templates:
- ncx
- nav
- chapter
- cover
:Args:
- name: Name for the template
- value: Content for the template
"""
self.templates[name] = value
def get_template(self, name):
"""
Returns value for the template.
:Args:
- name: template name
:Returns:
Value of the template.
"""
return self.templates.get(name)
def add_prefix(self, name, uri):
"""
Appends custom prefix to be added to the content.opf document
>>> epub_book.add_prefix('bkterms', 'http://booktype.org/')
:Args:
- name: namespave name
- uri: URI for the namespace
"""
self.prefixes.append('%s: %s' % (name, uri))
|
aerkalov/ebooklib | ebooklib/epub.py | EpubBook.set_title | python | def set_title(self, title):
self.title = title
self.add_metadata('DC', 'title', self.title) | Set title. You can set multiple titles.
:Args:
- title: Title value | train | https://github.com/aerkalov/ebooklib/blob/305f2dd7f02923ffabf9586a5d16266113d00c4a/ebooklib/epub.py#L606-L616 | [
"def add_metadata(self, namespace, name, value, others=None):\n \"Add metadata\"\n\n if namespace in NAMESPACES:\n namespace = NAMESPACES[namespace]\n\n if namespace not in self.metadata:\n self.metadata[namespace] = {}\n\n if name not in self.metadata[namespace]:\n self.metadata[namespace][name] = []\n\n self.metadata[namespace][name].append((value, others))\n"
] | class EpubBook(object):
def __init__(self):
self.EPUB_VERSION = None
self.reset()
# we should have options here
def reset(self):
"Initialises all needed variables to default values"
self.metadata = {}
self.items = []
self.spine = []
self.guide = []
self.pages = []
self.toc = []
self.bindings = []
self.IDENTIFIER_ID = 'id'
self.FOLDER_NAME = 'EPUB'
self._id_html = 0
self._id_image = 0
self._id_static = 0
self.title = ''
self.language = 'en'
self.direction = None
self.templates = {
'ncx': NCX_XML,
'nav': NAV_XML,
'chapter': CHAPTER_XML,
'cover': COVER_XML
}
self.add_metadata('OPF', 'generator', '', {
'name': 'generator', 'content': 'Ebook-lib %s' % '.'.join([str(s) for s in VERSION])
})
# default to using a randomly-unique identifier if one is not specified manually
self.set_identifier(str(uuid.uuid4()))
# custom prefixes and namespaces to be set to the content.opf doc
self.prefixes = []
self.namespaces = {}
def set_identifier(self, uid):
"""
Sets unique id for this epub
:Args:
- uid: Value of unique identifier for this book
"""
self.uid = uid
self.set_unique_metadata('DC', 'identifier', self.uid, {'id': self.IDENTIFIER_ID})
def set_language(self, lang):
"""
Set language for this epub. You can set multiple languages. Specific items in the book can have
different language settings.
:Args:
- lang: Language code
"""
self.language = lang
self.add_metadata('DC', 'language', lang)
def set_direction(self, direction):
"""
:Args:
- direction: Options are "ltr", "rtl" and "default"
"""
self.direction = direction
def set_cover(self, file_name, content, create_page=True):
"""
Set cover and create cover document if needed.
:Args:
- file_name: file name of the cover page
- content: Content for the cover image
- create_page: Should cover page be defined. Defined as bool value (optional). Default value is True.
"""
# as it is now, it can only be called once
c0 = EpubCover(file_name=file_name)
c0.content = content
self.add_item(c0)
if create_page:
c1 = EpubCoverHtml(image_name=file_name)
self.add_item(c1)
self.add_metadata(None, 'meta', '', OrderedDict([('name', 'cover'), ('content', 'cover-img')]))
def add_author(self, author, file_as=None, role=None, uid='creator'):
"Add author for this document"
self.add_metadata('DC', 'creator', author, {'id': uid})
if file_as:
self.add_metadata(None, 'meta', file_as, {'refines': '#' + uid,
'property': 'file-as',
'scheme': 'marc:relators'})
if role:
self.add_metadata(None, 'meta', role, {'refines': '#' + uid,
'property': 'role',
'scheme': 'marc:relators'})
def add_metadata(self, namespace, name, value, others=None):
"Add metadata"
if namespace in NAMESPACES:
namespace = NAMESPACES[namespace]
if namespace not in self.metadata:
self.metadata[namespace] = {}
if name not in self.metadata[namespace]:
self.metadata[namespace][name] = []
self.metadata[namespace][name].append((value, others))
def get_metadata(self, namespace, name):
"Retrieve metadata"
if namespace in NAMESPACES:
namespace = NAMESPACES[namespace]
return self.metadata[namespace].get(name, [])
def set_unique_metadata(self, namespace, name, value, others=None):
"Add metadata if metadata with this identifier does not already exist, otherwise update existing metadata."
if namespace in NAMESPACES:
namespace = NAMESPACES[namespace]
if namespace in self.metadata and name in self.metadata[namespace]:
self.metadata[namespace][name] = [(value, others)]
else:
self.add_metadata(namespace, name, value, others)
def add_item(self, item):
"""
Add additional item to the book. If not defined, media type and chapter id will be defined
for the item.
:Args:
- item: Item instance
"""
if item.media_type == '':
(has_guessed, media_type) = guess_type(item.get_name().lower())
if has_guessed:
if media_type is not None:
item.media_type = media_type
else:
item.media_type = has_guessed
else:
item.media_type = 'application/octet-stream'
if not item.get_id():
# make chapter_, image_ and static_ configurable
if isinstance(item, EpubHtml):
item.id = 'chapter_%d' % self._id_html
self._id_html += 1
# If there's a page list, append it to the book's page list
self.pages += item.pages
elif isinstance(item, EpubImage):
item.id = 'image_%d' % self._id_image
self._id_image += 1
else:
item.id = 'static_%d' % self._id_image
self._id_image += 1
item.book = self
self.items.append(item)
return item
def get_item_with_id(self, uid):
"""
Returns item for defined UID.
>>> book.get_item_with_id('image_001')
:Args:
- uid: UID for the item
:Returns:
Returns item object. Returns None if nothing was found.
"""
for item in self.get_items():
if item.id == uid:
return item
return None
def get_item_with_href(self, href):
"""
Returns item for defined HREF.
>>> book.get_item_with_href('EPUB/document.xhtml')
:Args:
- href: HREF for the item we are searching for
:Returns:
Returns item object. Returns None if nothing was found.
"""
for item in self.get_items():
if item.get_name() == href:
return item
return None
def get_items(self):
"""
Returns all items attached to this book.
:Returns:
Returns all items as tuple.
"""
return (item for item in self.items)
def get_items_of_type(self, item_type):
"""
Returns all items of specified type.
>>> book.get_items_of_type(epub.ITEM_IMAGE)
:Args:
- item_type: Type for items we are searching for
:Returns:
Returns found items as tuple.
"""
return (item for item in self.items if item.get_type() == item_type)
def get_items_of_media_type(self, media_type):
"""
Returns all items of specified media type.
:Args:
- media_type: Media type for items we are searching for
:Returns:
Returns found items as tuple.
"""
return (item for item in self.items if item.media_type == media_type)
def set_template(self, name, value):
"""
Defines templates which are used to generate certain types of pages. When defining new value for the template
we have to use content of type 'str' (Python 2) or 'bytes' (Python 3).
At the moment we use these templates:
- ncx
- nav
- chapter
- cover
:Args:
- name: Name for the template
- value: Content for the template
"""
self.templates[name] = value
def get_template(self, name):
"""
Returns value for the template.
:Args:
- name: template name
:Returns:
Value of the template.
"""
return self.templates.get(name)
def add_prefix(self, name, uri):
"""
Appends custom prefix to be added to the content.opf document
>>> epub_book.add_prefix('bkterms', 'http://booktype.org/')
:Args:
- name: namespave name
- uri: URI for the namespace
"""
self.prefixes.append('%s: %s' % (name, uri))
|
aerkalov/ebooklib | ebooklib/epub.py | EpubBook.set_cover | python | def set_cover(self, file_name, content, create_page=True):
# as it is now, it can only be called once
c0 = EpubCover(file_name=file_name)
c0.content = content
self.add_item(c0)
if create_page:
c1 = EpubCoverHtml(image_name=file_name)
self.add_item(c1)
self.add_metadata(None, 'meta', '', OrderedDict([('name', 'cover'), ('content', 'cover-img')])) | Set cover and create cover document if needed.
:Args:
- file_name: file name of the cover page
- content: Content for the cover image
- create_page: Should cover page be defined. Defined as bool value (optional). Default value is True. | train | https://github.com/aerkalov/ebooklib/blob/305f2dd7f02923ffabf9586a5d16266113d00c4a/ebooklib/epub.py#L639-L658 | [
"def add_metadata(self, namespace, name, value, others=None):\n \"Add metadata\"\n\n if namespace in NAMESPACES:\n namespace = NAMESPACES[namespace]\n\n if namespace not in self.metadata:\n self.metadata[namespace] = {}\n\n if name not in self.metadata[namespace]:\n self.metadata[namespace][name] = []\n\n self.metadata[namespace][name].append((value, others))\n",
"def add_item(self, item):\n \"\"\"\n Add additional item to the book. If not defined, media type and chapter id will be defined\n for the item.\n\n :Args:\n - item: Item instance\n \"\"\"\n if item.media_type == '':\n (has_guessed, media_type) = guess_type(item.get_name().lower())\n\n if has_guessed:\n if media_type is not None:\n item.media_type = media_type\n else:\n item.media_type = has_guessed\n else:\n item.media_type = 'application/octet-stream'\n\n if not item.get_id():\n # make chapter_, image_ and static_ configurable\n if isinstance(item, EpubHtml):\n item.id = 'chapter_%d' % self._id_html\n self._id_html += 1\n # If there's a page list, append it to the book's page list\n self.pages += item.pages\n elif isinstance(item, EpubImage):\n item.id = 'image_%d' % self._id_image\n self._id_image += 1\n else:\n item.id = 'static_%d' % self._id_image\n self._id_image += 1\n\n item.book = self\n self.items.append(item)\n\n return item\n"
] | class EpubBook(object):
def __init__(self):
self.EPUB_VERSION = None
self.reset()
# we should have options here
def reset(self):
"Initialises all needed variables to default values"
self.metadata = {}
self.items = []
self.spine = []
self.guide = []
self.pages = []
self.toc = []
self.bindings = []
self.IDENTIFIER_ID = 'id'
self.FOLDER_NAME = 'EPUB'
self._id_html = 0
self._id_image = 0
self._id_static = 0
self.title = ''
self.language = 'en'
self.direction = None
self.templates = {
'ncx': NCX_XML,
'nav': NAV_XML,
'chapter': CHAPTER_XML,
'cover': COVER_XML
}
self.add_metadata('OPF', 'generator', '', {
'name': 'generator', 'content': 'Ebook-lib %s' % '.'.join([str(s) for s in VERSION])
})
# default to using a randomly-unique identifier if one is not specified manually
self.set_identifier(str(uuid.uuid4()))
# custom prefixes and namespaces to be set to the content.opf doc
self.prefixes = []
self.namespaces = {}
def set_identifier(self, uid):
"""
Sets unique id for this epub
:Args:
- uid: Value of unique identifier for this book
"""
self.uid = uid
self.set_unique_metadata('DC', 'identifier', self.uid, {'id': self.IDENTIFIER_ID})
def set_title(self, title):
"""
Set title. You can set multiple titles.
:Args:
- title: Title value
"""
self.title = title
self.add_metadata('DC', 'title', self.title)
def set_language(self, lang):
"""
Set language for this epub. You can set multiple languages. Specific items in the book can have
different language settings.
:Args:
- lang: Language code
"""
self.language = lang
self.add_metadata('DC', 'language', lang)
def set_direction(self, direction):
"""
:Args:
- direction: Options are "ltr", "rtl" and "default"
"""
self.direction = direction
def add_author(self, author, file_as=None, role=None, uid='creator'):
"Add author for this document"
self.add_metadata('DC', 'creator', author, {'id': uid})
if file_as:
self.add_metadata(None, 'meta', file_as, {'refines': '#' + uid,
'property': 'file-as',
'scheme': 'marc:relators'})
if role:
self.add_metadata(None, 'meta', role, {'refines': '#' + uid,
'property': 'role',
'scheme': 'marc:relators'})
def add_metadata(self, namespace, name, value, others=None):
"Add metadata"
if namespace in NAMESPACES:
namespace = NAMESPACES[namespace]
if namespace not in self.metadata:
self.metadata[namespace] = {}
if name not in self.metadata[namespace]:
self.metadata[namespace][name] = []
self.metadata[namespace][name].append((value, others))
def get_metadata(self, namespace, name):
"Retrieve metadata"
if namespace in NAMESPACES:
namespace = NAMESPACES[namespace]
return self.metadata[namespace].get(name, [])
def set_unique_metadata(self, namespace, name, value, others=None):
"Add metadata if metadata with this identifier does not already exist, otherwise update existing metadata."
if namespace in NAMESPACES:
namespace = NAMESPACES[namespace]
if namespace in self.metadata and name in self.metadata[namespace]:
self.metadata[namespace][name] = [(value, others)]
else:
self.add_metadata(namespace, name, value, others)
def add_item(self, item):
"""
Add additional item to the book. If not defined, media type and chapter id will be defined
for the item.
:Args:
- item: Item instance
"""
if item.media_type == '':
(has_guessed, media_type) = guess_type(item.get_name().lower())
if has_guessed:
if media_type is not None:
item.media_type = media_type
else:
item.media_type = has_guessed
else:
item.media_type = 'application/octet-stream'
if not item.get_id():
# make chapter_, image_ and static_ configurable
if isinstance(item, EpubHtml):
item.id = 'chapter_%d' % self._id_html
self._id_html += 1
# If there's a page list, append it to the book's page list
self.pages += item.pages
elif isinstance(item, EpubImage):
item.id = 'image_%d' % self._id_image
self._id_image += 1
else:
item.id = 'static_%d' % self._id_image
self._id_image += 1
item.book = self
self.items.append(item)
return item
def get_item_with_id(self, uid):
"""
Returns item for defined UID.
>>> book.get_item_with_id('image_001')
:Args:
- uid: UID for the item
:Returns:
Returns item object. Returns None if nothing was found.
"""
for item in self.get_items():
if item.id == uid:
return item
return None
def get_item_with_href(self, href):
"""
Returns item for defined HREF.
>>> book.get_item_with_href('EPUB/document.xhtml')
:Args:
- href: HREF for the item we are searching for
:Returns:
Returns item object. Returns None if nothing was found.
"""
for item in self.get_items():
if item.get_name() == href:
return item
return None
def get_items(self):
"""
Returns all items attached to this book.
:Returns:
Returns all items as tuple.
"""
return (item for item in self.items)
def get_items_of_type(self, item_type):
"""
Returns all items of specified type.
>>> book.get_items_of_type(epub.ITEM_IMAGE)
:Args:
- item_type: Type for items we are searching for
:Returns:
Returns found items as tuple.
"""
return (item for item in self.items if item.get_type() == item_type)
def get_items_of_media_type(self, media_type):
"""
Returns all items of specified media type.
:Args:
- media_type: Media type for items we are searching for
:Returns:
Returns found items as tuple.
"""
return (item for item in self.items if item.media_type == media_type)
def set_template(self, name, value):
"""
Defines templates which are used to generate certain types of pages. When defining new value for the template
we have to use content of type 'str' (Python 2) or 'bytes' (Python 3).
At the moment we use these templates:
- ncx
- nav
- chapter
- cover
:Args:
- name: Name for the template
- value: Content for the template
"""
self.templates[name] = value
def get_template(self, name):
"""
Returns value for the template.
:Args:
- name: template name
:Returns:
Value of the template.
"""
return self.templates.get(name)
def add_prefix(self, name, uri):
"""
Appends custom prefix to be added to the content.opf document
>>> epub_book.add_prefix('bkterms', 'http://booktype.org/')
:Args:
- name: namespave name
- uri: URI for the namespace
"""
self.prefixes.append('%s: %s' % (name, uri))
|
aerkalov/ebooklib | ebooklib/epub.py | EpubBook.add_author | python | def add_author(self, author, file_as=None, role=None, uid='creator'):
"Add author for this document"
self.add_metadata('DC', 'creator', author, {'id': uid})
if file_as:
self.add_metadata(None, 'meta', file_as, {'refines': '#' + uid,
'property': 'file-as',
'scheme': 'marc:relators'})
if role:
self.add_metadata(None, 'meta', role, {'refines': '#' + uid,
'property': 'role',
'scheme': 'marc:relators'}) | Add author for this document | train | https://github.com/aerkalov/ebooklib/blob/305f2dd7f02923ffabf9586a5d16266113d00c4a/ebooklib/epub.py#L660-L672 | [
"def add_metadata(self, namespace, name, value, others=None):\n \"Add metadata\"\n\n if namespace in NAMESPACES:\n namespace = NAMESPACES[namespace]\n\n if namespace not in self.metadata:\n self.metadata[namespace] = {}\n\n if name not in self.metadata[namespace]:\n self.metadata[namespace][name] = []\n\n self.metadata[namespace][name].append((value, others))\n"
] | class EpubBook(object):
def __init__(self):
self.EPUB_VERSION = None
self.reset()
# we should have options here
def reset(self):
"Initialises all needed variables to default values"
self.metadata = {}
self.items = []
self.spine = []
self.guide = []
self.pages = []
self.toc = []
self.bindings = []
self.IDENTIFIER_ID = 'id'
self.FOLDER_NAME = 'EPUB'
self._id_html = 0
self._id_image = 0
self._id_static = 0
self.title = ''
self.language = 'en'
self.direction = None
self.templates = {
'ncx': NCX_XML,
'nav': NAV_XML,
'chapter': CHAPTER_XML,
'cover': COVER_XML
}
self.add_metadata('OPF', 'generator', '', {
'name': 'generator', 'content': 'Ebook-lib %s' % '.'.join([str(s) for s in VERSION])
})
# default to using a randomly-unique identifier if one is not specified manually
self.set_identifier(str(uuid.uuid4()))
# custom prefixes and namespaces to be set to the content.opf doc
self.prefixes = []
self.namespaces = {}
def set_identifier(self, uid):
"""
Sets unique id for this epub
:Args:
- uid: Value of unique identifier for this book
"""
self.uid = uid
self.set_unique_metadata('DC', 'identifier', self.uid, {'id': self.IDENTIFIER_ID})
def set_title(self, title):
"""
Set title. You can set multiple titles.
:Args:
- title: Title value
"""
self.title = title
self.add_metadata('DC', 'title', self.title)
def set_language(self, lang):
"""
Set language for this epub. You can set multiple languages. Specific items in the book can have
different language settings.
:Args:
- lang: Language code
"""
self.language = lang
self.add_metadata('DC', 'language', lang)
def set_direction(self, direction):
"""
:Args:
- direction: Options are "ltr", "rtl" and "default"
"""
self.direction = direction
def set_cover(self, file_name, content, create_page=True):
"""
Set cover and create cover document if needed.
:Args:
- file_name: file name of the cover page
- content: Content for the cover image
- create_page: Should cover page be defined. Defined as bool value (optional). Default value is True.
"""
# as it is now, it can only be called once
c0 = EpubCover(file_name=file_name)
c0.content = content
self.add_item(c0)
if create_page:
c1 = EpubCoverHtml(image_name=file_name)
self.add_item(c1)
self.add_metadata(None, 'meta', '', OrderedDict([('name', 'cover'), ('content', 'cover-img')]))
def add_metadata(self, namespace, name, value, others=None):
"Add metadata"
if namespace in NAMESPACES:
namespace = NAMESPACES[namespace]
if namespace not in self.metadata:
self.metadata[namespace] = {}
if name not in self.metadata[namespace]:
self.metadata[namespace][name] = []
self.metadata[namespace][name].append((value, others))
def get_metadata(self, namespace, name):
"Retrieve metadata"
if namespace in NAMESPACES:
namespace = NAMESPACES[namespace]
return self.metadata[namespace].get(name, [])
def set_unique_metadata(self, namespace, name, value, others=None):
"Add metadata if metadata with this identifier does not already exist, otherwise update existing metadata."
if namespace in NAMESPACES:
namespace = NAMESPACES[namespace]
if namespace in self.metadata and name in self.metadata[namespace]:
self.metadata[namespace][name] = [(value, others)]
else:
self.add_metadata(namespace, name, value, others)
def add_item(self, item):
"""
Add additional item to the book. If not defined, media type and chapter id will be defined
for the item.
:Args:
- item: Item instance
"""
if item.media_type == '':
(has_guessed, media_type) = guess_type(item.get_name().lower())
if has_guessed:
if media_type is not None:
item.media_type = media_type
else:
item.media_type = has_guessed
else:
item.media_type = 'application/octet-stream'
if not item.get_id():
# make chapter_, image_ and static_ configurable
if isinstance(item, EpubHtml):
item.id = 'chapter_%d' % self._id_html
self._id_html += 1
# If there's a page list, append it to the book's page list
self.pages += item.pages
elif isinstance(item, EpubImage):
item.id = 'image_%d' % self._id_image
self._id_image += 1
else:
item.id = 'static_%d' % self._id_image
self._id_image += 1
item.book = self
self.items.append(item)
return item
def get_item_with_id(self, uid):
"""
Returns item for defined UID.
>>> book.get_item_with_id('image_001')
:Args:
- uid: UID for the item
:Returns:
Returns item object. Returns None if nothing was found.
"""
for item in self.get_items():
if item.id == uid:
return item
return None
def get_item_with_href(self, href):
"""
Returns item for defined HREF.
>>> book.get_item_with_href('EPUB/document.xhtml')
:Args:
- href: HREF for the item we are searching for
:Returns:
Returns item object. Returns None if nothing was found.
"""
for item in self.get_items():
if item.get_name() == href:
return item
return None
def get_items(self):
"""
Returns all items attached to this book.
:Returns:
Returns all items as tuple.
"""
return (item for item in self.items)
def get_items_of_type(self, item_type):
"""
Returns all items of specified type.
>>> book.get_items_of_type(epub.ITEM_IMAGE)
:Args:
- item_type: Type for items we are searching for
:Returns:
Returns found items as tuple.
"""
return (item for item in self.items if item.get_type() == item_type)
def get_items_of_media_type(self, media_type):
"""
Returns all items of specified media type.
:Args:
- media_type: Media type for items we are searching for
:Returns:
Returns found items as tuple.
"""
return (item for item in self.items if item.media_type == media_type)
def set_template(self, name, value):
"""
Defines templates which are used to generate certain types of pages. When defining new value for the template
we have to use content of type 'str' (Python 2) or 'bytes' (Python 3).
At the moment we use these templates:
- ncx
- nav
- chapter
- cover
:Args:
- name: Name for the template
- value: Content for the template
"""
self.templates[name] = value
def get_template(self, name):
"""
Returns value for the template.
:Args:
- name: template name
:Returns:
Value of the template.
"""
return self.templates.get(name)
def add_prefix(self, name, uri):
"""
Appends custom prefix to be added to the content.opf document
>>> epub_book.add_prefix('bkterms', 'http://booktype.org/')
:Args:
- name: namespave name
- uri: URI for the namespace
"""
self.prefixes.append('%s: %s' % (name, uri))
|
aerkalov/ebooklib | ebooklib/epub.py | EpubBook.add_metadata | python | def add_metadata(self, namespace, name, value, others=None):
"Add metadata"
if namespace in NAMESPACES:
namespace = NAMESPACES[namespace]
if namespace not in self.metadata:
self.metadata[namespace] = {}
if name not in self.metadata[namespace]:
self.metadata[namespace][name] = []
self.metadata[namespace][name].append((value, others)) | Add metadata | train | https://github.com/aerkalov/ebooklib/blob/305f2dd7f02923ffabf9586a5d16266113d00c4a/ebooklib/epub.py#L674-L686 | null | class EpubBook(object):
def __init__(self):
self.EPUB_VERSION = None
self.reset()
# we should have options here
def reset(self):
"Initialises all needed variables to default values"
self.metadata = {}
self.items = []
self.spine = []
self.guide = []
self.pages = []
self.toc = []
self.bindings = []
self.IDENTIFIER_ID = 'id'
self.FOLDER_NAME = 'EPUB'
self._id_html = 0
self._id_image = 0
self._id_static = 0
self.title = ''
self.language = 'en'
self.direction = None
self.templates = {
'ncx': NCX_XML,
'nav': NAV_XML,
'chapter': CHAPTER_XML,
'cover': COVER_XML
}
self.add_metadata('OPF', 'generator', '', {
'name': 'generator', 'content': 'Ebook-lib %s' % '.'.join([str(s) for s in VERSION])
})
# default to using a randomly-unique identifier if one is not specified manually
self.set_identifier(str(uuid.uuid4()))
# custom prefixes and namespaces to be set to the content.opf doc
self.prefixes = []
self.namespaces = {}
def set_identifier(self, uid):
"""
Sets unique id for this epub
:Args:
- uid: Value of unique identifier for this book
"""
self.uid = uid
self.set_unique_metadata('DC', 'identifier', self.uid, {'id': self.IDENTIFIER_ID})
def set_title(self, title):
"""
Set title. You can set multiple titles.
:Args:
- title: Title value
"""
self.title = title
self.add_metadata('DC', 'title', self.title)
def set_language(self, lang):
"""
Set language for this epub. You can set multiple languages. Specific items in the book can have
different language settings.
:Args:
- lang: Language code
"""
self.language = lang
self.add_metadata('DC', 'language', lang)
def set_direction(self, direction):
"""
:Args:
- direction: Options are "ltr", "rtl" and "default"
"""
self.direction = direction
def set_cover(self, file_name, content, create_page=True):
"""
Set cover and create cover document if needed.
:Args:
- file_name: file name of the cover page
- content: Content for the cover image
- create_page: Should cover page be defined. Defined as bool value (optional). Default value is True.
"""
# as it is now, it can only be called once
c0 = EpubCover(file_name=file_name)
c0.content = content
self.add_item(c0)
if create_page:
c1 = EpubCoverHtml(image_name=file_name)
self.add_item(c1)
self.add_metadata(None, 'meta', '', OrderedDict([('name', 'cover'), ('content', 'cover-img')]))
def add_author(self, author, file_as=None, role=None, uid='creator'):
"Add author for this document"
self.add_metadata('DC', 'creator', author, {'id': uid})
if file_as:
self.add_metadata(None, 'meta', file_as, {'refines': '#' + uid,
'property': 'file-as',
'scheme': 'marc:relators'})
if role:
self.add_metadata(None, 'meta', role, {'refines': '#' + uid,
'property': 'role',
'scheme': 'marc:relators'})
def get_metadata(self, namespace, name):
"Retrieve metadata"
if namespace in NAMESPACES:
namespace = NAMESPACES[namespace]
return self.metadata[namespace].get(name, [])
def set_unique_metadata(self, namespace, name, value, others=None):
"Add metadata if metadata with this identifier does not already exist, otherwise update existing metadata."
if namespace in NAMESPACES:
namespace = NAMESPACES[namespace]
if namespace in self.metadata and name in self.metadata[namespace]:
self.metadata[namespace][name] = [(value, others)]
else:
self.add_metadata(namespace, name, value, others)
def add_item(self, item):
"""
Add additional item to the book. If not defined, media type and chapter id will be defined
for the item.
:Args:
- item: Item instance
"""
if item.media_type == '':
(has_guessed, media_type) = guess_type(item.get_name().lower())
if has_guessed:
if media_type is not None:
item.media_type = media_type
else:
item.media_type = has_guessed
else:
item.media_type = 'application/octet-stream'
if not item.get_id():
# make chapter_, image_ and static_ configurable
if isinstance(item, EpubHtml):
item.id = 'chapter_%d' % self._id_html
self._id_html += 1
# If there's a page list, append it to the book's page list
self.pages += item.pages
elif isinstance(item, EpubImage):
item.id = 'image_%d' % self._id_image
self._id_image += 1
else:
item.id = 'static_%d' % self._id_image
self._id_image += 1
item.book = self
self.items.append(item)
return item
def get_item_with_id(self, uid):
"""
Returns item for defined UID.
>>> book.get_item_with_id('image_001')
:Args:
- uid: UID for the item
:Returns:
Returns item object. Returns None if nothing was found.
"""
for item in self.get_items():
if item.id == uid:
return item
return None
def get_item_with_href(self, href):
"""
Returns item for defined HREF.
>>> book.get_item_with_href('EPUB/document.xhtml')
:Args:
- href: HREF for the item we are searching for
:Returns:
Returns item object. Returns None if nothing was found.
"""
for item in self.get_items():
if item.get_name() == href:
return item
return None
def get_items(self):
"""
Returns all items attached to this book.
:Returns:
Returns all items as tuple.
"""
return (item for item in self.items)
def get_items_of_type(self, item_type):
"""
Returns all items of specified type.
>>> book.get_items_of_type(epub.ITEM_IMAGE)
:Args:
- item_type: Type for items we are searching for
:Returns:
Returns found items as tuple.
"""
return (item for item in self.items if item.get_type() == item_type)
def get_items_of_media_type(self, media_type):
"""
Returns all items of specified media type.
:Args:
- media_type: Media type for items we are searching for
:Returns:
Returns found items as tuple.
"""
return (item for item in self.items if item.media_type == media_type)
def set_template(self, name, value):
"""
Defines templates which are used to generate certain types of pages. When defining new value for the template
we have to use content of type 'str' (Python 2) or 'bytes' (Python 3).
At the moment we use these templates:
- ncx
- nav
- chapter
- cover
:Args:
- name: Name for the template
- value: Content for the template
"""
self.templates[name] = value
def get_template(self, name):
"""
Returns value for the template.
:Args:
- name: template name
:Returns:
Value of the template.
"""
return self.templates.get(name)
def add_prefix(self, name, uri):
"""
Appends custom prefix to be added to the content.opf document
>>> epub_book.add_prefix('bkterms', 'http://booktype.org/')
:Args:
- name: namespave name
- uri: URI for the namespace
"""
self.prefixes.append('%s: %s' % (name, uri))
|
aerkalov/ebooklib | ebooklib/epub.py | EpubBook.get_metadata | python | def get_metadata(self, namespace, name):
"Retrieve metadata"
if namespace in NAMESPACES:
namespace = NAMESPACES[namespace]
return self.metadata[namespace].get(name, []) | Retrieve metadata | train | https://github.com/aerkalov/ebooklib/blob/305f2dd7f02923ffabf9586a5d16266113d00c4a/ebooklib/epub.py#L688-L694 | null | class EpubBook(object):
def __init__(self):
self.EPUB_VERSION = None
self.reset()
# we should have options here
def reset(self):
"Initialises all needed variables to default values"
self.metadata = {}
self.items = []
self.spine = []
self.guide = []
self.pages = []
self.toc = []
self.bindings = []
self.IDENTIFIER_ID = 'id'
self.FOLDER_NAME = 'EPUB'
self._id_html = 0
self._id_image = 0
self._id_static = 0
self.title = ''
self.language = 'en'
self.direction = None
self.templates = {
'ncx': NCX_XML,
'nav': NAV_XML,
'chapter': CHAPTER_XML,
'cover': COVER_XML
}
self.add_metadata('OPF', 'generator', '', {
'name': 'generator', 'content': 'Ebook-lib %s' % '.'.join([str(s) for s in VERSION])
})
# default to using a randomly-unique identifier if one is not specified manually
self.set_identifier(str(uuid.uuid4()))
# custom prefixes and namespaces to be set to the content.opf doc
self.prefixes = []
self.namespaces = {}
def set_identifier(self, uid):
"""
Sets unique id for this epub
:Args:
- uid: Value of unique identifier for this book
"""
self.uid = uid
self.set_unique_metadata('DC', 'identifier', self.uid, {'id': self.IDENTIFIER_ID})
def set_title(self, title):
"""
Set title. You can set multiple titles.
:Args:
- title: Title value
"""
self.title = title
self.add_metadata('DC', 'title', self.title)
def set_language(self, lang):
"""
Set language for this epub. You can set multiple languages. Specific items in the book can have
different language settings.
:Args:
- lang: Language code
"""
self.language = lang
self.add_metadata('DC', 'language', lang)
def set_direction(self, direction):
"""
:Args:
- direction: Options are "ltr", "rtl" and "default"
"""
self.direction = direction
def set_cover(self, file_name, content, create_page=True):
"""
Set cover and create cover document if needed.
:Args:
- file_name: file name of the cover page
- content: Content for the cover image
- create_page: Should cover page be defined. Defined as bool value (optional). Default value is True.
"""
# as it is now, it can only be called once
c0 = EpubCover(file_name=file_name)
c0.content = content
self.add_item(c0)
if create_page:
c1 = EpubCoverHtml(image_name=file_name)
self.add_item(c1)
self.add_metadata(None, 'meta', '', OrderedDict([('name', 'cover'), ('content', 'cover-img')]))
def add_author(self, author, file_as=None, role=None, uid='creator'):
"Add author for this document"
self.add_metadata('DC', 'creator', author, {'id': uid})
if file_as:
self.add_metadata(None, 'meta', file_as, {'refines': '#' + uid,
'property': 'file-as',
'scheme': 'marc:relators'})
if role:
self.add_metadata(None, 'meta', role, {'refines': '#' + uid,
'property': 'role',
'scheme': 'marc:relators'})
def add_metadata(self, namespace, name, value, others=None):
"Add metadata"
if namespace in NAMESPACES:
namespace = NAMESPACES[namespace]
if namespace not in self.metadata:
self.metadata[namespace] = {}
if name not in self.metadata[namespace]:
self.metadata[namespace][name] = []
self.metadata[namespace][name].append((value, others))
def set_unique_metadata(self, namespace, name, value, others=None):
"Add metadata if metadata with this identifier does not already exist, otherwise update existing metadata."
if namespace in NAMESPACES:
namespace = NAMESPACES[namespace]
if namespace in self.metadata and name in self.metadata[namespace]:
self.metadata[namespace][name] = [(value, others)]
else:
self.add_metadata(namespace, name, value, others)
def add_item(self, item):
"""
Add additional item to the book. If not defined, media type and chapter id will be defined
for the item.
:Args:
- item: Item instance
"""
if item.media_type == '':
(has_guessed, media_type) = guess_type(item.get_name().lower())
if has_guessed:
if media_type is not None:
item.media_type = media_type
else:
item.media_type = has_guessed
else:
item.media_type = 'application/octet-stream'
if not item.get_id():
# make chapter_, image_ and static_ configurable
if isinstance(item, EpubHtml):
item.id = 'chapter_%d' % self._id_html
self._id_html += 1
# If there's a page list, append it to the book's page list
self.pages += item.pages
elif isinstance(item, EpubImage):
item.id = 'image_%d' % self._id_image
self._id_image += 1
else:
item.id = 'static_%d' % self._id_image
self._id_image += 1
item.book = self
self.items.append(item)
return item
def get_item_with_id(self, uid):
"""
Returns item for defined UID.
>>> book.get_item_with_id('image_001')
:Args:
- uid: UID for the item
:Returns:
Returns item object. Returns None if nothing was found.
"""
for item in self.get_items():
if item.id == uid:
return item
return None
def get_item_with_href(self, href):
"""
Returns item for defined HREF.
>>> book.get_item_with_href('EPUB/document.xhtml')
:Args:
- href: HREF for the item we are searching for
:Returns:
Returns item object. Returns None if nothing was found.
"""
for item in self.get_items():
if item.get_name() == href:
return item
return None
def get_items(self):
"""
Returns all items attached to this book.
:Returns:
Returns all items as tuple.
"""
return (item for item in self.items)
def get_items_of_type(self, item_type):
"""
Returns all items of specified type.
>>> book.get_items_of_type(epub.ITEM_IMAGE)
:Args:
- item_type: Type for items we are searching for
:Returns:
Returns found items as tuple.
"""
return (item for item in self.items if item.get_type() == item_type)
def get_items_of_media_type(self, media_type):
"""
Returns all items of specified media type.
:Args:
- media_type: Media type for items we are searching for
:Returns:
Returns found items as tuple.
"""
return (item for item in self.items if item.media_type == media_type)
def set_template(self, name, value):
"""
Defines templates which are used to generate certain types of pages. When defining new value for the template
we have to use content of type 'str' (Python 2) or 'bytes' (Python 3).
At the moment we use these templates:
- ncx
- nav
- chapter
- cover
:Args:
- name: Name for the template
- value: Content for the template
"""
self.templates[name] = value
def get_template(self, name):
"""
Returns value for the template.
:Args:
- name: template name
:Returns:
Value of the template.
"""
return self.templates.get(name)
def add_prefix(self, name, uri):
"""
Appends custom prefix to be added to the content.opf document
>>> epub_book.add_prefix('bkterms', 'http://booktype.org/')
:Args:
- name: namespave name
- uri: URI for the namespace
"""
self.prefixes.append('%s: %s' % (name, uri))
|
aerkalov/ebooklib | ebooklib/epub.py | EpubBook.add_item | python | def add_item(self, item):
if item.media_type == '':
(has_guessed, media_type) = guess_type(item.get_name().lower())
if has_guessed:
if media_type is not None:
item.media_type = media_type
else:
item.media_type = has_guessed
else:
item.media_type = 'application/octet-stream'
if not item.get_id():
# make chapter_, image_ and static_ configurable
if isinstance(item, EpubHtml):
item.id = 'chapter_%d' % self._id_html
self._id_html += 1
# If there's a page list, append it to the book's page list
self.pages += item.pages
elif isinstance(item, EpubImage):
item.id = 'image_%d' % self._id_image
self._id_image += 1
else:
item.id = 'static_%d' % self._id_image
self._id_image += 1
item.book = self
self.items.append(item)
return item | Add additional item to the book. If not defined, media type and chapter id will be defined
for the item.
:Args:
- item: Item instance | train | https://github.com/aerkalov/ebooklib/blob/305f2dd7f02923ffabf9586a5d16266113d00c4a/ebooklib/epub.py#L707-L743 | [
"def guess_type(extenstion):\n global mimetype_initialised\n\n if not mimetype_initialised:\n mimetypes.init()\n mimetypes.add_type('application/xhtml+xml', '.xhtml')\n mimetype_initialised = True\n\n return mimetypes.guess_type(extenstion)\n",
"def get_id(self):\n \"\"\"\n Returns unique identifier for this item.\n\n :Returns:\n Returns uid number as string.\n \"\"\"\n return self.id\n",
"def get_name(self):\n \"\"\"\n Returns name for this item. By default it is always file name but it does not have to be.\n\n :Returns:\n Returns file name for this item.\n \"\"\"\n return self.file_name\n"
] | class EpubBook(object):
def __init__(self):
self.EPUB_VERSION = None
self.reset()
# we should have options here
def reset(self):
"Initialises all needed variables to default values"
self.metadata = {}
self.items = []
self.spine = []
self.guide = []
self.pages = []
self.toc = []
self.bindings = []
self.IDENTIFIER_ID = 'id'
self.FOLDER_NAME = 'EPUB'
self._id_html = 0
self._id_image = 0
self._id_static = 0
self.title = ''
self.language = 'en'
self.direction = None
self.templates = {
'ncx': NCX_XML,
'nav': NAV_XML,
'chapter': CHAPTER_XML,
'cover': COVER_XML
}
self.add_metadata('OPF', 'generator', '', {
'name': 'generator', 'content': 'Ebook-lib %s' % '.'.join([str(s) for s in VERSION])
})
# default to using a randomly-unique identifier if one is not specified manually
self.set_identifier(str(uuid.uuid4()))
# custom prefixes and namespaces to be set to the content.opf doc
self.prefixes = []
self.namespaces = {}
def set_identifier(self, uid):
"""
Sets unique id for this epub
:Args:
- uid: Value of unique identifier for this book
"""
self.uid = uid
self.set_unique_metadata('DC', 'identifier', self.uid, {'id': self.IDENTIFIER_ID})
def set_title(self, title):
"""
Set title. You can set multiple titles.
:Args:
- title: Title value
"""
self.title = title
self.add_metadata('DC', 'title', self.title)
def set_language(self, lang):
"""
Set language for this epub. You can set multiple languages. Specific items in the book can have
different language settings.
:Args:
- lang: Language code
"""
self.language = lang
self.add_metadata('DC', 'language', lang)
def set_direction(self, direction):
"""
:Args:
- direction: Options are "ltr", "rtl" and "default"
"""
self.direction = direction
def set_cover(self, file_name, content, create_page=True):
"""
Set cover and create cover document if needed.
:Args:
- file_name: file name of the cover page
- content: Content for the cover image
- create_page: Should cover page be defined. Defined as bool value (optional). Default value is True.
"""
# as it is now, it can only be called once
c0 = EpubCover(file_name=file_name)
c0.content = content
self.add_item(c0)
if create_page:
c1 = EpubCoverHtml(image_name=file_name)
self.add_item(c1)
self.add_metadata(None, 'meta', '', OrderedDict([('name', 'cover'), ('content', 'cover-img')]))
def add_author(self, author, file_as=None, role=None, uid='creator'):
"Add author for this document"
self.add_metadata('DC', 'creator', author, {'id': uid})
if file_as:
self.add_metadata(None, 'meta', file_as, {'refines': '#' + uid,
'property': 'file-as',
'scheme': 'marc:relators'})
if role:
self.add_metadata(None, 'meta', role, {'refines': '#' + uid,
'property': 'role',
'scheme': 'marc:relators'})
def add_metadata(self, namespace, name, value, others=None):
"Add metadata"
if namespace in NAMESPACES:
namespace = NAMESPACES[namespace]
if namespace not in self.metadata:
self.metadata[namespace] = {}
if name not in self.metadata[namespace]:
self.metadata[namespace][name] = []
self.metadata[namespace][name].append((value, others))
def get_metadata(self, namespace, name):
"Retrieve metadata"
if namespace in NAMESPACES:
namespace = NAMESPACES[namespace]
return self.metadata[namespace].get(name, [])
def set_unique_metadata(self, namespace, name, value, others=None):
"Add metadata if metadata with this identifier does not already exist, otherwise update existing metadata."
if namespace in NAMESPACES:
namespace = NAMESPACES[namespace]
if namespace in self.metadata and name in self.metadata[namespace]:
self.metadata[namespace][name] = [(value, others)]
else:
self.add_metadata(namespace, name, value, others)
def get_item_with_id(self, uid):
"""
Returns item for defined UID.
>>> book.get_item_with_id('image_001')
:Args:
- uid: UID for the item
:Returns:
Returns item object. Returns None if nothing was found.
"""
for item in self.get_items():
if item.id == uid:
return item
return None
def get_item_with_href(self, href):
"""
Returns item for defined HREF.
>>> book.get_item_with_href('EPUB/document.xhtml')
:Args:
- href: HREF for the item we are searching for
:Returns:
Returns item object. Returns None if nothing was found.
"""
for item in self.get_items():
if item.get_name() == href:
return item
return None
def get_items(self):
"""
Returns all items attached to this book.
:Returns:
Returns all items as tuple.
"""
return (item for item in self.items)
def get_items_of_type(self, item_type):
"""
Returns all items of specified type.
>>> book.get_items_of_type(epub.ITEM_IMAGE)
:Args:
- item_type: Type for items we are searching for
:Returns:
Returns found items as tuple.
"""
return (item for item in self.items if item.get_type() == item_type)
def get_items_of_media_type(self, media_type):
"""
Returns all items of specified media type.
:Args:
- media_type: Media type for items we are searching for
:Returns:
Returns found items as tuple.
"""
return (item for item in self.items if item.media_type == media_type)
def set_template(self, name, value):
"""
Defines templates which are used to generate certain types of pages. When defining new value for the template
we have to use content of type 'str' (Python 2) or 'bytes' (Python 3).
At the moment we use these templates:
- ncx
- nav
- chapter
- cover
:Args:
- name: Name for the template
- value: Content for the template
"""
self.templates[name] = value
def get_template(self, name):
"""
Returns value for the template.
:Args:
- name: template name
:Returns:
Value of the template.
"""
return self.templates.get(name)
def add_prefix(self, name, uri):
"""
Appends custom prefix to be added to the content.opf document
>>> epub_book.add_prefix('bkterms', 'http://booktype.org/')
:Args:
- name: namespave name
- uri: URI for the namespace
"""
self.prefixes.append('%s: %s' % (name, uri))
|
aerkalov/ebooklib | ebooklib/epub.py | EpubBook.get_item_with_id | python | def get_item_with_id(self, uid):
for item in self.get_items():
if item.id == uid:
return item
return None | Returns item for defined UID.
>>> book.get_item_with_id('image_001')
:Args:
- uid: UID for the item
:Returns:
Returns item object. Returns None if nothing was found. | train | https://github.com/aerkalov/ebooklib/blob/305f2dd7f02923ffabf9586a5d16266113d00c4a/ebooklib/epub.py#L745-L761 | [
"def get_items(self):\n \"\"\"\n Returns all items attached to this book.\n\n :Returns:\n Returns all items as tuple.\n \"\"\"\n return (item for item in self.items)\n"
] | class EpubBook(object):
def __init__(self):
self.EPUB_VERSION = None
self.reset()
# we should have options here
def reset(self):
"Initialises all needed variables to default values"
self.metadata = {}
self.items = []
self.spine = []
self.guide = []
self.pages = []
self.toc = []
self.bindings = []
self.IDENTIFIER_ID = 'id'
self.FOLDER_NAME = 'EPUB'
self._id_html = 0
self._id_image = 0
self._id_static = 0
self.title = ''
self.language = 'en'
self.direction = None
self.templates = {
'ncx': NCX_XML,
'nav': NAV_XML,
'chapter': CHAPTER_XML,
'cover': COVER_XML
}
self.add_metadata('OPF', 'generator', '', {
'name': 'generator', 'content': 'Ebook-lib %s' % '.'.join([str(s) for s in VERSION])
})
# default to using a randomly-unique identifier if one is not specified manually
self.set_identifier(str(uuid.uuid4()))
# custom prefixes and namespaces to be set to the content.opf doc
self.prefixes = []
self.namespaces = {}
def set_identifier(self, uid):
"""
Sets unique id for this epub
:Args:
- uid: Value of unique identifier for this book
"""
self.uid = uid
self.set_unique_metadata('DC', 'identifier', self.uid, {'id': self.IDENTIFIER_ID})
def set_title(self, title):
"""
Set title. You can set multiple titles.
:Args:
- title: Title value
"""
self.title = title
self.add_metadata('DC', 'title', self.title)
def set_language(self, lang):
"""
Set language for this epub. You can set multiple languages. Specific items in the book can have
different language settings.
:Args:
- lang: Language code
"""
self.language = lang
self.add_metadata('DC', 'language', lang)
def set_direction(self, direction):
"""
:Args:
- direction: Options are "ltr", "rtl" and "default"
"""
self.direction = direction
def set_cover(self, file_name, content, create_page=True):
"""
Set cover and create cover document if needed.
:Args:
- file_name: file name of the cover page
- content: Content for the cover image
- create_page: Should cover page be defined. Defined as bool value (optional). Default value is True.
"""
# as it is now, it can only be called once
c0 = EpubCover(file_name=file_name)
c0.content = content
self.add_item(c0)
if create_page:
c1 = EpubCoverHtml(image_name=file_name)
self.add_item(c1)
self.add_metadata(None, 'meta', '', OrderedDict([('name', 'cover'), ('content', 'cover-img')]))
def add_author(self, author, file_as=None, role=None, uid='creator'):
"Add author for this document"
self.add_metadata('DC', 'creator', author, {'id': uid})
if file_as:
self.add_metadata(None, 'meta', file_as, {'refines': '#' + uid,
'property': 'file-as',
'scheme': 'marc:relators'})
if role:
self.add_metadata(None, 'meta', role, {'refines': '#' + uid,
'property': 'role',
'scheme': 'marc:relators'})
def add_metadata(self, namespace, name, value, others=None):
"Add metadata"
if namespace in NAMESPACES:
namespace = NAMESPACES[namespace]
if namespace not in self.metadata:
self.metadata[namespace] = {}
if name not in self.metadata[namespace]:
self.metadata[namespace][name] = []
self.metadata[namespace][name].append((value, others))
def get_metadata(self, namespace, name):
"Retrieve metadata"
if namespace in NAMESPACES:
namespace = NAMESPACES[namespace]
return self.metadata[namespace].get(name, [])
def set_unique_metadata(self, namespace, name, value, others=None):
"Add metadata if metadata with this identifier does not already exist, otherwise update existing metadata."
if namespace in NAMESPACES:
namespace = NAMESPACES[namespace]
if namespace in self.metadata and name in self.metadata[namespace]:
self.metadata[namespace][name] = [(value, others)]
else:
self.add_metadata(namespace, name, value, others)
def add_item(self, item):
"""
Add additional item to the book. If not defined, media type and chapter id will be defined
for the item.
:Args:
- item: Item instance
"""
if item.media_type == '':
(has_guessed, media_type) = guess_type(item.get_name().lower())
if has_guessed:
if media_type is not None:
item.media_type = media_type
else:
item.media_type = has_guessed
else:
item.media_type = 'application/octet-stream'
if not item.get_id():
# make chapter_, image_ and static_ configurable
if isinstance(item, EpubHtml):
item.id = 'chapter_%d' % self._id_html
self._id_html += 1
# If there's a page list, append it to the book's page list
self.pages += item.pages
elif isinstance(item, EpubImage):
item.id = 'image_%d' % self._id_image
self._id_image += 1
else:
item.id = 'static_%d' % self._id_image
self._id_image += 1
item.book = self
self.items.append(item)
return item
def get_item_with_href(self, href):
"""
Returns item for defined HREF.
>>> book.get_item_with_href('EPUB/document.xhtml')
:Args:
- href: HREF for the item we are searching for
:Returns:
Returns item object. Returns None if nothing was found.
"""
for item in self.get_items():
if item.get_name() == href:
return item
return None
def get_items(self):
"""
Returns all items attached to this book.
:Returns:
Returns all items as tuple.
"""
return (item for item in self.items)
def get_items_of_type(self, item_type):
"""
Returns all items of specified type.
>>> book.get_items_of_type(epub.ITEM_IMAGE)
:Args:
- item_type: Type for items we are searching for
:Returns:
Returns found items as tuple.
"""
return (item for item in self.items if item.get_type() == item_type)
def get_items_of_media_type(self, media_type):
"""
Returns all items of specified media type.
:Args:
- media_type: Media type for items we are searching for
:Returns:
Returns found items as tuple.
"""
return (item for item in self.items if item.media_type == media_type)
def set_template(self, name, value):
"""
Defines templates which are used to generate certain types of pages. When defining new value for the template
we have to use content of type 'str' (Python 2) or 'bytes' (Python 3).
At the moment we use these templates:
- ncx
- nav
- chapter
- cover
:Args:
- name: Name for the template
- value: Content for the template
"""
self.templates[name] = value
def get_template(self, name):
"""
Returns value for the template.
:Args:
- name: template name
:Returns:
Value of the template.
"""
return self.templates.get(name)
def add_prefix(self, name, uri):
"""
Appends custom prefix to be added to the content.opf document
>>> epub_book.add_prefix('bkterms', 'http://booktype.org/')
:Args:
- name: namespave name
- uri: URI for the namespace
"""
self.prefixes.append('%s: %s' % (name, uri))
|
aerkalov/ebooklib | ebooklib/epub.py | EpubBook.get_item_with_href | python | def get_item_with_href(self, href):
for item in self.get_items():
if item.get_name() == href:
return item
return None | Returns item for defined HREF.
>>> book.get_item_with_href('EPUB/document.xhtml')
:Args:
- href: HREF for the item we are searching for
:Returns:
Returns item object. Returns None if nothing was found. | train | https://github.com/aerkalov/ebooklib/blob/305f2dd7f02923ffabf9586a5d16266113d00c4a/ebooklib/epub.py#L763-L779 | [
"def get_items(self):\n \"\"\"\n Returns all items attached to this book.\n\n :Returns:\n Returns all items as tuple.\n \"\"\"\n return (item for item in self.items)\n"
] | class EpubBook(object):
def __init__(self):
self.EPUB_VERSION = None
self.reset()
# we should have options here
def reset(self):
"Initialises all needed variables to default values"
self.metadata = {}
self.items = []
self.spine = []
self.guide = []
self.pages = []
self.toc = []
self.bindings = []
self.IDENTIFIER_ID = 'id'
self.FOLDER_NAME = 'EPUB'
self._id_html = 0
self._id_image = 0
self._id_static = 0
self.title = ''
self.language = 'en'
self.direction = None
self.templates = {
'ncx': NCX_XML,
'nav': NAV_XML,
'chapter': CHAPTER_XML,
'cover': COVER_XML
}
self.add_metadata('OPF', 'generator', '', {
'name': 'generator', 'content': 'Ebook-lib %s' % '.'.join([str(s) for s in VERSION])
})
# default to using a randomly-unique identifier if one is not specified manually
self.set_identifier(str(uuid.uuid4()))
# custom prefixes and namespaces to be set to the content.opf doc
self.prefixes = []
self.namespaces = {}
def set_identifier(self, uid):
"""
Sets unique id for this epub
:Args:
- uid: Value of unique identifier for this book
"""
self.uid = uid
self.set_unique_metadata('DC', 'identifier', self.uid, {'id': self.IDENTIFIER_ID})
def set_title(self, title):
"""
Set title. You can set multiple titles.
:Args:
- title: Title value
"""
self.title = title
self.add_metadata('DC', 'title', self.title)
def set_language(self, lang):
"""
Set language for this epub. You can set multiple languages. Specific items in the book can have
different language settings.
:Args:
- lang: Language code
"""
self.language = lang
self.add_metadata('DC', 'language', lang)
def set_direction(self, direction):
"""
:Args:
- direction: Options are "ltr", "rtl" and "default"
"""
self.direction = direction
def set_cover(self, file_name, content, create_page=True):
"""
Set cover and create cover document if needed.
:Args:
- file_name: file name of the cover page
- content: Content for the cover image
- create_page: Should cover page be defined. Defined as bool value (optional). Default value is True.
"""
# as it is now, it can only be called once
c0 = EpubCover(file_name=file_name)
c0.content = content
self.add_item(c0)
if create_page:
c1 = EpubCoverHtml(image_name=file_name)
self.add_item(c1)
self.add_metadata(None, 'meta', '', OrderedDict([('name', 'cover'), ('content', 'cover-img')]))
def add_author(self, author, file_as=None, role=None, uid='creator'):
"Add author for this document"
self.add_metadata('DC', 'creator', author, {'id': uid})
if file_as:
self.add_metadata(None, 'meta', file_as, {'refines': '#' + uid,
'property': 'file-as',
'scheme': 'marc:relators'})
if role:
self.add_metadata(None, 'meta', role, {'refines': '#' + uid,
'property': 'role',
'scheme': 'marc:relators'})
def add_metadata(self, namespace, name, value, others=None):
"Add metadata"
if namespace in NAMESPACES:
namespace = NAMESPACES[namespace]
if namespace not in self.metadata:
self.metadata[namespace] = {}
if name not in self.metadata[namespace]:
self.metadata[namespace][name] = []
self.metadata[namespace][name].append((value, others))
def get_metadata(self, namespace, name):
"Retrieve metadata"
if namespace in NAMESPACES:
namespace = NAMESPACES[namespace]
return self.metadata[namespace].get(name, [])
def set_unique_metadata(self, namespace, name, value, others=None):
"Add metadata if metadata with this identifier does not already exist, otherwise update existing metadata."
if namespace in NAMESPACES:
namespace = NAMESPACES[namespace]
if namespace in self.metadata and name in self.metadata[namespace]:
self.metadata[namespace][name] = [(value, others)]
else:
self.add_metadata(namespace, name, value, others)
def add_item(self, item):
"""
Add additional item to the book. If not defined, media type and chapter id will be defined
for the item.
:Args:
- item: Item instance
"""
if item.media_type == '':
(has_guessed, media_type) = guess_type(item.get_name().lower())
if has_guessed:
if media_type is not None:
item.media_type = media_type
else:
item.media_type = has_guessed
else:
item.media_type = 'application/octet-stream'
if not item.get_id():
# make chapter_, image_ and static_ configurable
if isinstance(item, EpubHtml):
item.id = 'chapter_%d' % self._id_html
self._id_html += 1
# If there's a page list, append it to the book's page list
self.pages += item.pages
elif isinstance(item, EpubImage):
item.id = 'image_%d' % self._id_image
self._id_image += 1
else:
item.id = 'static_%d' % self._id_image
self._id_image += 1
item.book = self
self.items.append(item)
return item
def get_item_with_id(self, uid):
"""
Returns item for defined UID.
>>> book.get_item_with_id('image_001')
:Args:
- uid: UID for the item
:Returns:
Returns item object. Returns None if nothing was found.
"""
for item in self.get_items():
if item.id == uid:
return item
return None
def get_items(self):
"""
Returns all items attached to this book.
:Returns:
Returns all items as tuple.
"""
return (item for item in self.items)
def get_items_of_type(self, item_type):
"""
Returns all items of specified type.
>>> book.get_items_of_type(epub.ITEM_IMAGE)
:Args:
- item_type: Type for items we are searching for
:Returns:
Returns found items as tuple.
"""
return (item for item in self.items if item.get_type() == item_type)
def get_items_of_media_type(self, media_type):
"""
Returns all items of specified media type.
:Args:
- media_type: Media type for items we are searching for
:Returns:
Returns found items as tuple.
"""
return (item for item in self.items if item.media_type == media_type)
def set_template(self, name, value):
"""
Defines templates which are used to generate certain types of pages. When defining new value for the template
we have to use content of type 'str' (Python 2) or 'bytes' (Python 3).
At the moment we use these templates:
- ncx
- nav
- chapter
- cover
:Args:
- name: Name for the template
- value: Content for the template
"""
self.templates[name] = value
def get_template(self, name):
"""
Returns value for the template.
:Args:
- name: template name
:Returns:
Value of the template.
"""
return self.templates.get(name)
def add_prefix(self, name, uri):
"""
Appends custom prefix to be added to the content.opf document
>>> epub_book.add_prefix('bkterms', 'http://booktype.org/')
:Args:
- name: namespave name
- uri: URI for the namespace
"""
self.prefixes.append('%s: %s' % (name, uri))
|
aerkalov/ebooklib | ebooklib/epub.py | EpubBook.get_items_of_type | python | def get_items_of_type(self, item_type):
return (item for item in self.items if item.get_type() == item_type) | Returns all items of specified type.
>>> book.get_items_of_type(epub.ITEM_IMAGE)
:Args:
- item_type: Type for items we are searching for
:Returns:
Returns found items as tuple. | train | https://github.com/aerkalov/ebooklib/blob/305f2dd7f02923ffabf9586a5d16266113d00c4a/ebooklib/epub.py#L790-L802 | null | class EpubBook(object):
def __init__(self):
self.EPUB_VERSION = None
self.reset()
# we should have options here
def reset(self):
"Initialises all needed variables to default values"
self.metadata = {}
self.items = []
self.spine = []
self.guide = []
self.pages = []
self.toc = []
self.bindings = []
self.IDENTIFIER_ID = 'id'
self.FOLDER_NAME = 'EPUB'
self._id_html = 0
self._id_image = 0
self._id_static = 0
self.title = ''
self.language = 'en'
self.direction = None
self.templates = {
'ncx': NCX_XML,
'nav': NAV_XML,
'chapter': CHAPTER_XML,
'cover': COVER_XML
}
self.add_metadata('OPF', 'generator', '', {
'name': 'generator', 'content': 'Ebook-lib %s' % '.'.join([str(s) for s in VERSION])
})
# default to using a randomly-unique identifier if one is not specified manually
self.set_identifier(str(uuid.uuid4()))
# custom prefixes and namespaces to be set to the content.opf doc
self.prefixes = []
self.namespaces = {}
def set_identifier(self, uid):
"""
Sets unique id for this epub
:Args:
- uid: Value of unique identifier for this book
"""
self.uid = uid
self.set_unique_metadata('DC', 'identifier', self.uid, {'id': self.IDENTIFIER_ID})
def set_title(self, title):
"""
Set title. You can set multiple titles.
:Args:
- title: Title value
"""
self.title = title
self.add_metadata('DC', 'title', self.title)
def set_language(self, lang):
"""
Set language for this epub. You can set multiple languages. Specific items in the book can have
different language settings.
:Args:
- lang: Language code
"""
self.language = lang
self.add_metadata('DC', 'language', lang)
def set_direction(self, direction):
"""
:Args:
- direction: Options are "ltr", "rtl" and "default"
"""
self.direction = direction
def set_cover(self, file_name, content, create_page=True):
"""
Set cover and create cover document if needed.
:Args:
- file_name: file name of the cover page
- content: Content for the cover image
- create_page: Should cover page be defined. Defined as bool value (optional). Default value is True.
"""
# as it is now, it can only be called once
c0 = EpubCover(file_name=file_name)
c0.content = content
self.add_item(c0)
if create_page:
c1 = EpubCoverHtml(image_name=file_name)
self.add_item(c1)
self.add_metadata(None, 'meta', '', OrderedDict([('name', 'cover'), ('content', 'cover-img')]))
def add_author(self, author, file_as=None, role=None, uid='creator'):
"Add author for this document"
self.add_metadata('DC', 'creator', author, {'id': uid})
if file_as:
self.add_metadata(None, 'meta', file_as, {'refines': '#' + uid,
'property': 'file-as',
'scheme': 'marc:relators'})
if role:
self.add_metadata(None, 'meta', role, {'refines': '#' + uid,
'property': 'role',
'scheme': 'marc:relators'})
def add_metadata(self, namespace, name, value, others=None):
"Add metadata"
if namespace in NAMESPACES:
namespace = NAMESPACES[namespace]
if namespace not in self.metadata:
self.metadata[namespace] = {}
if name not in self.metadata[namespace]:
self.metadata[namespace][name] = []
self.metadata[namespace][name].append((value, others))
def get_metadata(self, namespace, name):
"Retrieve metadata"
if namespace in NAMESPACES:
namespace = NAMESPACES[namespace]
return self.metadata[namespace].get(name, [])
def set_unique_metadata(self, namespace, name, value, others=None):
"Add metadata if metadata with this identifier does not already exist, otherwise update existing metadata."
if namespace in NAMESPACES:
namespace = NAMESPACES[namespace]
if namespace in self.metadata and name in self.metadata[namespace]:
self.metadata[namespace][name] = [(value, others)]
else:
self.add_metadata(namespace, name, value, others)
def add_item(self, item):
"""
Add additional item to the book. If not defined, media type and chapter id will be defined
for the item.
:Args:
- item: Item instance
"""
if item.media_type == '':
(has_guessed, media_type) = guess_type(item.get_name().lower())
if has_guessed:
if media_type is not None:
item.media_type = media_type
else:
item.media_type = has_guessed
else:
item.media_type = 'application/octet-stream'
if not item.get_id():
# make chapter_, image_ and static_ configurable
if isinstance(item, EpubHtml):
item.id = 'chapter_%d' % self._id_html
self._id_html += 1
# If there's a page list, append it to the book's page list
self.pages += item.pages
elif isinstance(item, EpubImage):
item.id = 'image_%d' % self._id_image
self._id_image += 1
else:
item.id = 'static_%d' % self._id_image
self._id_image += 1
item.book = self
self.items.append(item)
return item
def get_item_with_id(self, uid):
"""
Returns item for defined UID.
>>> book.get_item_with_id('image_001')
:Args:
- uid: UID for the item
:Returns:
Returns item object. Returns None if nothing was found.
"""
for item in self.get_items():
if item.id == uid:
return item
return None
def get_item_with_href(self, href):
"""
Returns item for defined HREF.
>>> book.get_item_with_href('EPUB/document.xhtml')
:Args:
- href: HREF for the item we are searching for
:Returns:
Returns item object. Returns None if nothing was found.
"""
for item in self.get_items():
if item.get_name() == href:
return item
return None
def get_items(self):
"""
Returns all items attached to this book.
:Returns:
Returns all items as tuple.
"""
return (item for item in self.items)
def get_items_of_media_type(self, media_type):
"""
Returns all items of specified media type.
:Args:
- media_type: Media type for items we are searching for
:Returns:
Returns found items as tuple.
"""
return (item for item in self.items if item.media_type == media_type)
def set_template(self, name, value):
"""
Defines templates which are used to generate certain types of pages. When defining new value for the template
we have to use content of type 'str' (Python 2) or 'bytes' (Python 3).
At the moment we use these templates:
- ncx
- nav
- chapter
- cover
:Args:
- name: Name for the template
- value: Content for the template
"""
self.templates[name] = value
def get_template(self, name):
"""
Returns value for the template.
:Args:
- name: template name
:Returns:
Value of the template.
"""
return self.templates.get(name)
def add_prefix(self, name, uri):
"""
Appends custom prefix to be added to the content.opf document
>>> epub_book.add_prefix('bkterms', 'http://booktype.org/')
:Args:
- name: namespave name
- uri: URI for the namespace
"""
self.prefixes.append('%s: %s' % (name, uri))
|
aerkalov/ebooklib | ebooklib/epub.py | EpubBook.get_items_of_media_type | python | def get_items_of_media_type(self, media_type):
return (item for item in self.items if item.media_type == media_type) | Returns all items of specified media type.
:Args:
- media_type: Media type for items we are searching for
:Returns:
Returns found items as tuple. | train | https://github.com/aerkalov/ebooklib/blob/305f2dd7f02923ffabf9586a5d16266113d00c4a/ebooklib/epub.py#L804-L814 | null | class EpubBook(object):
def __init__(self):
self.EPUB_VERSION = None
self.reset()
# we should have options here
def reset(self):
"Initialises all needed variables to default values"
self.metadata = {}
self.items = []
self.spine = []
self.guide = []
self.pages = []
self.toc = []
self.bindings = []
self.IDENTIFIER_ID = 'id'
self.FOLDER_NAME = 'EPUB'
self._id_html = 0
self._id_image = 0
self._id_static = 0
self.title = ''
self.language = 'en'
self.direction = None
self.templates = {
'ncx': NCX_XML,
'nav': NAV_XML,
'chapter': CHAPTER_XML,
'cover': COVER_XML
}
self.add_metadata('OPF', 'generator', '', {
'name': 'generator', 'content': 'Ebook-lib %s' % '.'.join([str(s) for s in VERSION])
})
# default to using a randomly-unique identifier if one is not specified manually
self.set_identifier(str(uuid.uuid4()))
# custom prefixes and namespaces to be set to the content.opf doc
self.prefixes = []
self.namespaces = {}
def set_identifier(self, uid):
"""
Sets unique id for this epub
:Args:
- uid: Value of unique identifier for this book
"""
self.uid = uid
self.set_unique_metadata('DC', 'identifier', self.uid, {'id': self.IDENTIFIER_ID})
def set_title(self, title):
"""
Set title. You can set multiple titles.
:Args:
- title: Title value
"""
self.title = title
self.add_metadata('DC', 'title', self.title)
def set_language(self, lang):
"""
Set language for this epub. You can set multiple languages. Specific items in the book can have
different language settings.
:Args:
- lang: Language code
"""
self.language = lang
self.add_metadata('DC', 'language', lang)
def set_direction(self, direction):
"""
:Args:
- direction: Options are "ltr", "rtl" and "default"
"""
self.direction = direction
def set_cover(self, file_name, content, create_page=True):
"""
Set cover and create cover document if needed.
:Args:
- file_name: file name of the cover page
- content: Content for the cover image
- create_page: Should cover page be defined. Defined as bool value (optional). Default value is True.
"""
# as it is now, it can only be called once
c0 = EpubCover(file_name=file_name)
c0.content = content
self.add_item(c0)
if create_page:
c1 = EpubCoverHtml(image_name=file_name)
self.add_item(c1)
self.add_metadata(None, 'meta', '', OrderedDict([('name', 'cover'), ('content', 'cover-img')]))
def add_author(self, author, file_as=None, role=None, uid='creator'):
"Add author for this document"
self.add_metadata('DC', 'creator', author, {'id': uid})
if file_as:
self.add_metadata(None, 'meta', file_as, {'refines': '#' + uid,
'property': 'file-as',
'scheme': 'marc:relators'})
if role:
self.add_metadata(None, 'meta', role, {'refines': '#' + uid,
'property': 'role',
'scheme': 'marc:relators'})
def add_metadata(self, namespace, name, value, others=None):
"Add metadata"
if namespace in NAMESPACES:
namespace = NAMESPACES[namespace]
if namespace not in self.metadata:
self.metadata[namespace] = {}
if name not in self.metadata[namespace]:
self.metadata[namespace][name] = []
self.metadata[namespace][name].append((value, others))
def get_metadata(self, namespace, name):
"Retrieve metadata"
if namespace in NAMESPACES:
namespace = NAMESPACES[namespace]
return self.metadata[namespace].get(name, [])
def set_unique_metadata(self, namespace, name, value, others=None):
"Add metadata if metadata with this identifier does not already exist, otherwise update existing metadata."
if namespace in NAMESPACES:
namespace = NAMESPACES[namespace]
if namespace in self.metadata and name in self.metadata[namespace]:
self.metadata[namespace][name] = [(value, others)]
else:
self.add_metadata(namespace, name, value, others)
def add_item(self, item):
"""
Add additional item to the book. If not defined, media type and chapter id will be defined
for the item.
:Args:
- item: Item instance
"""
if item.media_type == '':
(has_guessed, media_type) = guess_type(item.get_name().lower())
if has_guessed:
if media_type is not None:
item.media_type = media_type
else:
item.media_type = has_guessed
else:
item.media_type = 'application/octet-stream'
if not item.get_id():
# make chapter_, image_ and static_ configurable
if isinstance(item, EpubHtml):
item.id = 'chapter_%d' % self._id_html
self._id_html += 1
# If there's a page list, append it to the book's page list
self.pages += item.pages
elif isinstance(item, EpubImage):
item.id = 'image_%d' % self._id_image
self._id_image += 1
else:
item.id = 'static_%d' % self._id_image
self._id_image += 1
item.book = self
self.items.append(item)
return item
def get_item_with_id(self, uid):
"""
Returns item for defined UID.
>>> book.get_item_with_id('image_001')
:Args:
- uid: UID for the item
:Returns:
Returns item object. Returns None if nothing was found.
"""
for item in self.get_items():
if item.id == uid:
return item
return None
def get_item_with_href(self, href):
"""
Returns item for defined HREF.
>>> book.get_item_with_href('EPUB/document.xhtml')
:Args:
- href: HREF for the item we are searching for
:Returns:
Returns item object. Returns None if nothing was found.
"""
for item in self.get_items():
if item.get_name() == href:
return item
return None
def get_items(self):
"""
Returns all items attached to this book.
:Returns:
Returns all items as tuple.
"""
return (item for item in self.items)
def get_items_of_type(self, item_type):
"""
Returns all items of specified type.
>>> book.get_items_of_type(epub.ITEM_IMAGE)
:Args:
- item_type: Type for items we are searching for
:Returns:
Returns found items as tuple.
"""
return (item for item in self.items if item.get_type() == item_type)
def set_template(self, name, value):
"""
Defines templates which are used to generate certain types of pages. When defining new value for the template
we have to use content of type 'str' (Python 2) or 'bytes' (Python 3).
At the moment we use these templates:
- ncx
- nav
- chapter
- cover
:Args:
- name: Name for the template
- value: Content for the template
"""
self.templates[name] = value
def get_template(self, name):
"""
Returns value for the template.
:Args:
- name: template name
:Returns:
Value of the template.
"""
return self.templates.get(name)
def add_prefix(self, name, uri):
"""
Appends custom prefix to be added to the content.opf document
>>> epub_book.add_prefix('bkterms', 'http://booktype.org/')
:Args:
- name: namespave name
- uri: URI for the namespace
"""
self.prefixes.append('%s: %s' % (name, uri))
|
MaxHalford/prince | prince/mfa.py | MFA.row_coordinates | python | def row_coordinates(self, X):
utils.validation.check_is_fitted(self, 's_')
# Check input
if self.check_input:
utils.check_array(X, dtype=[str, np.number])
# Prepare input
X = self._prepare_input(X)
return self._row_coordinates_from_global(self._build_X_global(X)) | Returns the row principal coordinates. | train | https://github.com/MaxHalford/prince/blob/714c9cdfc4d9f8823eabf550a23ad01fe87c50d7/prince/mfa.py#L132-L143 | null | class MFA(pca.PCA):
def __init__(self, groups=None, normalize=True, n_components=2, n_iter=10,
copy=True, check_input=True, random_state=None, engine='auto'):
super().__init__(
rescale_with_mean=False,
rescale_with_std=False,
n_components=n_components,
n_iter=n_iter,
copy=copy,
check_input=check_input,
random_state=random_state,
engine=engine
)
self.groups = groups
self.normalize = normalize
def fit(self, X, y=None):
# Checks groups are provided
if self.groups is None:
raise ValueError('Groups have to be specified')
# Check input
if self.check_input:
utils.check_array(X, dtype=[str, np.number])
# Prepare input
X = self._prepare_input(X)
# Check group types are consistent
self.all_nums_ = {}
for name, cols in sorted(self.groups.items()):
all_num = all(pd.api.types.is_numeric_dtype(X[c]) for c in cols)
all_cat = all(pd.api.types.is_string_dtype(X[c]) for c in cols)
if not (all_num or all_cat):
raise ValueError('Not all columns in "{}" group are of the same type'.format(name))
self.all_nums_[name] = all_num
# Run a factor analysis in each group
self.partial_factor_analysis_ = {}
for name, cols in sorted(self.groups.items()):
if self.all_nums_[name]:
fa = pca.PCA(
rescale_with_mean=False,
rescale_with_std=False,
n_components=self.n_components,
n_iter=self.n_iter,
copy=True,
random_state=self.random_state,
engine=self.engine
)
else:
fa = mca.MCA(
n_components=self.n_components,
n_iter=self.n_iter,
copy=self.copy,
random_state=self.random_state,
engine=self.engine
)
self.partial_factor_analysis_[name] = fa.fit(X.loc[:, cols])
# Fit the global PCA
self.cat_one_hots_ = {}
super().fit(self._build_X_global(X))
return self
def _prepare_input(self, X):
# Make sure X is a DataFrame for convenience
if not isinstance(X, pd.DataFrame):
X = pd.DataFrame(X)
# Copy data
if self.copy:
X = X.copy()
if self.normalize:
# Scale continuous variables to unit variance
num = X.select_dtypes(np.number).columns
# If a column's cardinality is 1 then it's variance is 0 which can
# can cause a division by 0
normalize = lambda x: x / (np.sqrt((x ** 2).sum()) or 1)
X.loc[:, num] = (X.loc[:, num] - X.loc[:, num].mean()).apply(normalize, axis='rows')
return X
def _build_X_global(self, X):
X_partials = []
for name, cols in sorted(self.groups.items()):
X_partial = X.loc[:, cols]
if not self.all_nums_[name]:
if name in self.cat_one_hots_:
oh = self.cat_one_hots_[name]
else:
oh = one_hot.OneHotEncoder().fit(X_partial)
X_partial = oh.transform(X_partial)
self.cat_one_hots_[name] = oh
X_partials.append(X_partial / self.partial_factor_analysis_[name].s_[0])
X_global = pd.concat(X_partials, axis='columns')
X_global.index = X.index
return X_global
def transform(self, X):
"""Returns the row principal coordinates of a dataset."""
return self.row_coordinates(X)
def _row_coordinates_from_global(self, X_global):
"""Returns the row principal coordinates."""
return len(X_global) ** 0.5 * super().row_coordinates(X_global)
def row_contributions(self, X):
"""Returns the row contributions towards each principal component."""
utils.validation.check_is_fitted(self, 's_')
# Check input
if self.check_input:
utils.check_array(X, dtype=[str, np.number])
# Prepare input
X = self._prepare_input(X)
return super().row_contributions(self._build_X_global(X))
def partial_row_coordinates(self, X):
"""Returns the row coordinates for each group."""
utils.validation.check_is_fitted(self, 's_')
# Check input
if self.check_input:
utils.check_array(X, dtype=[str, np.number])
# Prepare input
X = self._prepare_input(X)
# Define the projection matrix P
P = len(X) ** 0.5 * self.U_ / self.s_
# Get the projections for each group
coords = {}
for name, cols in sorted(self.groups.items()):
X_partial = X.loc[:, cols]
if not self.all_nums_[name]:
X_partial = self.cat_one_hots_[name].transform(X_partial)
Z_partial = X_partial / self.partial_factor_analysis_[name].s_[0]
coords[name] = len(self.groups) * (Z_partial @ Z_partial.T) @ P
# Convert coords to a MultiIndex DataFrame
coords = pd.DataFrame({
(name, i): group_coords.loc[:, i]
for name, group_coords in coords.items()
for i in range(group_coords.shape[1])
})
return coords
def column_correlations(self, X):
"""Returns the column correlations."""
utils.validation.check_is_fitted(self, 's_')
X_global = self._build_X_global(X)
row_pc = self._row_coordinates_from_global(X_global)
return pd.DataFrame({
component: {
feature: row_pc[component].corr(X_global[feature].to_dense())
for feature in X_global.columns
}
for component in row_pc.columns
})
def plot_partial_row_coordinates(self, X, ax=None, figsize=(6, 6), x_component=0, y_component=1,
color_labels=None, **kwargs):
"""Plot the row principal coordinates."""
utils.validation.check_is_fitted(self, 's_')
if ax is None:
fig, ax = plt.subplots(figsize=figsize)
# Add plotting style
ax = plot.stylize_axis(ax)
# Check input
if self.check_input:
utils.check_array(X, dtype=[str, np.number])
# Prepare input
X = self._prepare_input(X)
# Retrieve partial coordinates
coords = self.partial_row_coordinates(X)
# Determine the color of each group if there are group labels
if color_labels is not None:
colors = {g: ax._get_lines.get_next_color() for g in sorted(list(set(color_labels)))}
# Get the list of all possible markers
marks = itertools.cycle(list(markers.MarkerStyle.markers.keys()))
next(marks) # The first marker looks pretty shit so we skip it
# Plot points
for name in self.groups:
mark = next(marks)
x = coords[name][x_component]
y = coords[name][y_component]
if color_labels is None:
ax.scatter(x, y, marker=mark, label=name, **kwargs)
continue
for color_label, color in sorted(colors.items()):
mask = np.array(color_labels) == color_label
label = '{} - {}'.format(name, color_label)
ax.scatter(x[mask], y[mask], marker=mark, color=color, label=label, **kwargs)
# Legend
ax.legend()
# Text
ax.set_title('Partial row principal coordinates')
ei = self.explained_inertia_
ax.set_xlabel('Component {} ({:.2f}% inertia)'.format(x_component, 100 * ei[x_component]))
ax.set_ylabel('Component {} ({:.2f}% inertia)'.format(y_component, 100 * ei[y_component]))
return ax
|
MaxHalford/prince | prince/mfa.py | MFA.row_contributions | python | def row_contributions(self, X):
utils.validation.check_is_fitted(self, 's_')
# Check input
if self.check_input:
utils.check_array(X, dtype=[str, np.number])
# Prepare input
X = self._prepare_input(X)
return super().row_contributions(self._build_X_global(X)) | Returns the row contributions towards each principal component. | train | https://github.com/MaxHalford/prince/blob/714c9cdfc4d9f8823eabf550a23ad01fe87c50d7/prince/mfa.py#L145-L156 | null | class MFA(pca.PCA):
def __init__(self, groups=None, normalize=True, n_components=2, n_iter=10,
copy=True, check_input=True, random_state=None, engine='auto'):
super().__init__(
rescale_with_mean=False,
rescale_with_std=False,
n_components=n_components,
n_iter=n_iter,
copy=copy,
check_input=check_input,
random_state=random_state,
engine=engine
)
self.groups = groups
self.normalize = normalize
def fit(self, X, y=None):
# Checks groups are provided
if self.groups is None:
raise ValueError('Groups have to be specified')
# Check input
if self.check_input:
utils.check_array(X, dtype=[str, np.number])
# Prepare input
X = self._prepare_input(X)
# Check group types are consistent
self.all_nums_ = {}
for name, cols in sorted(self.groups.items()):
all_num = all(pd.api.types.is_numeric_dtype(X[c]) for c in cols)
all_cat = all(pd.api.types.is_string_dtype(X[c]) for c in cols)
if not (all_num or all_cat):
raise ValueError('Not all columns in "{}" group are of the same type'.format(name))
self.all_nums_[name] = all_num
# Run a factor analysis in each group
self.partial_factor_analysis_ = {}
for name, cols in sorted(self.groups.items()):
if self.all_nums_[name]:
fa = pca.PCA(
rescale_with_mean=False,
rescale_with_std=False,
n_components=self.n_components,
n_iter=self.n_iter,
copy=True,
random_state=self.random_state,
engine=self.engine
)
else:
fa = mca.MCA(
n_components=self.n_components,
n_iter=self.n_iter,
copy=self.copy,
random_state=self.random_state,
engine=self.engine
)
self.partial_factor_analysis_[name] = fa.fit(X.loc[:, cols])
# Fit the global PCA
self.cat_one_hots_ = {}
super().fit(self._build_X_global(X))
return self
def _prepare_input(self, X):
# Make sure X is a DataFrame for convenience
if not isinstance(X, pd.DataFrame):
X = pd.DataFrame(X)
# Copy data
if self.copy:
X = X.copy()
if self.normalize:
# Scale continuous variables to unit variance
num = X.select_dtypes(np.number).columns
# If a column's cardinality is 1 then it's variance is 0 which can
# can cause a division by 0
normalize = lambda x: x / (np.sqrt((x ** 2).sum()) or 1)
X.loc[:, num] = (X.loc[:, num] - X.loc[:, num].mean()).apply(normalize, axis='rows')
return X
def _build_X_global(self, X):
X_partials = []
for name, cols in sorted(self.groups.items()):
X_partial = X.loc[:, cols]
if not self.all_nums_[name]:
if name in self.cat_one_hots_:
oh = self.cat_one_hots_[name]
else:
oh = one_hot.OneHotEncoder().fit(X_partial)
X_partial = oh.transform(X_partial)
self.cat_one_hots_[name] = oh
X_partials.append(X_partial / self.partial_factor_analysis_[name].s_[0])
X_global = pd.concat(X_partials, axis='columns')
X_global.index = X.index
return X_global
def transform(self, X):
"""Returns the row principal coordinates of a dataset."""
return self.row_coordinates(X)
def _row_coordinates_from_global(self, X_global):
"""Returns the row principal coordinates."""
return len(X_global) ** 0.5 * super().row_coordinates(X_global)
def row_coordinates(self, X):
"""Returns the row principal coordinates."""
utils.validation.check_is_fitted(self, 's_')
# Check input
if self.check_input:
utils.check_array(X, dtype=[str, np.number])
# Prepare input
X = self._prepare_input(X)
return self._row_coordinates_from_global(self._build_X_global(X))
def partial_row_coordinates(self, X):
"""Returns the row coordinates for each group."""
utils.validation.check_is_fitted(self, 's_')
# Check input
if self.check_input:
utils.check_array(X, dtype=[str, np.number])
# Prepare input
X = self._prepare_input(X)
# Define the projection matrix P
P = len(X) ** 0.5 * self.U_ / self.s_
# Get the projections for each group
coords = {}
for name, cols in sorted(self.groups.items()):
X_partial = X.loc[:, cols]
if not self.all_nums_[name]:
X_partial = self.cat_one_hots_[name].transform(X_partial)
Z_partial = X_partial / self.partial_factor_analysis_[name].s_[0]
coords[name] = len(self.groups) * (Z_partial @ Z_partial.T) @ P
# Convert coords to a MultiIndex DataFrame
coords = pd.DataFrame({
(name, i): group_coords.loc[:, i]
for name, group_coords in coords.items()
for i in range(group_coords.shape[1])
})
return coords
def column_correlations(self, X):
"""Returns the column correlations."""
utils.validation.check_is_fitted(self, 's_')
X_global = self._build_X_global(X)
row_pc = self._row_coordinates_from_global(X_global)
return pd.DataFrame({
component: {
feature: row_pc[component].corr(X_global[feature].to_dense())
for feature in X_global.columns
}
for component in row_pc.columns
})
def plot_partial_row_coordinates(self, X, ax=None, figsize=(6, 6), x_component=0, y_component=1,
color_labels=None, **kwargs):
"""Plot the row principal coordinates."""
utils.validation.check_is_fitted(self, 's_')
if ax is None:
fig, ax = plt.subplots(figsize=figsize)
# Add plotting style
ax = plot.stylize_axis(ax)
# Check input
if self.check_input:
utils.check_array(X, dtype=[str, np.number])
# Prepare input
X = self._prepare_input(X)
# Retrieve partial coordinates
coords = self.partial_row_coordinates(X)
# Determine the color of each group if there are group labels
if color_labels is not None:
colors = {g: ax._get_lines.get_next_color() for g in sorted(list(set(color_labels)))}
# Get the list of all possible markers
marks = itertools.cycle(list(markers.MarkerStyle.markers.keys()))
next(marks) # The first marker looks pretty shit so we skip it
# Plot points
for name in self.groups:
mark = next(marks)
x = coords[name][x_component]
y = coords[name][y_component]
if color_labels is None:
ax.scatter(x, y, marker=mark, label=name, **kwargs)
continue
for color_label, color in sorted(colors.items()):
mask = np.array(color_labels) == color_label
label = '{} - {}'.format(name, color_label)
ax.scatter(x[mask], y[mask], marker=mark, color=color, label=label, **kwargs)
# Legend
ax.legend()
# Text
ax.set_title('Partial row principal coordinates')
ei = self.explained_inertia_
ax.set_xlabel('Component {} ({:.2f}% inertia)'.format(x_component, 100 * ei[x_component]))
ax.set_ylabel('Component {} ({:.2f}% inertia)'.format(y_component, 100 * ei[y_component]))
return ax
|
MaxHalford/prince | prince/mfa.py | MFA.partial_row_coordinates | python | def partial_row_coordinates(self, X):
utils.validation.check_is_fitted(self, 's_')
# Check input
if self.check_input:
utils.check_array(X, dtype=[str, np.number])
# Prepare input
X = self._prepare_input(X)
# Define the projection matrix P
P = len(X) ** 0.5 * self.U_ / self.s_
# Get the projections for each group
coords = {}
for name, cols in sorted(self.groups.items()):
X_partial = X.loc[:, cols]
if not self.all_nums_[name]:
X_partial = self.cat_one_hots_[name].transform(X_partial)
Z_partial = X_partial / self.partial_factor_analysis_[name].s_[0]
coords[name] = len(self.groups) * (Z_partial @ Z_partial.T) @ P
# Convert coords to a MultiIndex DataFrame
coords = pd.DataFrame({
(name, i): group_coords.loc[:, i]
for name, group_coords in coords.items()
for i in range(group_coords.shape[1])
})
return coords | Returns the row coordinates for each group. | train | https://github.com/MaxHalford/prince/blob/714c9cdfc4d9f8823eabf550a23ad01fe87c50d7/prince/mfa.py#L158-L190 | null | class MFA(pca.PCA):
def __init__(self, groups=None, normalize=True, n_components=2, n_iter=10,
copy=True, check_input=True, random_state=None, engine='auto'):
super().__init__(
rescale_with_mean=False,
rescale_with_std=False,
n_components=n_components,
n_iter=n_iter,
copy=copy,
check_input=check_input,
random_state=random_state,
engine=engine
)
self.groups = groups
self.normalize = normalize
def fit(self, X, y=None):
# Checks groups are provided
if self.groups is None:
raise ValueError('Groups have to be specified')
# Check input
if self.check_input:
utils.check_array(X, dtype=[str, np.number])
# Prepare input
X = self._prepare_input(X)
# Check group types are consistent
self.all_nums_ = {}
for name, cols in sorted(self.groups.items()):
all_num = all(pd.api.types.is_numeric_dtype(X[c]) for c in cols)
all_cat = all(pd.api.types.is_string_dtype(X[c]) for c in cols)
if not (all_num or all_cat):
raise ValueError('Not all columns in "{}" group are of the same type'.format(name))
self.all_nums_[name] = all_num
# Run a factor analysis in each group
self.partial_factor_analysis_ = {}
for name, cols in sorted(self.groups.items()):
if self.all_nums_[name]:
fa = pca.PCA(
rescale_with_mean=False,
rescale_with_std=False,
n_components=self.n_components,
n_iter=self.n_iter,
copy=True,
random_state=self.random_state,
engine=self.engine
)
else:
fa = mca.MCA(
n_components=self.n_components,
n_iter=self.n_iter,
copy=self.copy,
random_state=self.random_state,
engine=self.engine
)
self.partial_factor_analysis_[name] = fa.fit(X.loc[:, cols])
# Fit the global PCA
self.cat_one_hots_ = {}
super().fit(self._build_X_global(X))
return self
def _prepare_input(self, X):
# Make sure X is a DataFrame for convenience
if not isinstance(X, pd.DataFrame):
X = pd.DataFrame(X)
# Copy data
if self.copy:
X = X.copy()
if self.normalize:
# Scale continuous variables to unit variance
num = X.select_dtypes(np.number).columns
# If a column's cardinality is 1 then it's variance is 0 which can
# can cause a division by 0
normalize = lambda x: x / (np.sqrt((x ** 2).sum()) or 1)
X.loc[:, num] = (X.loc[:, num] - X.loc[:, num].mean()).apply(normalize, axis='rows')
return X
def _build_X_global(self, X):
X_partials = []
for name, cols in sorted(self.groups.items()):
X_partial = X.loc[:, cols]
if not self.all_nums_[name]:
if name in self.cat_one_hots_:
oh = self.cat_one_hots_[name]
else:
oh = one_hot.OneHotEncoder().fit(X_partial)
X_partial = oh.transform(X_partial)
self.cat_one_hots_[name] = oh
X_partials.append(X_partial / self.partial_factor_analysis_[name].s_[0])
X_global = pd.concat(X_partials, axis='columns')
X_global.index = X.index
return X_global
def transform(self, X):
"""Returns the row principal coordinates of a dataset."""
return self.row_coordinates(X)
def _row_coordinates_from_global(self, X_global):
"""Returns the row principal coordinates."""
return len(X_global) ** 0.5 * super().row_coordinates(X_global)
def row_coordinates(self, X):
"""Returns the row principal coordinates."""
utils.validation.check_is_fitted(self, 's_')
# Check input
if self.check_input:
utils.check_array(X, dtype=[str, np.number])
# Prepare input
X = self._prepare_input(X)
return self._row_coordinates_from_global(self._build_X_global(X))
def row_contributions(self, X):
"""Returns the row contributions towards each principal component."""
utils.validation.check_is_fitted(self, 's_')
# Check input
if self.check_input:
utils.check_array(X, dtype=[str, np.number])
# Prepare input
X = self._prepare_input(X)
return super().row_contributions(self._build_X_global(X))
def column_correlations(self, X):
"""Returns the column correlations."""
utils.validation.check_is_fitted(self, 's_')
X_global = self._build_X_global(X)
row_pc = self._row_coordinates_from_global(X_global)
return pd.DataFrame({
component: {
feature: row_pc[component].corr(X_global[feature].to_dense())
for feature in X_global.columns
}
for component in row_pc.columns
})
def plot_partial_row_coordinates(self, X, ax=None, figsize=(6, 6), x_component=0, y_component=1,
color_labels=None, **kwargs):
"""Plot the row principal coordinates."""
utils.validation.check_is_fitted(self, 's_')
if ax is None:
fig, ax = plt.subplots(figsize=figsize)
# Add plotting style
ax = plot.stylize_axis(ax)
# Check input
if self.check_input:
utils.check_array(X, dtype=[str, np.number])
# Prepare input
X = self._prepare_input(X)
# Retrieve partial coordinates
coords = self.partial_row_coordinates(X)
# Determine the color of each group if there are group labels
if color_labels is not None:
colors = {g: ax._get_lines.get_next_color() for g in sorted(list(set(color_labels)))}
# Get the list of all possible markers
marks = itertools.cycle(list(markers.MarkerStyle.markers.keys()))
next(marks) # The first marker looks pretty shit so we skip it
# Plot points
for name in self.groups:
mark = next(marks)
x = coords[name][x_component]
y = coords[name][y_component]
if color_labels is None:
ax.scatter(x, y, marker=mark, label=name, **kwargs)
continue
for color_label, color in sorted(colors.items()):
mask = np.array(color_labels) == color_label
label = '{} - {}'.format(name, color_label)
ax.scatter(x[mask], y[mask], marker=mark, color=color, label=label, **kwargs)
# Legend
ax.legend()
# Text
ax.set_title('Partial row principal coordinates')
ei = self.explained_inertia_
ax.set_xlabel('Component {} ({:.2f}% inertia)'.format(x_component, 100 * ei[x_component]))
ax.set_ylabel('Component {} ({:.2f}% inertia)'.format(y_component, 100 * ei[y_component]))
return ax
|
MaxHalford/prince | prince/mfa.py | MFA.column_correlations | python | def column_correlations(self, X):
utils.validation.check_is_fitted(self, 's_')
X_global = self._build_X_global(X)
row_pc = self._row_coordinates_from_global(X_global)
return pd.DataFrame({
component: {
feature: row_pc[component].corr(X_global[feature].to_dense())
for feature in X_global.columns
}
for component in row_pc.columns
}) | Returns the column correlations. | train | https://github.com/MaxHalford/prince/blob/714c9cdfc4d9f8823eabf550a23ad01fe87c50d7/prince/mfa.py#L192-L205 | null | class MFA(pca.PCA):
def __init__(self, groups=None, normalize=True, n_components=2, n_iter=10,
copy=True, check_input=True, random_state=None, engine='auto'):
super().__init__(
rescale_with_mean=False,
rescale_with_std=False,
n_components=n_components,
n_iter=n_iter,
copy=copy,
check_input=check_input,
random_state=random_state,
engine=engine
)
self.groups = groups
self.normalize = normalize
def fit(self, X, y=None):
# Checks groups are provided
if self.groups is None:
raise ValueError('Groups have to be specified')
# Check input
if self.check_input:
utils.check_array(X, dtype=[str, np.number])
# Prepare input
X = self._prepare_input(X)
# Check group types are consistent
self.all_nums_ = {}
for name, cols in sorted(self.groups.items()):
all_num = all(pd.api.types.is_numeric_dtype(X[c]) for c in cols)
all_cat = all(pd.api.types.is_string_dtype(X[c]) for c in cols)
if not (all_num or all_cat):
raise ValueError('Not all columns in "{}" group are of the same type'.format(name))
self.all_nums_[name] = all_num
# Run a factor analysis in each group
self.partial_factor_analysis_ = {}
for name, cols in sorted(self.groups.items()):
if self.all_nums_[name]:
fa = pca.PCA(
rescale_with_mean=False,
rescale_with_std=False,
n_components=self.n_components,
n_iter=self.n_iter,
copy=True,
random_state=self.random_state,
engine=self.engine
)
else:
fa = mca.MCA(
n_components=self.n_components,
n_iter=self.n_iter,
copy=self.copy,
random_state=self.random_state,
engine=self.engine
)
self.partial_factor_analysis_[name] = fa.fit(X.loc[:, cols])
# Fit the global PCA
self.cat_one_hots_ = {}
super().fit(self._build_X_global(X))
return self
def _prepare_input(self, X):
# Make sure X is a DataFrame for convenience
if not isinstance(X, pd.DataFrame):
X = pd.DataFrame(X)
# Copy data
if self.copy:
X = X.copy()
if self.normalize:
# Scale continuous variables to unit variance
num = X.select_dtypes(np.number).columns
# If a column's cardinality is 1 then it's variance is 0 which can
# can cause a division by 0
normalize = lambda x: x / (np.sqrt((x ** 2).sum()) or 1)
X.loc[:, num] = (X.loc[:, num] - X.loc[:, num].mean()).apply(normalize, axis='rows')
return X
def _build_X_global(self, X):
X_partials = []
for name, cols in sorted(self.groups.items()):
X_partial = X.loc[:, cols]
if not self.all_nums_[name]:
if name in self.cat_one_hots_:
oh = self.cat_one_hots_[name]
else:
oh = one_hot.OneHotEncoder().fit(X_partial)
X_partial = oh.transform(X_partial)
self.cat_one_hots_[name] = oh
X_partials.append(X_partial / self.partial_factor_analysis_[name].s_[0])
X_global = pd.concat(X_partials, axis='columns')
X_global.index = X.index
return X_global
def transform(self, X):
"""Returns the row principal coordinates of a dataset."""
return self.row_coordinates(X)
def _row_coordinates_from_global(self, X_global):
"""Returns the row principal coordinates."""
return len(X_global) ** 0.5 * super().row_coordinates(X_global)
def row_coordinates(self, X):
"""Returns the row principal coordinates."""
utils.validation.check_is_fitted(self, 's_')
# Check input
if self.check_input:
utils.check_array(X, dtype=[str, np.number])
# Prepare input
X = self._prepare_input(X)
return self._row_coordinates_from_global(self._build_X_global(X))
def row_contributions(self, X):
"""Returns the row contributions towards each principal component."""
utils.validation.check_is_fitted(self, 's_')
# Check input
if self.check_input:
utils.check_array(X, dtype=[str, np.number])
# Prepare input
X = self._prepare_input(X)
return super().row_contributions(self._build_X_global(X))
def partial_row_coordinates(self, X):
"""Returns the row coordinates for each group."""
utils.validation.check_is_fitted(self, 's_')
# Check input
if self.check_input:
utils.check_array(X, dtype=[str, np.number])
# Prepare input
X = self._prepare_input(X)
# Define the projection matrix P
P = len(X) ** 0.5 * self.U_ / self.s_
# Get the projections for each group
coords = {}
for name, cols in sorted(self.groups.items()):
X_partial = X.loc[:, cols]
if not self.all_nums_[name]:
X_partial = self.cat_one_hots_[name].transform(X_partial)
Z_partial = X_partial / self.partial_factor_analysis_[name].s_[0]
coords[name] = len(self.groups) * (Z_partial @ Z_partial.T) @ P
# Convert coords to a MultiIndex DataFrame
coords = pd.DataFrame({
(name, i): group_coords.loc[:, i]
for name, group_coords in coords.items()
for i in range(group_coords.shape[1])
})
return coords
def plot_partial_row_coordinates(self, X, ax=None, figsize=(6, 6), x_component=0, y_component=1,
color_labels=None, **kwargs):
"""Plot the row principal coordinates."""
utils.validation.check_is_fitted(self, 's_')
if ax is None:
fig, ax = plt.subplots(figsize=figsize)
# Add plotting style
ax = plot.stylize_axis(ax)
# Check input
if self.check_input:
utils.check_array(X, dtype=[str, np.number])
# Prepare input
X = self._prepare_input(X)
# Retrieve partial coordinates
coords = self.partial_row_coordinates(X)
# Determine the color of each group if there are group labels
if color_labels is not None:
colors = {g: ax._get_lines.get_next_color() for g in sorted(list(set(color_labels)))}
# Get the list of all possible markers
marks = itertools.cycle(list(markers.MarkerStyle.markers.keys()))
next(marks) # The first marker looks pretty shit so we skip it
# Plot points
for name in self.groups:
mark = next(marks)
x = coords[name][x_component]
y = coords[name][y_component]
if color_labels is None:
ax.scatter(x, y, marker=mark, label=name, **kwargs)
continue
for color_label, color in sorted(colors.items()):
mask = np.array(color_labels) == color_label
label = '{} - {}'.format(name, color_label)
ax.scatter(x[mask], y[mask], marker=mark, color=color, label=label, **kwargs)
# Legend
ax.legend()
# Text
ax.set_title('Partial row principal coordinates')
ei = self.explained_inertia_
ax.set_xlabel('Component {} ({:.2f}% inertia)'.format(x_component, 100 * ei[x_component]))
ax.set_ylabel('Component {} ({:.2f}% inertia)'.format(y_component, 100 * ei[y_component]))
return ax
|
MaxHalford/prince | prince/mfa.py | MFA.plot_partial_row_coordinates | python | def plot_partial_row_coordinates(self, X, ax=None, figsize=(6, 6), x_component=0, y_component=1,
color_labels=None, **kwargs):
utils.validation.check_is_fitted(self, 's_')
if ax is None:
fig, ax = plt.subplots(figsize=figsize)
# Add plotting style
ax = plot.stylize_axis(ax)
# Check input
if self.check_input:
utils.check_array(X, dtype=[str, np.number])
# Prepare input
X = self._prepare_input(X)
# Retrieve partial coordinates
coords = self.partial_row_coordinates(X)
# Determine the color of each group if there are group labels
if color_labels is not None:
colors = {g: ax._get_lines.get_next_color() for g in sorted(list(set(color_labels)))}
# Get the list of all possible markers
marks = itertools.cycle(list(markers.MarkerStyle.markers.keys()))
next(marks) # The first marker looks pretty shit so we skip it
# Plot points
for name in self.groups:
mark = next(marks)
x = coords[name][x_component]
y = coords[name][y_component]
if color_labels is None:
ax.scatter(x, y, marker=mark, label=name, **kwargs)
continue
for color_label, color in sorted(colors.items()):
mask = np.array(color_labels) == color_label
label = '{} - {}'.format(name, color_label)
ax.scatter(x[mask], y[mask], marker=mark, color=color, label=label, **kwargs)
# Legend
ax.legend()
# Text
ax.set_title('Partial row principal coordinates')
ei = self.explained_inertia_
ax.set_xlabel('Component {} ({:.2f}% inertia)'.format(x_component, 100 * ei[x_component]))
ax.set_ylabel('Component {} ({:.2f}% inertia)'.format(y_component, 100 * ei[y_component]))
return ax | Plot the row principal coordinates. | train | https://github.com/MaxHalford/prince/blob/714c9cdfc4d9f8823eabf550a23ad01fe87c50d7/prince/mfa.py#L207-L262 | [
"def stylize_axis(ax, grid=True):\n\n if grid:\n ax.grid()\n\n ax.xaxis.set_ticks_position('none')\n ax.yaxis.set_ticks_position('none')\n\n ax.axhline(y=0, linestyle='-', linewidth=1.2, color=GRAY['dark'], alpha=0.6)\n ax.axvline(x=0, linestyle='-', linewidth=1.2, color=GRAY['dark'], alpha=0.6)\n\n return ax\n"
] | class MFA(pca.PCA):
def __init__(self, groups=None, normalize=True, n_components=2, n_iter=10,
copy=True, check_input=True, random_state=None, engine='auto'):
super().__init__(
rescale_with_mean=False,
rescale_with_std=False,
n_components=n_components,
n_iter=n_iter,
copy=copy,
check_input=check_input,
random_state=random_state,
engine=engine
)
self.groups = groups
self.normalize = normalize
def fit(self, X, y=None):
# Checks groups are provided
if self.groups is None:
raise ValueError('Groups have to be specified')
# Check input
if self.check_input:
utils.check_array(X, dtype=[str, np.number])
# Prepare input
X = self._prepare_input(X)
# Check group types are consistent
self.all_nums_ = {}
for name, cols in sorted(self.groups.items()):
all_num = all(pd.api.types.is_numeric_dtype(X[c]) for c in cols)
all_cat = all(pd.api.types.is_string_dtype(X[c]) for c in cols)
if not (all_num or all_cat):
raise ValueError('Not all columns in "{}" group are of the same type'.format(name))
self.all_nums_[name] = all_num
# Run a factor analysis in each group
self.partial_factor_analysis_ = {}
for name, cols in sorted(self.groups.items()):
if self.all_nums_[name]:
fa = pca.PCA(
rescale_with_mean=False,
rescale_with_std=False,
n_components=self.n_components,
n_iter=self.n_iter,
copy=True,
random_state=self.random_state,
engine=self.engine
)
else:
fa = mca.MCA(
n_components=self.n_components,
n_iter=self.n_iter,
copy=self.copy,
random_state=self.random_state,
engine=self.engine
)
self.partial_factor_analysis_[name] = fa.fit(X.loc[:, cols])
# Fit the global PCA
self.cat_one_hots_ = {}
super().fit(self._build_X_global(X))
return self
def _prepare_input(self, X):
# Make sure X is a DataFrame for convenience
if not isinstance(X, pd.DataFrame):
X = pd.DataFrame(X)
# Copy data
if self.copy:
X = X.copy()
if self.normalize:
# Scale continuous variables to unit variance
num = X.select_dtypes(np.number).columns
# If a column's cardinality is 1 then it's variance is 0 which can
# can cause a division by 0
normalize = lambda x: x / (np.sqrt((x ** 2).sum()) or 1)
X.loc[:, num] = (X.loc[:, num] - X.loc[:, num].mean()).apply(normalize, axis='rows')
return X
def _build_X_global(self, X):
X_partials = []
for name, cols in sorted(self.groups.items()):
X_partial = X.loc[:, cols]
if not self.all_nums_[name]:
if name in self.cat_one_hots_:
oh = self.cat_one_hots_[name]
else:
oh = one_hot.OneHotEncoder().fit(X_partial)
X_partial = oh.transform(X_partial)
self.cat_one_hots_[name] = oh
X_partials.append(X_partial / self.partial_factor_analysis_[name].s_[0])
X_global = pd.concat(X_partials, axis='columns')
X_global.index = X.index
return X_global
def transform(self, X):
"""Returns the row principal coordinates of a dataset."""
return self.row_coordinates(X)
def _row_coordinates_from_global(self, X_global):
"""Returns the row principal coordinates."""
return len(X_global) ** 0.5 * super().row_coordinates(X_global)
def row_coordinates(self, X):
"""Returns the row principal coordinates."""
utils.validation.check_is_fitted(self, 's_')
# Check input
if self.check_input:
utils.check_array(X, dtype=[str, np.number])
# Prepare input
X = self._prepare_input(X)
return self._row_coordinates_from_global(self._build_X_global(X))
def row_contributions(self, X):
"""Returns the row contributions towards each principal component."""
utils.validation.check_is_fitted(self, 's_')
# Check input
if self.check_input:
utils.check_array(X, dtype=[str, np.number])
# Prepare input
X = self._prepare_input(X)
return super().row_contributions(self._build_X_global(X))
def partial_row_coordinates(self, X):
"""Returns the row coordinates for each group."""
utils.validation.check_is_fitted(self, 's_')
# Check input
if self.check_input:
utils.check_array(X, dtype=[str, np.number])
# Prepare input
X = self._prepare_input(X)
# Define the projection matrix P
P = len(X) ** 0.5 * self.U_ / self.s_
# Get the projections for each group
coords = {}
for name, cols in sorted(self.groups.items()):
X_partial = X.loc[:, cols]
if not self.all_nums_[name]:
X_partial = self.cat_one_hots_[name].transform(X_partial)
Z_partial = X_partial / self.partial_factor_analysis_[name].s_[0]
coords[name] = len(self.groups) * (Z_partial @ Z_partial.T) @ P
# Convert coords to a MultiIndex DataFrame
coords = pd.DataFrame({
(name, i): group_coords.loc[:, i]
for name, group_coords in coords.items()
for i in range(group_coords.shape[1])
})
return coords
def column_correlations(self, X):
"""Returns the column correlations."""
utils.validation.check_is_fitted(self, 's_')
X_global = self._build_X_global(X)
row_pc = self._row_coordinates_from_global(X_global)
return pd.DataFrame({
component: {
feature: row_pc[component].corr(X_global[feature].to_dense())
for feature in X_global.columns
}
for component in row_pc.columns
})
|
MaxHalford/prince | prince/ca.py | CA.transform | python | def transform(self, X):
utils.validation.check_is_fitted(self, 's_')
if self.check_input:
utils.check_array(X)
return self.row_coordinates(X) | Computes the row principal coordinates of a dataset.
Same as calling `row_coordinates`. In most cases you should be using the same
dataset as you did when calling the `fit` method. You might however also want to included
supplementary data. | train | https://github.com/MaxHalford/prince/blob/714c9cdfc4d9f8823eabf550a23ad01fe87c50d7/prince/ca.py#L69-L79 | null | class CA(base.BaseEstimator, base.TransformerMixin):
def __init__(self, n_components=2, n_iter=10, copy=True, check_input=True, random_state=None,
engine='auto'):
self.n_components = n_components
self.n_iter = n_iter
self.copy = copy
self.check_input = check_input
self.random_state = random_state
self.engine = engine
def fit(self, X, y=None):
# Check input
if self.check_input:
utils.check_array(X)
# Check all values are positive
if (X < 0).any().any():
raise ValueError("All values in X should be positive")
_, row_names, _, col_names = util.make_labels_and_names(X)
if isinstance(X, pd.DataFrame):
X = X.to_numpy()
if self.copy:
X = np.copy(X)
# Compute the correspondence matrix which contains the relative frequencies
X = X / np.sum(X)
# Compute row and column masses
self.row_masses_ = pd.Series(X.sum(axis=1), index=row_names)
self.col_masses_ = pd.Series(X.sum(axis=0), index=col_names)
# Compute standardised residuals
r = self.row_masses_.to_numpy()
c = self.col_masses_.to_numpy()
S = sparse.diags(r ** -0.5) @ (X - np.outer(r, c)) @ sparse.diags(c ** -0.5)
# Compute SVD on the standardised residuals
self.U_, self.s_, self.V_ = svd.compute_svd(
X=S,
n_components=self.n_components,
n_iter=self.n_iter,
random_state=self.random_state,
engine=self.engine
)
# Compute total inertia
self.total_inertia_ = np.einsum('ij,ji->', S, S.T)
return self
@property
def eigenvalues_(self):
"""The eigenvalues associated with each principal component."""
utils.validation.check_is_fitted(self, 's_')
return np.square(self.s_).tolist()
@property
def explained_inertia_(self):
"""The percentage of explained inertia per principal component."""
utils.validation.check_is_fitted(self, 'total_inertia_')
return [eig / self.total_inertia_ for eig in self.eigenvalues_]
def row_coordinates(self, X):
"""The row principal coordinates."""
utils.validation.check_is_fitted(self, 'V_')
_, row_names, _, _ = util.make_labels_and_names(X)
if isinstance(X, pd.SparseDataFrame):
X = X.to_coo().astype(float)
elif isinstance(X, pd.DataFrame):
X = X.to_numpy()
if self.copy:
X = X.copy()
# Normalise the rows so that they sum up to 1
if isinstance(X, np.ndarray):
X = X / X.sum(axis=1)[:, None]
else:
X = X / X.sum(axis=1)
return pd.DataFrame(
data=X @ sparse.diags(self.col_masses_.to_numpy() ** -0.5) @ self.V_.T,
index=row_names
)
def column_coordinates(self, X):
"""The column principal coordinates."""
utils.validation.check_is_fitted(self, 'V_')
_, _, _, col_names = util.make_labels_and_names(X)
if isinstance(X, pd.SparseDataFrame):
X = X.to_coo()
elif isinstance(X, pd.DataFrame):
X = X.to_numpy()
if self.copy:
X = X.copy()
# Transpose and make sure the rows sum up to 1
if isinstance(X, np.ndarray):
X = X.T / X.T.sum(axis=1)[:, None]
else:
X = X.T / X.T.sum(axis=1)
return pd.DataFrame(
data=X @ sparse.diags(self.row_masses_.to_numpy() ** -0.5) @ self.U_,
index=col_names
)
def plot_coordinates(self, X, ax=None, figsize=(6, 6), x_component=0, y_component=1,
show_row_labels=True, show_col_labels=True, **kwargs):
"""Plot the principal coordinates."""
utils.validation.check_is_fitted(self, 's_')
if ax is None:
fig, ax = plt.subplots(figsize=figsize)
# Add style
ax = plot.stylize_axis(ax)
# Get labels and names
row_label, row_names, col_label, col_names = util.make_labels_and_names(X)
# Plot row principal coordinates
row_coords = self.row_coordinates(X)
ax.scatter(
row_coords[x_component],
row_coords[y_component],
**kwargs,
label=row_label
)
# Plot column principal coordinates
col_coords = self.column_coordinates(X)
ax.scatter(
col_coords[x_component],
col_coords[y_component],
**kwargs,
label=col_label
)
# Add row labels
if show_row_labels:
x = row_coords[x_component]
y = row_coords[y_component]
for i, label in enumerate(row_names):
ax.annotate(label, (x[i], y[i]))
# Add column labels
if show_col_labels:
x = col_coords[x_component]
y = col_coords[y_component]
for i, label in enumerate(col_names):
ax.annotate(label, (x[i], y[i]))
# Legend
ax.legend()
# Text
ax.set_title('Principal coordinates')
ei = self.explained_inertia_
ax.set_xlabel('Component {} ({:.2f}% inertia)'.format(x_component, 100 * ei[x_component]))
ax.set_ylabel('Component {} ({:.2f}% inertia)'.format(y_component, 100 * ei[y_component]))
return ax
|
MaxHalford/prince | prince/ca.py | CA.eigenvalues_ | python | def eigenvalues_(self):
utils.validation.check_is_fitted(self, 's_')
return np.square(self.s_).tolist() | The eigenvalues associated with each principal component. | train | https://github.com/MaxHalford/prince/blob/714c9cdfc4d9f8823eabf550a23ad01fe87c50d7/prince/ca.py#L82-L85 | null | class CA(base.BaseEstimator, base.TransformerMixin):
def __init__(self, n_components=2, n_iter=10, copy=True, check_input=True, random_state=None,
engine='auto'):
self.n_components = n_components
self.n_iter = n_iter
self.copy = copy
self.check_input = check_input
self.random_state = random_state
self.engine = engine
def fit(self, X, y=None):
# Check input
if self.check_input:
utils.check_array(X)
# Check all values are positive
if (X < 0).any().any():
raise ValueError("All values in X should be positive")
_, row_names, _, col_names = util.make_labels_and_names(X)
if isinstance(X, pd.DataFrame):
X = X.to_numpy()
if self.copy:
X = np.copy(X)
# Compute the correspondence matrix which contains the relative frequencies
X = X / np.sum(X)
# Compute row and column masses
self.row_masses_ = pd.Series(X.sum(axis=1), index=row_names)
self.col_masses_ = pd.Series(X.sum(axis=0), index=col_names)
# Compute standardised residuals
r = self.row_masses_.to_numpy()
c = self.col_masses_.to_numpy()
S = sparse.diags(r ** -0.5) @ (X - np.outer(r, c)) @ sparse.diags(c ** -0.5)
# Compute SVD on the standardised residuals
self.U_, self.s_, self.V_ = svd.compute_svd(
X=S,
n_components=self.n_components,
n_iter=self.n_iter,
random_state=self.random_state,
engine=self.engine
)
# Compute total inertia
self.total_inertia_ = np.einsum('ij,ji->', S, S.T)
return self
def transform(self, X):
"""Computes the row principal coordinates of a dataset.
Same as calling `row_coordinates`. In most cases you should be using the same
dataset as you did when calling the `fit` method. You might however also want to included
supplementary data.
"""
utils.validation.check_is_fitted(self, 's_')
if self.check_input:
utils.check_array(X)
return self.row_coordinates(X)
@property
@property
def explained_inertia_(self):
"""The percentage of explained inertia per principal component."""
utils.validation.check_is_fitted(self, 'total_inertia_')
return [eig / self.total_inertia_ for eig in self.eigenvalues_]
def row_coordinates(self, X):
"""The row principal coordinates."""
utils.validation.check_is_fitted(self, 'V_')
_, row_names, _, _ = util.make_labels_and_names(X)
if isinstance(X, pd.SparseDataFrame):
X = X.to_coo().astype(float)
elif isinstance(X, pd.DataFrame):
X = X.to_numpy()
if self.copy:
X = X.copy()
# Normalise the rows so that they sum up to 1
if isinstance(X, np.ndarray):
X = X / X.sum(axis=1)[:, None]
else:
X = X / X.sum(axis=1)
return pd.DataFrame(
data=X @ sparse.diags(self.col_masses_.to_numpy() ** -0.5) @ self.V_.T,
index=row_names
)
def column_coordinates(self, X):
"""The column principal coordinates."""
utils.validation.check_is_fitted(self, 'V_')
_, _, _, col_names = util.make_labels_and_names(X)
if isinstance(X, pd.SparseDataFrame):
X = X.to_coo()
elif isinstance(X, pd.DataFrame):
X = X.to_numpy()
if self.copy:
X = X.copy()
# Transpose and make sure the rows sum up to 1
if isinstance(X, np.ndarray):
X = X.T / X.T.sum(axis=1)[:, None]
else:
X = X.T / X.T.sum(axis=1)
return pd.DataFrame(
data=X @ sparse.diags(self.row_masses_.to_numpy() ** -0.5) @ self.U_,
index=col_names
)
def plot_coordinates(self, X, ax=None, figsize=(6, 6), x_component=0, y_component=1,
show_row_labels=True, show_col_labels=True, **kwargs):
"""Plot the principal coordinates."""
utils.validation.check_is_fitted(self, 's_')
if ax is None:
fig, ax = plt.subplots(figsize=figsize)
# Add style
ax = plot.stylize_axis(ax)
# Get labels and names
row_label, row_names, col_label, col_names = util.make_labels_and_names(X)
# Plot row principal coordinates
row_coords = self.row_coordinates(X)
ax.scatter(
row_coords[x_component],
row_coords[y_component],
**kwargs,
label=row_label
)
# Plot column principal coordinates
col_coords = self.column_coordinates(X)
ax.scatter(
col_coords[x_component],
col_coords[y_component],
**kwargs,
label=col_label
)
# Add row labels
if show_row_labels:
x = row_coords[x_component]
y = row_coords[y_component]
for i, label in enumerate(row_names):
ax.annotate(label, (x[i], y[i]))
# Add column labels
if show_col_labels:
x = col_coords[x_component]
y = col_coords[y_component]
for i, label in enumerate(col_names):
ax.annotate(label, (x[i], y[i]))
# Legend
ax.legend()
# Text
ax.set_title('Principal coordinates')
ei = self.explained_inertia_
ax.set_xlabel('Component {} ({:.2f}% inertia)'.format(x_component, 100 * ei[x_component]))
ax.set_ylabel('Component {} ({:.2f}% inertia)'.format(y_component, 100 * ei[y_component]))
return ax
|
MaxHalford/prince | prince/ca.py | CA.explained_inertia_ | python | def explained_inertia_(self):
utils.validation.check_is_fitted(self, 'total_inertia_')
return [eig / self.total_inertia_ for eig in self.eigenvalues_] | The percentage of explained inertia per principal component. | train | https://github.com/MaxHalford/prince/blob/714c9cdfc4d9f8823eabf550a23ad01fe87c50d7/prince/ca.py#L88-L91 | null | class CA(base.BaseEstimator, base.TransformerMixin):
def __init__(self, n_components=2, n_iter=10, copy=True, check_input=True, random_state=None,
engine='auto'):
self.n_components = n_components
self.n_iter = n_iter
self.copy = copy
self.check_input = check_input
self.random_state = random_state
self.engine = engine
def fit(self, X, y=None):
# Check input
if self.check_input:
utils.check_array(X)
# Check all values are positive
if (X < 0).any().any():
raise ValueError("All values in X should be positive")
_, row_names, _, col_names = util.make_labels_and_names(X)
if isinstance(X, pd.DataFrame):
X = X.to_numpy()
if self.copy:
X = np.copy(X)
# Compute the correspondence matrix which contains the relative frequencies
X = X / np.sum(X)
# Compute row and column masses
self.row_masses_ = pd.Series(X.sum(axis=1), index=row_names)
self.col_masses_ = pd.Series(X.sum(axis=0), index=col_names)
# Compute standardised residuals
r = self.row_masses_.to_numpy()
c = self.col_masses_.to_numpy()
S = sparse.diags(r ** -0.5) @ (X - np.outer(r, c)) @ sparse.diags(c ** -0.5)
# Compute SVD on the standardised residuals
self.U_, self.s_, self.V_ = svd.compute_svd(
X=S,
n_components=self.n_components,
n_iter=self.n_iter,
random_state=self.random_state,
engine=self.engine
)
# Compute total inertia
self.total_inertia_ = np.einsum('ij,ji->', S, S.T)
return self
def transform(self, X):
"""Computes the row principal coordinates of a dataset.
Same as calling `row_coordinates`. In most cases you should be using the same
dataset as you did when calling the `fit` method. You might however also want to included
supplementary data.
"""
utils.validation.check_is_fitted(self, 's_')
if self.check_input:
utils.check_array(X)
return self.row_coordinates(X)
@property
def eigenvalues_(self):
"""The eigenvalues associated with each principal component."""
utils.validation.check_is_fitted(self, 's_')
return np.square(self.s_).tolist()
@property
def row_coordinates(self, X):
"""The row principal coordinates."""
utils.validation.check_is_fitted(self, 'V_')
_, row_names, _, _ = util.make_labels_and_names(X)
if isinstance(X, pd.SparseDataFrame):
X = X.to_coo().astype(float)
elif isinstance(X, pd.DataFrame):
X = X.to_numpy()
if self.copy:
X = X.copy()
# Normalise the rows so that they sum up to 1
if isinstance(X, np.ndarray):
X = X / X.sum(axis=1)[:, None]
else:
X = X / X.sum(axis=1)
return pd.DataFrame(
data=X @ sparse.diags(self.col_masses_.to_numpy() ** -0.5) @ self.V_.T,
index=row_names
)
def column_coordinates(self, X):
"""The column principal coordinates."""
utils.validation.check_is_fitted(self, 'V_')
_, _, _, col_names = util.make_labels_and_names(X)
if isinstance(X, pd.SparseDataFrame):
X = X.to_coo()
elif isinstance(X, pd.DataFrame):
X = X.to_numpy()
if self.copy:
X = X.copy()
# Transpose and make sure the rows sum up to 1
if isinstance(X, np.ndarray):
X = X.T / X.T.sum(axis=1)[:, None]
else:
X = X.T / X.T.sum(axis=1)
return pd.DataFrame(
data=X @ sparse.diags(self.row_masses_.to_numpy() ** -0.5) @ self.U_,
index=col_names
)
def plot_coordinates(self, X, ax=None, figsize=(6, 6), x_component=0, y_component=1,
show_row_labels=True, show_col_labels=True, **kwargs):
"""Plot the principal coordinates."""
utils.validation.check_is_fitted(self, 's_')
if ax is None:
fig, ax = plt.subplots(figsize=figsize)
# Add style
ax = plot.stylize_axis(ax)
# Get labels and names
row_label, row_names, col_label, col_names = util.make_labels_and_names(X)
# Plot row principal coordinates
row_coords = self.row_coordinates(X)
ax.scatter(
row_coords[x_component],
row_coords[y_component],
**kwargs,
label=row_label
)
# Plot column principal coordinates
col_coords = self.column_coordinates(X)
ax.scatter(
col_coords[x_component],
col_coords[y_component],
**kwargs,
label=col_label
)
# Add row labels
if show_row_labels:
x = row_coords[x_component]
y = row_coords[y_component]
for i, label in enumerate(row_names):
ax.annotate(label, (x[i], y[i]))
# Add column labels
if show_col_labels:
x = col_coords[x_component]
y = col_coords[y_component]
for i, label in enumerate(col_names):
ax.annotate(label, (x[i], y[i]))
# Legend
ax.legend()
# Text
ax.set_title('Principal coordinates')
ei = self.explained_inertia_
ax.set_xlabel('Component {} ({:.2f}% inertia)'.format(x_component, 100 * ei[x_component]))
ax.set_ylabel('Component {} ({:.2f}% inertia)'.format(y_component, 100 * ei[y_component]))
return ax
|
MaxHalford/prince | prince/ca.py | CA.row_coordinates | python | def row_coordinates(self, X):
utils.validation.check_is_fitted(self, 'V_')
_, row_names, _, _ = util.make_labels_and_names(X)
if isinstance(X, pd.SparseDataFrame):
X = X.to_coo().astype(float)
elif isinstance(X, pd.DataFrame):
X = X.to_numpy()
if self.copy:
X = X.copy()
# Normalise the rows so that they sum up to 1
if isinstance(X, np.ndarray):
X = X / X.sum(axis=1)[:, None]
else:
X = X / X.sum(axis=1)
return pd.DataFrame(
data=X @ sparse.diags(self.col_masses_.to_numpy() ** -0.5) @ self.V_.T,
index=row_names
) | The row principal coordinates. | train | https://github.com/MaxHalford/prince/blob/714c9cdfc4d9f8823eabf550a23ad01fe87c50d7/prince/ca.py#L93-L116 | [
"def make_labels_and_names(X):\n\n if isinstance(X, pd.DataFrame):\n row_label = X.index.name if X.index.name else 'Rows'\n row_names = X.index.tolist()\n col_label = X.columns.name if X.columns.name else 'Columns'\n col_names = X.columns.tolist()\n else:\n row_label = 'Rows'\n row_names = list(range(X.shape[0]))\n col_label = 'Columns'\n col_names = list(range(X.shape[1]))\n\n return row_label, row_names, col_label, col_names\n"
] | class CA(base.BaseEstimator, base.TransformerMixin):
def __init__(self, n_components=2, n_iter=10, copy=True, check_input=True, random_state=None,
engine='auto'):
self.n_components = n_components
self.n_iter = n_iter
self.copy = copy
self.check_input = check_input
self.random_state = random_state
self.engine = engine
def fit(self, X, y=None):
# Check input
if self.check_input:
utils.check_array(X)
# Check all values are positive
if (X < 0).any().any():
raise ValueError("All values in X should be positive")
_, row_names, _, col_names = util.make_labels_and_names(X)
if isinstance(X, pd.DataFrame):
X = X.to_numpy()
if self.copy:
X = np.copy(X)
# Compute the correspondence matrix which contains the relative frequencies
X = X / np.sum(X)
# Compute row and column masses
self.row_masses_ = pd.Series(X.sum(axis=1), index=row_names)
self.col_masses_ = pd.Series(X.sum(axis=0), index=col_names)
# Compute standardised residuals
r = self.row_masses_.to_numpy()
c = self.col_masses_.to_numpy()
S = sparse.diags(r ** -0.5) @ (X - np.outer(r, c)) @ sparse.diags(c ** -0.5)
# Compute SVD on the standardised residuals
self.U_, self.s_, self.V_ = svd.compute_svd(
X=S,
n_components=self.n_components,
n_iter=self.n_iter,
random_state=self.random_state,
engine=self.engine
)
# Compute total inertia
self.total_inertia_ = np.einsum('ij,ji->', S, S.T)
return self
def transform(self, X):
"""Computes the row principal coordinates of a dataset.
Same as calling `row_coordinates`. In most cases you should be using the same
dataset as you did when calling the `fit` method. You might however also want to included
supplementary data.
"""
utils.validation.check_is_fitted(self, 's_')
if self.check_input:
utils.check_array(X)
return self.row_coordinates(X)
@property
def eigenvalues_(self):
"""The eigenvalues associated with each principal component."""
utils.validation.check_is_fitted(self, 's_')
return np.square(self.s_).tolist()
@property
def explained_inertia_(self):
"""The percentage of explained inertia per principal component."""
utils.validation.check_is_fitted(self, 'total_inertia_')
return [eig / self.total_inertia_ for eig in self.eigenvalues_]
def column_coordinates(self, X):
"""The column principal coordinates."""
utils.validation.check_is_fitted(self, 'V_')
_, _, _, col_names = util.make_labels_and_names(X)
if isinstance(X, pd.SparseDataFrame):
X = X.to_coo()
elif isinstance(X, pd.DataFrame):
X = X.to_numpy()
if self.copy:
X = X.copy()
# Transpose and make sure the rows sum up to 1
if isinstance(X, np.ndarray):
X = X.T / X.T.sum(axis=1)[:, None]
else:
X = X.T / X.T.sum(axis=1)
return pd.DataFrame(
data=X @ sparse.diags(self.row_masses_.to_numpy() ** -0.5) @ self.U_,
index=col_names
)
def plot_coordinates(self, X, ax=None, figsize=(6, 6), x_component=0, y_component=1,
show_row_labels=True, show_col_labels=True, **kwargs):
"""Plot the principal coordinates."""
utils.validation.check_is_fitted(self, 's_')
if ax is None:
fig, ax = plt.subplots(figsize=figsize)
# Add style
ax = plot.stylize_axis(ax)
# Get labels and names
row_label, row_names, col_label, col_names = util.make_labels_and_names(X)
# Plot row principal coordinates
row_coords = self.row_coordinates(X)
ax.scatter(
row_coords[x_component],
row_coords[y_component],
**kwargs,
label=row_label
)
# Plot column principal coordinates
col_coords = self.column_coordinates(X)
ax.scatter(
col_coords[x_component],
col_coords[y_component],
**kwargs,
label=col_label
)
# Add row labels
if show_row_labels:
x = row_coords[x_component]
y = row_coords[y_component]
for i, label in enumerate(row_names):
ax.annotate(label, (x[i], y[i]))
# Add column labels
if show_col_labels:
x = col_coords[x_component]
y = col_coords[y_component]
for i, label in enumerate(col_names):
ax.annotate(label, (x[i], y[i]))
# Legend
ax.legend()
# Text
ax.set_title('Principal coordinates')
ei = self.explained_inertia_
ax.set_xlabel('Component {} ({:.2f}% inertia)'.format(x_component, 100 * ei[x_component]))
ax.set_ylabel('Component {} ({:.2f}% inertia)'.format(y_component, 100 * ei[y_component]))
return ax
|
MaxHalford/prince | prince/ca.py | CA.column_coordinates | python | def column_coordinates(self, X):
utils.validation.check_is_fitted(self, 'V_')
_, _, _, col_names = util.make_labels_and_names(X)
if isinstance(X, pd.SparseDataFrame):
X = X.to_coo()
elif isinstance(X, pd.DataFrame):
X = X.to_numpy()
if self.copy:
X = X.copy()
# Transpose and make sure the rows sum up to 1
if isinstance(X, np.ndarray):
X = X.T / X.T.sum(axis=1)[:, None]
else:
X = X.T / X.T.sum(axis=1)
return pd.DataFrame(
data=X @ sparse.diags(self.row_masses_.to_numpy() ** -0.5) @ self.U_,
index=col_names
) | The column principal coordinates. | train | https://github.com/MaxHalford/prince/blob/714c9cdfc4d9f8823eabf550a23ad01fe87c50d7/prince/ca.py#L118-L141 | [
"def make_labels_and_names(X):\n\n if isinstance(X, pd.DataFrame):\n row_label = X.index.name if X.index.name else 'Rows'\n row_names = X.index.tolist()\n col_label = X.columns.name if X.columns.name else 'Columns'\n col_names = X.columns.tolist()\n else:\n row_label = 'Rows'\n row_names = list(range(X.shape[0]))\n col_label = 'Columns'\n col_names = list(range(X.shape[1]))\n\n return row_label, row_names, col_label, col_names\n"
] | class CA(base.BaseEstimator, base.TransformerMixin):
def __init__(self, n_components=2, n_iter=10, copy=True, check_input=True, random_state=None,
engine='auto'):
self.n_components = n_components
self.n_iter = n_iter
self.copy = copy
self.check_input = check_input
self.random_state = random_state
self.engine = engine
def fit(self, X, y=None):
# Check input
if self.check_input:
utils.check_array(X)
# Check all values are positive
if (X < 0).any().any():
raise ValueError("All values in X should be positive")
_, row_names, _, col_names = util.make_labels_and_names(X)
if isinstance(X, pd.DataFrame):
X = X.to_numpy()
if self.copy:
X = np.copy(X)
# Compute the correspondence matrix which contains the relative frequencies
X = X / np.sum(X)
# Compute row and column masses
self.row_masses_ = pd.Series(X.sum(axis=1), index=row_names)
self.col_masses_ = pd.Series(X.sum(axis=0), index=col_names)
# Compute standardised residuals
r = self.row_masses_.to_numpy()
c = self.col_masses_.to_numpy()
S = sparse.diags(r ** -0.5) @ (X - np.outer(r, c)) @ sparse.diags(c ** -0.5)
# Compute SVD on the standardised residuals
self.U_, self.s_, self.V_ = svd.compute_svd(
X=S,
n_components=self.n_components,
n_iter=self.n_iter,
random_state=self.random_state,
engine=self.engine
)
# Compute total inertia
self.total_inertia_ = np.einsum('ij,ji->', S, S.T)
return self
def transform(self, X):
"""Computes the row principal coordinates of a dataset.
Same as calling `row_coordinates`. In most cases you should be using the same
dataset as you did when calling the `fit` method. You might however also want to included
supplementary data.
"""
utils.validation.check_is_fitted(self, 's_')
if self.check_input:
utils.check_array(X)
return self.row_coordinates(X)
@property
def eigenvalues_(self):
"""The eigenvalues associated with each principal component."""
utils.validation.check_is_fitted(self, 's_')
return np.square(self.s_).tolist()
@property
def explained_inertia_(self):
"""The percentage of explained inertia per principal component."""
utils.validation.check_is_fitted(self, 'total_inertia_')
return [eig / self.total_inertia_ for eig in self.eigenvalues_]
def row_coordinates(self, X):
"""The row principal coordinates."""
utils.validation.check_is_fitted(self, 'V_')
_, row_names, _, _ = util.make_labels_and_names(X)
if isinstance(X, pd.SparseDataFrame):
X = X.to_coo().astype(float)
elif isinstance(X, pd.DataFrame):
X = X.to_numpy()
if self.copy:
X = X.copy()
# Normalise the rows so that they sum up to 1
if isinstance(X, np.ndarray):
X = X / X.sum(axis=1)[:, None]
else:
X = X / X.sum(axis=1)
return pd.DataFrame(
data=X @ sparse.diags(self.col_masses_.to_numpy() ** -0.5) @ self.V_.T,
index=row_names
)
def plot_coordinates(self, X, ax=None, figsize=(6, 6), x_component=0, y_component=1,
show_row_labels=True, show_col_labels=True, **kwargs):
"""Plot the principal coordinates."""
utils.validation.check_is_fitted(self, 's_')
if ax is None:
fig, ax = plt.subplots(figsize=figsize)
# Add style
ax = plot.stylize_axis(ax)
# Get labels and names
row_label, row_names, col_label, col_names = util.make_labels_and_names(X)
# Plot row principal coordinates
row_coords = self.row_coordinates(X)
ax.scatter(
row_coords[x_component],
row_coords[y_component],
**kwargs,
label=row_label
)
# Plot column principal coordinates
col_coords = self.column_coordinates(X)
ax.scatter(
col_coords[x_component],
col_coords[y_component],
**kwargs,
label=col_label
)
# Add row labels
if show_row_labels:
x = row_coords[x_component]
y = row_coords[y_component]
for i, label in enumerate(row_names):
ax.annotate(label, (x[i], y[i]))
# Add column labels
if show_col_labels:
x = col_coords[x_component]
y = col_coords[y_component]
for i, label in enumerate(col_names):
ax.annotate(label, (x[i], y[i]))
# Legend
ax.legend()
# Text
ax.set_title('Principal coordinates')
ei = self.explained_inertia_
ax.set_xlabel('Component {} ({:.2f}% inertia)'.format(x_component, 100 * ei[x_component]))
ax.set_ylabel('Component {} ({:.2f}% inertia)'.format(y_component, 100 * ei[y_component]))
return ax
|
MaxHalford/prince | prince/ca.py | CA.plot_coordinates | python | def plot_coordinates(self, X, ax=None, figsize=(6, 6), x_component=0, y_component=1,
show_row_labels=True, show_col_labels=True, **kwargs):
utils.validation.check_is_fitted(self, 's_')
if ax is None:
fig, ax = plt.subplots(figsize=figsize)
# Add style
ax = plot.stylize_axis(ax)
# Get labels and names
row_label, row_names, col_label, col_names = util.make_labels_and_names(X)
# Plot row principal coordinates
row_coords = self.row_coordinates(X)
ax.scatter(
row_coords[x_component],
row_coords[y_component],
**kwargs,
label=row_label
)
# Plot column principal coordinates
col_coords = self.column_coordinates(X)
ax.scatter(
col_coords[x_component],
col_coords[y_component],
**kwargs,
label=col_label
)
# Add row labels
if show_row_labels:
x = row_coords[x_component]
y = row_coords[y_component]
for i, label in enumerate(row_names):
ax.annotate(label, (x[i], y[i]))
# Add column labels
if show_col_labels:
x = col_coords[x_component]
y = col_coords[y_component]
for i, label in enumerate(col_names):
ax.annotate(label, (x[i], y[i]))
# Legend
ax.legend()
# Text
ax.set_title('Principal coordinates')
ei = self.explained_inertia_
ax.set_xlabel('Component {} ({:.2f}% inertia)'.format(x_component, 100 * ei[x_component]))
ax.set_ylabel('Component {} ({:.2f}% inertia)'.format(y_component, 100 * ei[y_component]))
return ax | Plot the principal coordinates. | train | https://github.com/MaxHalford/prince/blob/714c9cdfc4d9f8823eabf550a23ad01fe87c50d7/prince/ca.py#L143-L199 | [
"def make_labels_and_names(X):\n\n if isinstance(X, pd.DataFrame):\n row_label = X.index.name if X.index.name else 'Rows'\n row_names = X.index.tolist()\n col_label = X.columns.name if X.columns.name else 'Columns'\n col_names = X.columns.tolist()\n else:\n row_label = 'Rows'\n row_names = list(range(X.shape[0]))\n col_label = 'Columns'\n col_names = list(range(X.shape[1]))\n\n return row_label, row_names, col_label, col_names\n",
"def stylize_axis(ax, grid=True):\n\n if grid:\n ax.grid()\n\n ax.xaxis.set_ticks_position('none')\n ax.yaxis.set_ticks_position('none')\n\n ax.axhline(y=0, linestyle='-', linewidth=1.2, color=GRAY['dark'], alpha=0.6)\n ax.axvline(x=0, linestyle='-', linewidth=1.2, color=GRAY['dark'], alpha=0.6)\n\n return ax\n"
] | class CA(base.BaseEstimator, base.TransformerMixin):
def __init__(self, n_components=2, n_iter=10, copy=True, check_input=True, random_state=None,
engine='auto'):
self.n_components = n_components
self.n_iter = n_iter
self.copy = copy
self.check_input = check_input
self.random_state = random_state
self.engine = engine
def fit(self, X, y=None):
# Check input
if self.check_input:
utils.check_array(X)
# Check all values are positive
if (X < 0).any().any():
raise ValueError("All values in X should be positive")
_, row_names, _, col_names = util.make_labels_and_names(X)
if isinstance(X, pd.DataFrame):
X = X.to_numpy()
if self.copy:
X = np.copy(X)
# Compute the correspondence matrix which contains the relative frequencies
X = X / np.sum(X)
# Compute row and column masses
self.row_masses_ = pd.Series(X.sum(axis=1), index=row_names)
self.col_masses_ = pd.Series(X.sum(axis=0), index=col_names)
# Compute standardised residuals
r = self.row_masses_.to_numpy()
c = self.col_masses_.to_numpy()
S = sparse.diags(r ** -0.5) @ (X - np.outer(r, c)) @ sparse.diags(c ** -0.5)
# Compute SVD on the standardised residuals
self.U_, self.s_, self.V_ = svd.compute_svd(
X=S,
n_components=self.n_components,
n_iter=self.n_iter,
random_state=self.random_state,
engine=self.engine
)
# Compute total inertia
self.total_inertia_ = np.einsum('ij,ji->', S, S.T)
return self
def transform(self, X):
"""Computes the row principal coordinates of a dataset.
Same as calling `row_coordinates`. In most cases you should be using the same
dataset as you did when calling the `fit` method. You might however also want to included
supplementary data.
"""
utils.validation.check_is_fitted(self, 's_')
if self.check_input:
utils.check_array(X)
return self.row_coordinates(X)
@property
def eigenvalues_(self):
"""The eigenvalues associated with each principal component."""
utils.validation.check_is_fitted(self, 's_')
return np.square(self.s_).tolist()
@property
def explained_inertia_(self):
"""The percentage of explained inertia per principal component."""
utils.validation.check_is_fitted(self, 'total_inertia_')
return [eig / self.total_inertia_ for eig in self.eigenvalues_]
def row_coordinates(self, X):
"""The row principal coordinates."""
utils.validation.check_is_fitted(self, 'V_')
_, row_names, _, _ = util.make_labels_and_names(X)
if isinstance(X, pd.SparseDataFrame):
X = X.to_coo().astype(float)
elif isinstance(X, pd.DataFrame):
X = X.to_numpy()
if self.copy:
X = X.copy()
# Normalise the rows so that they sum up to 1
if isinstance(X, np.ndarray):
X = X / X.sum(axis=1)[:, None]
else:
X = X / X.sum(axis=1)
return pd.DataFrame(
data=X @ sparse.diags(self.col_masses_.to_numpy() ** -0.5) @ self.V_.T,
index=row_names
)
def column_coordinates(self, X):
"""The column principal coordinates."""
utils.validation.check_is_fitted(self, 'V_')
_, _, _, col_names = util.make_labels_and_names(X)
if isinstance(X, pd.SparseDataFrame):
X = X.to_coo()
elif isinstance(X, pd.DataFrame):
X = X.to_numpy()
if self.copy:
X = X.copy()
# Transpose and make sure the rows sum up to 1
if isinstance(X, np.ndarray):
X = X.T / X.T.sum(axis=1)[:, None]
else:
X = X.T / X.T.sum(axis=1)
return pd.DataFrame(
data=X @ sparse.diags(self.row_masses_.to_numpy() ** -0.5) @ self.U_,
index=col_names
)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.